public int getLongestPath(node[] nodes, int nodeIndex, bool[] visited) { int max = 0; visited[nodeIndex] = true; route[] neighbours = nodes[nodeIndex].neighbours; for (var i = 0; i < neighbours.Length; i++) { if (!visited[neighbours[i].dest]) { int dist = neighbours[i].cost + getLongestPath(nodes, neighbours[i].dest, visited); if (dist > max) { max = dist; } } } visited[nodeIndex] = false; return max; }
node insert(node _node, float x, float y, Transform t) { if (null == _node) { return new node(x, y, t); } if (x >= _node.x && y >= _node.y) { _node.ne = insert(_node.ne, x, y, t); } else if (x >= _node.x && y <= _node.y) { _node.se = insert(_node.se, x, y, t); } else if (x <= _node.x && y <= _node.y) { _node.sw = insert(_node.sw, x, y, t); } else if (x <= _node.x && y >= _node.y) { _node.nw = insert(_node.nw, x, y, t); } return _node; }
// constructor function public CELL(MBR W) { this.current = W; this.next = null; this.prev = null; this.child = null; }
public List<node> getNeighbours(node node) { List<node> neighbours = new List<node> (); for (int x = -1; x<= 1; x++) { for (int y = -1; y<= 1; y++) { if (x == 0 && y == 0) { continue; } int checkX = node.gridX + x; int checkY = node.gridY + y; if(checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY) { neighbours.Add(mainGrid[checkX, checkY]); } } } return neighbours; }
public void allot_category(Form1 form,node[] network,int alturists,int traders,int parasites) { int index; this.f = form; Random r = new Random(); for (int i = 0; i < alturists;) { index = r.Next() % f.no_of_nodes; if (network[index].category == 0) network[index].category = 1; else continue; i++; } for (int i = 0; i < traders;) { index = r.Next()%f.no_of_nodes; if (network[index].category == 0) network[index].category = 2; else continue; i++; } for (int i = 0; i < f.no_of_nodes;i++ ) { if (network[i].category == 0) { network[i].category = 3; network[i].upl_edges = 0; } } }
public Split_info() { mbr = null; newnode = null; xcut = - 1; ycut = - 1; }
private static void collectAllConnected(List<node> nodes, List<edge> edges, node initialNode, out List<node> outNodes, out List<edge> outEdges) { var theseNodes = new List<node> { initialNode }; var theseEdges = new List<edge>(); nodes.Remove(initialNode); while (true) { var edge = edges.FirstOrDefault(e => theseNodes.Contains(e.StartNode)); if (edge != null) { edges.Remove(edge); theseEdges.Add(edge); nodes.Remove(edge.EndNode); if (!theseNodes.Contains(edge.EndNode)) theseNodes.Add(edge.EndNode); } else { edge = edges.FirstOrDefault(e => theseNodes.Contains(e.EndNode)); if (edge == null) break; edges.Remove(edge); theseEdges.Add(edge); nodes.Remove(edge.StartNode); if (!theseNodes.Contains(edge.StartNode)) theseNodes.Add(edge.StartNode); } } outNodes = theseNodes; outEdges = theseEdges; }
public node[] ReadPlaces(string path) { string[] lines = System.IO.File.ReadAllLines(path); int numNodes = Int32.Parse(lines[0]); node[] nodes = new node[numNodes]; List<route>[] routes = new List<route>[numNodes]; for (int i = 0; i < numNodes; i++) { nodes[i] = new node(); routes[i] = new List<route>(); } for (int i = 1; i < lines.Length; i++) { string[] nums = lines[i].Split(' '); if (nums.Length < 3) { break; } int node = Int32.Parse(nums[0]); int neighbour = Int32.Parse(nums[1]); int cost = Int32.Parse(nums[2]); routes[node].Add(new route(neighbour, cost)); } for (int i = 0; i < routes.Length; i++) { nodes[i].neighbours = routes[i].ToArray(); } return nodes; }
//utiltiy function public node<int> GetlastNode(node<int> head) { node<int> last = head; while (last.next != null) last = last.next; return last; }
public Partition_info() { this.R = new node(); this.S = new LIST(); xcut = - 1; ycut = - 1; }
public node(HexBehavior current, node previous, float hDistance, float gDistance) { this.current = current; this.previous = previous; this.hDistance = hDistance; this.gDistance = gDistance; distance = hDistance + gDistance; }
public Edge(node Node1, node Node2) { FromNode = Node1; ToNode = Node2; distance = Driver.distance(Node1.x, Node1.y, Node2.x, Node2.y); xdif = Node2.x - Node1.x; ydif = Node2.y - Node1.y; }
public void print(node<int> head) { while (head != null) { Console.Write(" " + head.data); head = head.next; } }
// Create an empty initialized template public Template() { head = new node(); addedHead = new node(); addedTail = addedHead; firstSection = new section(); tpl = this; fields = new Object[MAX_FIELDS]; sections = new Object[MAX_FIELDS]; }
static void heapify(node[] arr) { int end = arr.Length - 1; int start = (end - 1) / 2; while (start >= 0) { siftDown(arr, start, end); start--; } }
public int getSize(node<int> head) { int count =0; node<int> cur = head; while (cur != null) { cur = cur.next; count++; } return count; }
private void addToList(List<List<string>> solutions, node end_n) { List<string> temp = new List<string>(); while (end_n._last != null) { temp.Add(end_n._word); end_n = end_n._last; } temp.Add(end_n._word); solutions.Add(temp); }
public static void disp(node root) { Console.WriteLine(root.getInst()); int size = 0; List<node> children = new List<node>(); children = root.getAll(ref size); for(int i = 0; i < size; i++) { disp(children[i]); } }
static void heapSort(node[] arr) { heapify(arr);; int end = arr.Length - 1; while (end > 0) { node temp = arr[0]; arr[0] = arr[end]; arr[end] = temp; end--; siftDown(arr, 0, end); } }
// Create using template file public Template(string data) { head = new node(); addedHead = new node(); addedTail = addedHead; firstSection = new section(); tpl = this; fields = new Object[MAX_FIELDS]; sections = new Object[MAX_FIELDS]; data = SECTIONTAG_HEAD + data + SECTIONTAG_TAIL; construct(data, SECTIONTAG_HEAD_LEN, data.Length-SECTIONTAG_TAIL_LEN); }
IEnumerable<node> IGraphService.GetShortestPath(node sourceNode, node destinationNode) { List<node> graphNodes = new List<node>(); using (var factory = new ChannelFactory<IDataService>("DataServiceClient")) { var proxy = factory.CreateChannel(); graphNodes = proxy.GetAllNodes().ToList(); } Graph graph = new Graph(graphNodes); var result = graph.GetShortestPath(sourceNode, destinationNode); return result; }
public bool add(int value) { if (root ==null) { root = new node(value); return true; } else { root.add(value); return true; } }
public void plot_cells(Vector3 start_posi, uint x_cell_height, uint y_cell_width) { int xlen = grid.GetLength (0); int ylen = grid.GetLength (1); for (int x = 0; x < xlen; x++) { for (int y = 0; y< ylen; y++) { Vector3 posi = start_posi; posi.x += x_cell_height * x; posi.z += y_cell_width * y; grid [x, y] = new node (posi, true); } } }
public string add(int value) { if (root ==null) { root = new node(value); return "添加节点为第一个父节点"; } else { root.add(value); return "添加节点成功"; } }
public void compute_h_costs(node[,] grid, node desination) { foreach (node n in grid) { n.extimated_cost = Vector3.Distance (n.position, desination.position); } foreach (node n in grid) { if (n.walkable == false) { closed_nodes.Add (n); } else { open_nodes.Add (n); } } }
public List<node> A_star_find_path(node current, node goal, node[,] grid) { List<node> path = new List<node> (); if (goal.walkable == false) { Debug.Log ("you clicked on a non rechable area"); return path; } compute_h_costs (grid, goal); //pre compute h costs //find all open neighbour nodes arround current node node current_n = current; while (current_n != goal) { if(!path.Contains(current_n)) path.Add (current_n); List<node> neighbours = find_neighbour_nodes (current_n, grid); if(neighbours.Count == 0){ Debug.Log("dead lock"); path.Remove(current_n); //remove it from path open_nodes.Remove(current_n); closed_nodes.Add(current_n); current_n = path[path.Count-2]; // open_nodes.Add(current_n); // if (path.Count > 22 ) { // Debug.Log("No route possible"); // break; // } // break; continue; } node next_node = chose_node (neighbours, current_n); if(next_node == current_n) { //failed to choose because no open neighbour exits Debug.Log("No route possible"); break; } current_n = next_node; open_nodes.Remove(current_n); if(path.Contains(current_n)){ //path reversing node last_entry = path[path.Count-1]; path.Remove(last_entry); open_nodes.Remove(last_entry); //remove last node closed_nodes.Add(last_entry); //add that to closed path } } if(current_n == goal){ Debug.Log("It worked you got it"); } return path; }
// Create using template file public Template(string filename) { head = new node(); addedHead = new node(); addedTail = addedHead; firstSection = new section(); tpl = this; fields = new Object[MAX_FIELDS]; sections = new Object[MAX_FIELDS]; StreamReader re = new StreamReader(filename, System.Text.Encoding.Default); string data = SECTIONTAG_HEAD + re.ReadToEnd() + SECTIONTAG_TAIL; re.Close(); construct(data, SECTIONTAG_HEAD_LEN, data.Length - SECTIONTAG_TAIL_LEN); }
static void FindAdjacentIndex(int[] arr) { node[] n = new node[arr.Length]; for (int i = 0; i < arr.Length; i++) { n[i] = new node(arr[i], i); } heapSort(n); Console.WriteLine("After sorting elements: "); foreach (node ele in n) { Console.WriteLine("val = {0} & index = {1}", ele.val, ele.index); } Console.WriteLine("Adjacent Pairs: "); Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>(); //node cur = n[0]; //int prevIndex = cur.index; //List<int> dup = new List<int>(); //for(int i = 1; i < n.Length; i++) //{ // if (cur.val == n[i].val) // { // dup.Add(n[i].val); // } // else if (dup.Count > 0) // { // foreach (int j in dup) // { // Console.Write("({0}, {1}) ", prevIndex, j); // Console.Write("({0}, {1}) ", j, n[i].index); // } // dup.Clear(); // Console.WriteLine(); // Console.WriteLine("({0}, {1})", cur.index, n[i].index); // prevIndex = cur.index; // cur = n[i]; // } // else // { // Console.WriteLine("({0}, {1})", cur.index, n[i].index); // prevIndex = cur.index; // cur = n[i]; // } }
//Recursively delete alternate nodes public void RemoveAltRecursive(node<int> head) { if (head == null) return; node<int> cur = head; if(cur.next!=null) { node<int> deletenode = cur.next; cur.next = deletenode.next; deletenode = null; } RemoveAltRecursive(cur.next); }
public int add(UInt32 childIst) { node child = new node(childIst); try { this.children.Add(child); size++; return 0; } catch { return 1; } }
/// <summary> /// Invoked when <see cref="ToEntity"/> operation is about to return. /// </summary> /// <param name="entity"><see cref="node"/> converted from <see cref="nodeDto"/>.</param> static partial void OnEntity(this nodeDto dto, node entity);
protected override void SolveInstance(Grasshopper.Kernel.IGH_DataAccess DA) { if (!DA.GetData(6, ref v)) { return; } if (!FriedChiken.isInitialized) { GH_Point[] pointList = new GH_Point[8]; List <GH_Point> tmpPointList = new List <GH_Point>(); int[] nEdgeNodes = new int[_dim]; DA.GetData(0, ref pointList[0]); DA.GetData(1, ref pointList[1]); DA.GetData(2, ref pointList[2]); DA.GetData(3, ref pointList[3]); DA.GetData(4, ref nEdgeNodes[0]); DA.GetData(5, ref nEdgeNodes[1]); for (int i = 0; i < _dim; i++) { if (nEdgeNodes[i] < 2) { AddRuntimeMessage(Grasshopper.Kernel.GH_RuntimeMessageLevel.Error, "Integers must be greater than or equal to 2"); return; } } //点群生成 double[,] wt = mikity.MathUtil.bicubic(_dim, nEdgeNodes); nNewNodes = wt.GetLength(0); mikity.NumericalMethodHelper.particle[] particles = new mikity.NumericalMethodHelper.particle[nNewNodes]; for (int i = 0; i < nNewNodes; i++) { particles[i] = new particle(0, 0, 0); for (int j = 0; j < _nNodes; j++) { particles[i][0] += pointList[j].Value.X * wt[i, j]; particles[i][1] += pointList[j].Value.Y * wt[i, j]; particles[i][2] += pointList[j].Value.Z * wt[i, j]; } } pS = new GH_particleSystem(particles); node[] lNodes = new node[nNewNodes]; for (int i = 0; i < nNewNodes; i++) { lNodes[i] = new node(i); lNodes[i].copyFrom(pS.Value.particles); } nF = new nodalForce(v.X, v.Y, v.Z); for (int i = 0; i < nNewNodes; i++) { nF.addNode(lNodes[i]); } pS.Value.addObject(nF); lGeometry.Clear(); lGeometry2.Clear(); for (int i = 0; i < nNewNodes; i++) { lGeometry.Add(new Rhino.Geometry.Line(new Rhino.Geometry.Point3d(particles[i][0], particles[i][1], particles[i][2]), v)); } this.DVPW = GetDVPW(lGeometry); pS.DVPW = GetDVPW(lGeometry2); pS.UPGR = GetUPGR(lGeometry2); } else { nF.forceX = v.X; nF.forceY = v.Y; nF.forceZ = v.Z; } DA.SetData(0, pS); }
public IActionResult Get() { int systemsCount = js.All <RDSystem>().Count(); int releaseCount = js.All <Release>().Count(); int changeSetCount = js.All <ChangeSet>().Count(); List <Table> tableRef = js.All <Table>(); int tableCount = tableRef.Count(); List <string> tableList = new List <string>(); tableRef.ForEach(e => tableList.Add(e.ID)); node root = new node() { name = "RDM", size = 0, level = "0", children = new List <node>() }; node sysnode; node relnode; node csnode; foreach (RDSystem s in js.All <RDSystem>()) { sysnode = new node() { name = s.Name, size = 150, level = "1", children = new List <node>() }; foreach (Release r in js.All <Release>().Where(r => r.SystemID.Equals(s.ID))) { relnode = new node() { name = r.Name, size = 100, level = "2", children = new List <node>() }; foreach (ChangeSet c in js.All <ChangeSet>().Where(cs => cs.ReleaseID.Equals(r.ID))) { csnode = new node() { name = c.Name, size = c.Changes.Count, level = "3", }; relnode.children.Add(csnode); } relnode.size = relnode.children.Count; sysnode.children.Add(relnode); } sysnode.size = sysnode.children.Count; root.children.Add(sysnode); } Dictionary <string, Dictionary <string, string> > returnobj = new Dictionary <string, Dictionary <string, string> >(); var statusObject = new { SystemCount = systemsCount, ReleaseCount = releaseCount, ChangeSetCount = changeSetCount, TableCount = tableCount, status = root, TableList = tableList }; return(StatusCode(201, statusObject)); }
public void extractData() { string[] row; node noeud; using (SqlCommand sc = new SqlCommand(sqlFormat(), cnn)) { using (SqlDataReader dr = sc.ExecuteReader()) { while (dr.Read()) { noeud = new node(); noeud.Reference = dr.GetString(0); noeud.designation = dr.GetString(1); noeud.numSerie = dr.GetString(2); noeud.peremption = dr.GetDateTime(3); noeud.qteStockReel = dr.GetDecimal(4); noeud.qteStockDispo = dr.GetDecimal(5); //noeud.qteVendue = dr.GetDecimal(6); noeud.prixVen = articleInfo(noeud.Reference); noeud.valorisation = noeud.prixVen * noeud.qteStockReel; noeud.depot = dr.GetString(6); liste.Add(noeud); row = new string[dataGridView1.ColumnCount]; for (int j = 0; j < dataGridView1.ColumnCount - 2; j++) { if (j <= 2) { row[j] = dr.GetString(j); } else if (j == 3) { row[j] = dr.GetDateTime(j).ToString("dd/MM/yyyy"); } else { row[j] = formatMoney(DecimalToString(dr.GetDecimal(j))); } } row[dataGridView1.ColumnCount - 2] = DecimalToString(noeud.valorisation); row[dataGridView1.ColumnCount - 1] = noeud.depot; if (dataGridView1.InvokeRequired) { dataGridView1.Invoke(new Action(delegate() { dataGridView1.Rows.Add(row); })); } else { dataGridView1.Rows.Add(row); } } if (dataGridView1.InvokeRequired) { dataGridView1.Invoke(new Action(delegate() { if (dataGridView1.Rows.Count > 0) { dataGridView1.ClearSelection(); } })); } else { if (dataGridView1.Rows.Count > 0) { dataGridView1.ClearSelection(); } } } } }
public void segment_hit_test(node node_a, node node_b) { double[] a = point_to_array(node_a.next_position); double[] b = point_to_array(node_b.next_position); bool[,] plane_crossed = new bool[3, 2]; bool plane_was_crossed = false; for (int axis = 0; axis < 3; axis++) { for (int sign = 0; sign < 2; sign++) { plane_crossed[axis, sign] = (a[axis] > hit_test_extents[axis, sign]) ^ (b[axis] > hit_test_extents[axis, sign]); plane_was_crossed |= plane_crossed[axis, sign]; } } if (!plane_was_crossed) { return; } double[] v = new double[3]; for (int n = 0; n < 3; n++) { v[n] = b[n] - a[n]; // construct vector from a to b } double smallest_s = double.MaxValue; // smallest vector length of a valid intersection bool side_was_intersected = false; int smallest_axis = 0; int smallest_sign = 0; for (int axis = 0; axis < 3; axis++) { if (v[axis] == 0) // the vector is 'this axis'-invariant { continue; // use epsilon here } for (int sign = 0; sign < 2; sign++) { if (plane_crossed[axis, sign]) { double s = (hit_test_extents[axis, sign] - a[axis]) / v[axis]; // vector scaler (scalar) to add to a to get i, the intersection double[] i = new double[3]; for (int n = 0; n < 3; n++) { i[n] = a[n] + (s * v[n]); // now i = the plane's point of intersection } if (((i[(axis + 1) % 3] > hit_test_extents[(axis + 1) % 3, 0]) ^ (i[(axis + 1) % 3] > hit_test_extents[(axis + 1) % 3, 1])) && ((i[(axis + 2) % 3] > hit_test_extents[(axis + 2) % 3, 0]) ^ (i[(axis + 2) % 3] > hit_test_extents[(axis + 2) % 3, 1]))) // intersection on a box side { side_was_intersected = true; if (s < smallest_s) // smallest s corresponds to first collision { smallest_s = s; smallest_axis = axis; smallest_sign = sign; } } } } } if (!side_was_intersected) { return; } double offset; if (smallest_sign == 0) { offset = -hit_offset; } else { offset = hit_offset; } switch (smallest_axis) { case 0: node_a.velocity.X = 0; node_a.next_position.X = hit_test_extents[smallest_axis, smallest_sign] + offset; break; case 1: node_a.velocity.Y = 0; node_a.next_position.Y = hit_test_extents[smallest_axis, smallest_sign] + offset; break; case 2: node_a.velocity.Z = 0; node_a.next_position.Z = hit_test_extents[smallest_axis, smallest_sign] + offset; break; } }
public List <node> NeighbourNodes(node OriginNode) { Vector3Int vector; List <node> NeighboursList = new List <node>(); if (OriginNode.position[1] % 2 == 0 || OriginNode.position[1] == 0) { if (OriginNode.position[1] + 1 <= sizeOfMap && OriginNode.position[0] - 1 >= 0) { vector = new Vector3Int(OriginNode.position[0] - 1, OriginNode.position[1] + 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("even left up"); }// even left up node if (OriginNode.position[1] + 1 <= sizeOfMap) { vector = new Vector3Int(OriginNode.position[0], OriginNode.position[1] + 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("even right up"); }//even right up node if (OriginNode.position[0] - 1 >= 0) { vector = new Vector3Int(OriginNode.position[0] - 1, OriginNode.position[1], OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("even left"); }//even left node if (OriginNode.position[0] + 1 <= sizeOfMap) { vector = new Vector3Int(OriginNode.position[0] + 1, OriginNode.position[1], OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("even right"); }//even right node if (OriginNode.position[1] - 1 >= 0 && OriginNode.position[0] - 1 >= 0) { vector = new Vector3Int(OriginNode.position[0] - 1, OriginNode.position[1] - 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("even left down"); }//even left down node if (OriginNode.position[1] - 1 >= 0) { vector = new Vector3Int(OriginNode.position[0], OriginNode.position[1] - 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("even right down"); } //even right down node } //even else { if (OriginNode.position[1] + 1 <= sizeOfMap) { vector = new Vector3Int(OriginNode.position[0], OriginNode.position[1] + 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("odd left up"); }//odd left up node if (OriginNode.position[0] + 1 <= sizeOfMap && OriginNode.position[1] + 1 <= sizeOfMap) { vector = new Vector3Int(OriginNode.position[0] + 1, OriginNode.position[1] + 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("odd right up"); }//odd right up node if (OriginNode.position[0] - 1 >= 0) { vector = new Vector3Int(OriginNode.position[0] - 1, OriginNode.position[1], OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("odd left"); }//odd left node if (OriginNode.position[0] + 1 <= sizeOfMap) { vector = new Vector3Int(OriginNode.position[0] + 1, OriginNode.position[1], OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("odd right"); }//odd right node if (OriginNode.position[1] - 1 >= 0) { vector = new Vector3Int(OriginNode.position[0], OriginNode.position[1] - 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("odd left down"); }//odd left down node if (OriginNode.position[1] - 1 >= 0 && OriginNode.position[0] + 1 <= sizeOfMap) { vector = new Vector3Int(OriginNode.position[0] + 1, OriginNode.position[1] - 1, OriginNode.position[2]); if (tilemap.GetTile(vector) == tiles[0]) { NeighboursList.Add(new node(vector, false, "water", 9999)); } else if (tilemap.GetTile(vector) == tiles[1]) { NeighboursList.Add(new node(vector, true, "grass", 1)); } else if (tilemap.GetTile(vector) == tiles[2]) { NeighboursList.Add(new node(vector, true, "mountain", 1.2f)); } Debug.Log("odd right down"); } //odd right down node } //odd TestNei = NeighboursList; return(NeighboursList); }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter; IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter); IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber)); // get the name of the feature dataset int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\"); string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; System.Xml.XmlWriter xmlWriter = null; try { xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings); } catch (Exception ex) { message.AddError(120021, ex.Message); return; } xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("osm"); // start the osm root node xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute // write all the nodes // use a feature search cursor to loop through all the known points and write them out as osm node IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer; if (osmFeatureClasses == null) { message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name)); return; } IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt"); if (osmPointFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt")); return; } // check the extension of the point feature class to determine its version int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion(); IFeatureCursor searchCursor = null; System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg")); int pointCounter = 0; string nodesExportedMessage = String.Empty; // collect the indices for the point feature class once int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID"); int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset"); int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion"); int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid"); int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser"); int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp"); int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible"); int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags"); using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPointFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node)); IFeature currentFeature = searchCursor.NextFeature(); IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == true) { // convert the found point feature into a osm node representation to store into the OSM XML file node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion); pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty); // increase the point counter to later status report pointCounter++; currentFeature = searchCursor.NextFeature(); } else { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loader so far nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); return; } } } nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); // next loop through the line and polygon feature classes to export those features as ways // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln"); if (osmLineFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln")); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg")); // as we are looping through the line and polygon feature classes let's collect the multi-part features separately // as they are considered relations in the OSM world List<relation> multiPartElements = new List<relation>(); System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way)); int lineCounter = 0; int relationCounter = 0; string waysExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmLineFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID"); int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset"); int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion"); int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid"); int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser"); int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp"); int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible"); int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags"); int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers"); IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply"); IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace; if (osmPolygonFeatureClass == null) { message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply")); return; } using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPolygonFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID"); int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset"); int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion"); int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid"); int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser"); int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp"); int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible"); int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags"); int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); // now let's go through the relation table message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg")); ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation"); if (relationTable == null) { message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation")); return; } System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation)); string relationsExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { ICursor rowCursor = relationTable.Search(null, false); comReleaser.ManageLifetime(rowCursor); IRow currentRow = rowCursor.NextRow(); // collect the indices for the relation table once int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID"); int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset"); int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion"); int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid"); int relationUserFieldIndex = relationTable.Fields.FindField("osmuser"); int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp"); int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible"); int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags"); int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentRow != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion); relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty); // increase the line counter for later status report relationCounter++; currentRow = rowCursor.NextRow(); } } // lastly let's serialize the collected multipart-geometries back into relation elements foreach (relation currentRelation in multiPartElements) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); return; } relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty); relationCounter++; } relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document } catch (Exception ex) { message.AddError(11111, ex.StackTrace); message.AddError(120026, ex.Message); } }
//Dictionary<string, Texture2D> diffuseTextures = new Dictionary<string, Texture2D>(); //Dictionary<string, Texture2D> specularTextures = new Dictionary<string, Texture2D>(); //Dictionary<string, geometry> geometryLibrary = new Dictionary<string, geometry>(); //List<node> nodeList = new List<node>(); //this is very similar to the blockmesher function. void CollectModel(MapDataStore.Tile tile, MeshLayer layer, DFCoord pos) { if (layer == MeshLayer.Collision) { return; } #region Mesh Selection MeshContent meshContent = null; switch (layer) { case MeshLayer.GrowthMaterial: case MeshLayer.GrowthMaterial1: case MeshLayer.GrowthMaterial2: case MeshLayer.GrowthMaterial3: case MeshLayer.GrowthCutout: case MeshLayer.GrowthCutout1: case MeshLayer.GrowthCutout2: case MeshLayer.GrowthCutout3: case MeshLayer.GrowthTransparent: case MeshLayer.GrowthTransparent1: case MeshLayer.GrowthTransparent2: case MeshLayer.GrowthTransparent3: { switch (tile.tiletypeMaterial) { case TiletypeMaterial.PLANT: case TiletypeMaterial.ROOT: case TiletypeMaterial.TREE_MATERIAL: case TiletypeMaterial.MUSHROOM: if (!ContentLoader.Instance.GrowthMeshConfiguration.GetValue(tile, layer, out meshContent)) { return; } break; default: return; } } break; //case MeshLayer.BuildingMaterial: //case MeshLayer.NoMaterialBuilding: //case MeshLayer.BuildingMaterialCutout: //case MeshLayer.NoMaterialBuildingCutout: //case MeshLayer.BuildingMaterialTransparent: //case MeshLayer.NoMaterialBuildingTransparent: // { // if (tile.buildingType == default(BuildingStruct)) // return; // if (!ContentLoader.Instance.BuildingMeshConfiguration.GetValue(tile, layer, out meshContent)) // return; // } // break; default: { if (!ContentLoader.Instance.TileMeshConfiguration.GetValue(tile, layer, out meshContent)) { return; } } break; } if (!meshContent.MeshData.ContainsKey(layer)) { return; } #endregion node tileNode = new node(); tileNode.id = string.Format("Tile[{0},{1},{2}]_{3}", pos.x, pos.y, pos.z, layer); tileNode.Items = new object[] { COLLADA.ConvertMatrix(Matrix4x4.TRS( GameMap.DFtoUnityCoord(pos), meshContent.GetRotation(tile), Vector3.one)) }; tileNode.ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.matrix }; //string geometryName = "Mesh-" + meshContent.UniqueIndex; //if (!geometryLibrary.ContainsKey(geometryName)) //{ // geometryLibrary[geometryName] = COLLADA.MeshToGeometry(meshContent.MeshData[layer], geometryName); //} //instance_geometry geometryInstance = new instance_geometry(); //geometryInstance.url = "#" + geometryLibrary[geometryName].id; //tileNode.instance_geometry = new instance_geometry[] { geometryInstance }; //nodeList.Add(tileNode); //return; //----------------------------------------------------------- //Put normal map stuff here! Remember! //----------------------------------------------------------- //string patternName = "Tex-"; //Texture2D tiletexture = null; //TextureContent textureContent; //if (ContentLoader.Instance.MaterialTextureConfiguration.GetValue(tile, layer, out textureContent)) //{ // tiletexture = textureContent.Texture; // patternName += textureContent.UniqueIndex; //} //else patternName += "#"; //patternName += "-#"; //Color color = Color.grey; //ColorContent colorContent; //if (ContentLoader.Instance.ColorConfiguration.GetValue(tile, layer, out colorContent)) //{ // color = colorContent.color; //} //patternName += string.Format("{0:X2}{1:X2}{2:X2}", ((Color32)color).r, ((Color32)color).g, ((Color32)color).b); //if (diffuseTextures.ContainsKey(patternName)) // return; //Color neutralSpec = new Color(0.04f, 0.04f, 0.04f); //Texture2D outputDiffuse; //Texture2D outputSpec; //if (tiletexture != null) //{ // outputDiffuse = new Texture2D(tiletexture.width, tiletexture.height); // outputSpec = new Texture2D(tiletexture.width, tiletexture.height); // Color[] colors = tiletexture.GetPixels(); // Color[] specs = new Color[colors.Length]; // for (int i = 0; i < colors.Length; i++) // { // var diffuseColor = OverlayBlend(colors[i], color); // diffuseColor.a = 1; // colors[i] = Color.Lerp(Color.black, diffuseColor, color.a); // specs[i] = Color.Lerp(diffuseColor, neutralSpec, color.a); // } // outputDiffuse.SetPixels(colors); // outputSpec.SetPixels(specs); //} //else //{ // outputDiffuse = ContentLoader.CreateFlatTexture(color); // outputSpec = ContentLoader.CreateFlatTexture(neutralSpec); //} //outputDiffuse.name = patternName + "_Diffuse"; //outputSpec.name = patternName + "_Specular"; //diffuseTextures[patternName] = outputDiffuse; //specularTextures[patternName] = outputSpec; }
public bool BePrinted = false; //是否已輸出至MST public Edge(node node1, node node2, int value) { _node1 = node1; _node2 = node2; _value = value; } //constructor
public void Export(string filePath) { PalletProperties palletProperties = _palletSolution.Analysis.PalletProperties; COLLADA model = new COLLADA(); // asset model.asset = new asset() { created = DateTime.Now, modified = DateTime.Now }; model.asset.keywords = "StackBuilder Pallet Case"; model.asset.title = _palletSolution.Title; model.asset.unit = new assetUnit() { name = "millimeters", meter = 0.001 }; model.asset.up_axis = UpAxisType.Z_UP; library_images images = new library_images(); library_materials materials = new library_materials(); library_effects effects = new library_effects(); library_geometries geometries = new library_geometries(); library_nodes nodes = new library_nodes(); library_cameras cameras = new library_cameras(); library_animations animations = new library_animations(); library_visual_scenes scenes = new library_visual_scenes(); COLLADAScene colladaScene = new COLLADAScene(); model.Items = new Object[] { images, materials, effects, geometries, nodes, cameras, animations, scenes }; model.scene = colladaScene; // colors and materials List <effect> listEffects = new List <effect>(); List <material> listMaterials = new List <material>(); List <image> listImages = new List <image>(); // effects effect effectPallet; material materialPallet; CreateMaterial(palletProperties.Color, null, null, "Pallet", out effectPallet, out materialPallet); listEffects.Add(effectPallet); listMaterials.Add(materialPallet); Box box = new Box(0, _palletSolution.Analysis.BProperties); // build list of effects / materials / images uint faceIndex = 0; foreach (Face face in box.Faces) { // build texture image if any string textureName = null; if (face.HasBitmap) { textureName = string.Format("textureFace_{0}", faceIndex); string texturePath = System.IO.Path.Combine( System.IO.Path.GetDirectoryName(filePath) , textureName + ".jpg"); double dimX = 0.0, dimY = 0.0; switch (faceIndex) { case 0: dimX = box.Width; dimY = box.Height; break; case 1: dimX = box.Width; dimY = box.Height; break; case 2: dimX = box.Length; dimY = box.Height; break; case 3: dimX = box.Length; dimY = box.Height; break; case 4: dimX = box.Length; dimY = box.Width; break; case 5: dimX = box.Length; dimY = box.Width; break; default: break; } face.ExtractFaceBitmap(dimX, dimY, _bmpWidth, texturePath); // create image listImages.Add( new image() { id = textureName + ".jpg", name = textureName + ".jpg", Item = @".\" + textureName + @".jpg" } ); } material materialCase; effect effectCase; CreateMaterial(face.ColorFill, textureName, "0", string.Format("Case{0}", faceIndex), out effectCase, out materialCase); listEffects.Add(effectCase); listMaterials.Add(materialCase); ++faceIndex; } // add to image list images.image = listImages.ToArray(); // case lines material effect effectCaseLines; material materialCaseLines; CreateMaterial(Color.Black, null, null, "CaseLines", out effectCaseLines, out materialCaseLines); listEffects.Add(effectCaseLines); listMaterials.Add(materialCaseLines); effects.effect = listEffects.ToArray(); materials.material = listMaterials.ToArray(); // geometries geometry geomPallet = new geometry() { id = "palletGeometry", name = "palletGeometry" }; geometry geomCase = new geometry() { id = "caseGeometry", name = "caseGeometry" }; geometries.geometry = new geometry[] { geomPallet, geomCase }; // pallet mesh meshPallet = CreatePalletMesh(palletProperties); geomPallet.Item = meshPallet; // case mesh meshCase = CreateCaseMesh(_palletSolution.Analysis.BProperties as BoxProperties); geomCase.Item = meshCase; // library_animations animation animationMain = new animation() { id = "animationMain_ID", name = "animationMain" }; animations.animation = new animation[] { animationMain }; List <object> listAnimationSource = new List <object>(); // library_visual_scenes visual_scene mainScene = new visual_scene() { id = "MainScene", name = "MainScene" }; scenes.visual_scene = new visual_scene[] { mainScene }; List <node> sceneNodes = new List <node>(); sceneNodes.Add(new node() { id = "PalletNode", name = "PalletNode", instance_geometry = new instance_geometry[] { new instance_geometry() { url = "#palletGeometry", bind_material = new bind_material() { technique_common = new instance_material[] { new instance_material() { symbol = "materialPallet", target = string.Format("#{0}", materialPallet.id) } } } } } }); uint caseIndex = 0; foreach (ILayer layer in _palletSolution) { Layer3DBox bLayer = layer as Layer3DBox; if (null == bLayer) { continue; } foreach (BoxPosition bp in bLayer) { Vector3D translation = bp.Position; Vector3D rotations = bp.Transformation.Rotations; node caseNode = new node() { id = string.Format("CaseNode_{0}_ID", caseIndex), name = string.Format("CaseNode_{0}", caseIndex), ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.translate, ItemsChoiceType2.rotate, ItemsChoiceType2.rotate, ItemsChoiceType2.rotate }, Items = new object[] { new TargetableFloat3() { Values = new double[] { translation.X, translation.Y, translation.Z }, sid = "t", }, new rotate() { Values = new double[] { 1.0, 0.0, 0.0, rotations.X }, sid = "rx" }, new rotate() { Values = new double[] { 0.0, 1.0, 0.0, rotations.Y }, sid = "ry" }, new rotate() { Values = new double[] { 0.0, 0.0, 1.0, rotations.Z }, sid = "rz" } }, instance_geometry = new instance_geometry[] { new instance_geometry() { url = "#caseGeometry", bind_material = new bind_material() { technique_common = new instance_material[] { new instance_material() { symbol = "materialCase0", target = "#material_Case0_ID" }, new instance_material() { symbol = "materialCase1", target = "#material_Case1_ID" }, new instance_material() { symbol = "materialCase2", target = "#material_Case2_ID" }, new instance_material() { symbol = "materialCase3", target = "#material_Case3_ID" }, new instance_material() { symbol = "materialCase4", target = "#material_Case4_ID" }, new instance_material() { symbol = "materialCase5", target = "#material_Case5_ID" }, new instance_material() { symbol = "materialCaseLines", target = "#material_CaseLines_ID" } } } } } }; sceneNodes.Add(caseNode); // animations CreateAnimation(caseIndex, (uint)_palletSolution.CaseCount, listAnimationSource, bp); // increment case index ++caseIndex; } } // add nodes mainScene.node = sceneNodes.ToArray(); animationMain.Items = listAnimationSource.ToArray(); // library_cameras camera cameraCamera = new camera() { id = "Camera-Camera", name = "Camera-Camera" }; cameraOpticsTechnique_commonPerspective cameraPerspective = new cameraOpticsTechnique_commonPerspective() { znear = new TargetableFloat() { sid = "znear", Value = 1.0 }, zfar = new TargetableFloat() { sid = "zfar", Value = 10000.0 } }; cameraCamera.optics = new cameraOptics() { technique_common = new cameraOpticsTechnique_common() { Item = cameraPerspective } }; cameras.camera = new camera[] { cameraCamera }; // colladaScene colladaScene.instance_visual_scene = new InstanceWithExtra() { url = "#MainScene" }; model.Save(filePath); model.Save(System.IO.Path.ChangeExtension(filePath, "xml")); }
public void add(string value) { node currentNode = Root; add(currentNode, value, 0); }
public tree() // this rootValue is ignored { Root = new node(ROOTVALUE); }
public void DeselectNode() { selectedNode = null; nodeUI.Hide(); }
public void setNode(node node) { this.node = node; return; }
public void delete(int _key) { if (root == null) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("No elements in the tree"); Console.ForegroundColor = ConsoleColor.DarkCyan; return; } node current = root; node parent = null; while (current != null) { if (current.key == _key) { break; } parent = current; if (_key < current.key) { current = current.left; } else if (_key > current.key) { current = current.right; } } if (current == null) { Console.WriteLine("element is not present in the tree"); return; } //case element has 2 children //find in order sucessor and its parents node temp, temp1; if (current.right != null && current.left != null) { temp1 = current; temp = current.right; while (temp.left != null) { temp1 = temp; temp = temp.left; } current.key = temp.key; current = temp; parent = temp1; Console.WriteLine("deleted"); } //other case 1 or no child node temp2; if (current.left != null) { temp2 = current.left; } else { temp2 = current.right; } if (parent == null) { root = temp2; } else if (current == parent.left) { parent.left = temp2; } else { parent.right = temp2; } }
// Place a new key in the key cache and if this key displaced a existing key, // then return that key, else return null. public string Put(string key) { Debug.Assert(key != null, "Section is null"); Debug.Assert(cache.Count < max, "keyCache size blew up"); node tmp; if (cache.TryGetValue(key, out tmp)) // If the value exists ... { if ((tmp == head) || (cache.Count == 1)) { return(null); } Debug.Assert(cache.Count > 1, "Cache unexpectedly empty"); if (tmp == tail) // If the last element ... { tail = tail.prev; // The delete the last element, } else // Else delete the element (which is in the middle somewhere) { tmp.prev.next = tmp.next; tmp.next.prev = tmp.prev; } // And finally move it to the head. tmp.prev = null; tmp.next = head; head.prev = tmp; // THIS WAS THE BUG - This line was missing! head = tmp; } else // If the element does not exists ... { tmp = new node(key); cache.Add(key, tmp); // Add that element ... if (head == null) // If list is empty, initialize head & tail. { Debug.Assert(tail == null, "Tail not null, when head is null"); head = tail = tmp; } else // If list is empty, add the element in head. { Debug.Assert(tail != null, "Tail should not be null, when head is null"); tmp.next = head; head.prev = tmp; head = tmp; } Debug.Assert(cache.Count <= max, "keyCache size blew up"); // If Cache has exceeded the max limit, then delete the last element and // set it to Key Out and also return true (Othwise false). if (cache.Count == max) { Debug.Assert(tail != null, "Tail should not be null"); Debug.Assert(head != null, "Head should not be null"); string keyOut = tail.key; cache.Remove(keyOut); tail = tail.prev; return(keyOut); } } return(null); }
private node ConvertPointFeatureToOSMNode(IFeature currentFeature, IWorkspace featureWorkspace, int tagsFieldIndex, int osmIDFieldIndex, int changesetIDFieldIndex, int osmVersionFieldIndex, int userIDFieldIndex, int userNameFieldIndex, int timeStampFieldIndex, int visibleFieldIndex, int extensionVersion) { if (currentFeature == null) throw new ArgumentNullException("currentFeature"); node osmNode = new node(); object featureValue = DBNull.Value; if (currentFeature.Shape.IsEmpty == false) { IPoint wgs84Point = currentFeature.Shape as IPoint; wgs84Point.Project(m_wgs84); NumberFormatInfo exportCultureInfo = new CultureInfo("en-US", false).NumberFormat; exportCultureInfo.NumberDecimalDigits = 6; osmNode.lat = wgs84Point.Y.ToString("N", exportCultureInfo); osmNode.lon = wgs84Point.X.ToString("N", exportCultureInfo); Marshal.ReleaseComObject(wgs84Point); } if (osmIDFieldIndex != -1) { osmNode.id = Convert.ToString(currentFeature.get_Value(osmIDFieldIndex)); } if (changesetIDFieldIndex != -1) { featureValue = currentFeature.get_Value(changesetIDFieldIndex); if (featureValue != DBNull.Value) { osmNode.changeset = Convert.ToString(currentFeature.get_Value(changesetIDFieldIndex)); } } if (osmVersionFieldIndex != -1) { featureValue = currentFeature.get_Value(osmVersionFieldIndex); if (featureValue != DBNull.Value) { osmNode.version = Convert.ToString(featureValue); } } if (userIDFieldIndex != -1) { featureValue = currentFeature.get_Value(userIDFieldIndex); if (featureValue != DBNull.Value) { osmNode.uid = Convert.ToString(featureValue); } } if (userNameFieldIndex != -1) { featureValue = currentFeature.get_Value(userNameFieldIndex); if (featureValue != DBNull.Value) { osmNode.user = Convert.ToString(featureValue); } } if (timeStampFieldIndex != -1) { featureValue = currentFeature.get_Value(timeStampFieldIndex); if (featureValue != DBNull.Value) { osmNode.timestamp = Convert.ToDateTime(featureValue).ToUniversalTime().ToString("u"); } } if (visibleFieldIndex != -1) { featureValue = currentFeature.get_Value(visibleFieldIndex); if (featureValue != DBNull.Value) { try { osmNode.visible = (nodeVisible)Enum.Parse(typeof(nodeVisible), Convert.ToString(featureValue)); } catch { osmNode.visible = nodeVisible.@true; } } } if (tagsFieldIndex > -1) { tag[] tags = null; tags = _osmUtility.retrieveOSMTags((IRow)currentFeature, tagsFieldIndex, featureWorkspace); if (tags.Length != 0) { osmNode.tag = tags; } } return osmNode; }
protected override void SolveInstance(Grasshopper.Kernel.IGH_DataAccess DA) { if (!DA.GetData(3, ref v)) { return; } if (!FriedChiken.isInitialized) { Rhino.Geometry.Surface s = null; if (!DA.GetData(0, ref s)) { return; } Rhino.Geometry.Interval uDomain = s.Domain(0); Rhino.Geometry.Interval vDomain = s.Domain(1); int[] nEdgeNodes = new int[_dim]; DA.GetData(1, ref nEdgeNodes[0]); DA.GetData(2, ref nEdgeNodes[1]); for (int i = 0; i < _dim; i++) { if (nEdgeNodes[i] < 2) { AddRuntimeMessage(Grasshopper.Kernel.GH_RuntimeMessageLevel.Error, "Integers must be greater than or equal to 2"); return; } } newNodes.Clear(); for (int i = 0; i < nEdgeNodes[1]; i++) { for (int j = 0; j < nEdgeNodes[0]; j++) { newNodes.Add(s.PointAt(uDomain.T0 + (uDomain.T1 - uDomain.T0) / (nEdgeNodes[0] - 1) * j, vDomain.T0 + (vDomain.T1 - vDomain.T0) / (nEdgeNodes[1] - 1) * i)); } } int nNewNodes = newNodes.Count; mikity.NumericalMethodHelper.particle[] particles = new mikity.NumericalMethodHelper.particle[nNewNodes]; for (int i = 0; i < nNewNodes; i++) { particles[i] = new mikity.NumericalMethodHelper.particle(newNodes[i][0], newNodes[i][1], newNodes[i][2]); } pS = new GH_particleSystem(particles); node[] lNodes = new node[nNewNodes]; for (int i = 0; i < nNewNodes; i++) { lNodes[i] = new node(i); lNodes[i].copyFrom(pS.Value.particles); } nF = new nodalForce(v.X, v.Y, v.Z); for (int i = 0; i < nNewNodes; i++) { nF.addNode(lNodes[i]); } pS.Value.addObject(nF); lGeometry = new Rhino.Geometry.Point3d[nNewNodes]; for (int i = 0; i < nNewNodes; i++) { lGeometry[i] = new Rhino.Geometry.Point3d(particles[i][0], particles[i][1], particles[i][2]); } } else { nF.forceX = v.X; nF.forceY = v.Y; nF.forceZ = v.Z; } DA.SetData(0, pS); }
public node(string k) { key = k; next = null; prev = null; }
public static controller FindControllerFromNode(node daeNode, library_controllers controllers) { string mesh_id = daeNode.instance_controller[0].url.Trim('#'); return(Array.Find(controllers.controller, x => x.id == mesh_id)); }
// Update is called once per frame public List <node> GetNeigbours(node Node) { List <node> ret = new List <node>(); if (Node.diagonal_move) { for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if (x == 0 && y == 0) { continue; } int checkX = Node.GridX + x; if (checkX < 0 || checkX >= GridSizeX) { continue; } int checkY = Node.GridY + y; if (checkY < 0 || checkY >= GridSizeY) { continue; } node r = Grid[checkX, checkY]; //if(Mathf.Abs(Node.tile.Height - r.tile.Height) > MaxLeap) // continue; ret.Add(r); } } } else { for (int x = -1; x <= 1; x++) { if (x == 0) { continue; } int checkX = Node.GridX + x; if (checkX < 0 || checkX >= GridSizeX) { continue; } ret.Add(Grid[checkX, Node.GridY]); } for (int y = -1; y <= 1; y++) { if (y == 0) { continue; } int checkY = Node.GridY + y; if (checkY < 0 || checkY >= GridSizeY) { continue; } ret.Add(Grid[Node.GridX, checkY]); } } return(ret); }
_visits.Set <T>(node => node.Value is T casted ? visit(node, casted) : node);
public void Add(Shape displayShape, node n) { var icon = new NodeIconShape(n, displayShape, gd); base.Add(icon, n); }
//public string getProof(double din) //{ // string result = ""; // //ensure long double // for (int i = 1; i <= 9; i++) // { // for (int j = 0; j + i <= 9; j++) // { // Debug.Write($"width:{i} offset:{j}\r\n"); // //printf("width:%d offset:%d\n", i, j); // if (m[j, j + i] == null) m[j, j + i] = new SortedSet<node>(); // SortedSet<node> tout = m[j, j + i]; // node n; // //if(i==1){ //only single digits // n = leafnode(j, j + i); // insertnodup(tout, n); // if (j == 0 && n.num != 0.0) // { // //only negate the first number // //for positive initials and positive desired answers // //negation sign can be transformed out of brackets // n.num = -n.num; // insertnodup(tout, n); // } // //} // for (int k = 1; k <= i - 1; k++) // { // Debug.Write($"split:{k} len-a:{m[j, j + k].Count} len-b:{m[j + k, j + i].Count}\n"); // //printf("split:%d len-a:%d len-b:%d\n", k, m[j][j + k].size(), m[j + k][j + i].size()); // foreach (var ita in m[j, j + k]) // { // foreach (var itb in m[j + k, j + i]) // { // node na = ita; // node nb = itb; // n.l = na; // n.r = nb; // if (nb.optype != 1) // { // n.optype = 1; // if (nb.optype != 0 || nb.num >= 0) // { // n.opneg = 0; // n.num = na.num + nb.num; // if (Math.Abs(n.num - Math.Round(n.num)) < 1e-15 || // Math.Abs(n.num - Math.Round(n.num)) > 1e-3) // { // //numfix(n); // insertnodup(tout, n); // } // } // if (nb.optype != 0 || nb.num >= 0) // { // n.opneg = 1; // n.num = na.num - nb.num; // if (Math.Abs(n.num - Math.Round(n.num)) < 1e-15 || // Math.Abs(n.num - Math.Round(n.num)) > 1e-3) // { // //numfix(n); // insertnodup(tout, n); // } // } // } // if (nb.optype != 2) // { // n.optype = 2; // n.opneg = 0; // n.num = na.num * nb.num; // if (Math.Abs(n.num) < 1e10) // { //pruning // numfix(n); // insertnodup(tout, n); // } // } // if (na.optype != 3 && // (a^b)^c=a^(b*c) // na.num >= 0 && // true) // { // n.optype = 3; // n.opneg = 0; // n.num = Math.Pow(na.num, nb.num); // if (n.num == n.num && Math.Abs(n.num) < 1e10 && Math.Abs(n.num) > 1e-3) // { // numfix(n); // insertnodup(tout, n); // } // } // } // } // } // } // } // SortedSet<node> ans = m[0, 9]; // Debug.Write($"OK! total {ans.Count}\n"); // double prec = 1e-15; // node ntmp = new node(); // bool res = false; // prec = 1e-15; // while (!res) // { // ntmp.num = din - prec; // node smallest = new node(); // smallest.num = 0; // var it = ans.GetViewBetween(smallest, ntmp).First(); // while(true) // { // printnode(it, false); // Debug.Write($" = {it.num}\n"); // res = true; // } // //int index = ans.Select // //for (; it != ans.end() && Math.Abs(it.num - din) <= prec; it++) // //{ // // printnode(it, false); // // Debug.Write($" = {it.num}\n"); // // res = true; // //} // prec *= 2; // } // return result; //} public string getProof(double input) { string result = ""; //ensure long double for (int i = 1; i <= 9; i++) { for (int j = 0; j + i <= 9; j++) { Debug.Write($"width:{i} offset:{j}\r\n"); //printf("width:%d offset:%d\n", i, j); if (m[j, j + i] == null) { m[j, j + i] = new SortedSet <node>(); } SortedSet <node> tout = m[j, j + i]; node n; //if(i==1){ //only single digits n = leafnode(j, j + i); insertnodup(tout, n); if (j == 0 && n.num != 0.0) { //only negate the first number //for positive initials and positive desired answers //negation sign can be transformed out of brackets n.num = -n.num; insertnodup(tout, n); } //} for (int k = 1; k <= i - 1; k++) { Debug.Write($"split:{k} len-a:{m[j, j + k].Count} len-b:{m[j + k, j + i].Count}\n"); //printf("split:%d len-a:%d len-b:%d\n", k, m[j][j + k].size(), m[j + k][j + i].size()); foreach (var ita in m[j, j + k]) { foreach (var itb in m[j + k, j + i]) { node na = ita; node nb = itb; n.l = na; n.r = nb; if (nb.optype != 1) { n.optype = 1; if (nb.optype != 0 || nb.num >= 0) { n.opneg = 0; n.num = na.num + nb.num; if (Math.Abs(n.num - Math.Round(n.num)) < 1e-15 || Math.Abs(n.num - Math.Round(n.num)) > 1e-3) { //numfix(n); insertnodup(tout, n); } } if (nb.optype != 0 || nb.num >= 0) { n.opneg = 1; n.num = na.num - nb.num; if (Math.Abs(n.num - Math.Round(n.num)) < 1e-15 || Math.Abs(n.num - Math.Round(n.num)) > 1e-3) { //numfix(n); insertnodup(tout, n); } } } if (nb.optype != 2) { n.optype = 2; n.opneg = 0; n.num = na.num * nb.num; if (Math.Abs(n.num) < 1e10) { //pruning numfix(n); insertnodup(tout, n); } } //power, produces many useless nodes with division enabled if (na.optype != 3 && // (a^b)^c=a^(b*c) na.num >= 0 && //nb.num >= 0 && //Math.Abs(Math.Round(na.num)-na.num)<1e-15l && //Math.Abs(Math.Round(nb.num)-nb.num)<1e-15l && true) { n.optype = 3; n.opneg = 0; //n.num=powl(Math.Round(na.num),Math.Round(nb.num)); n.num = Math.Pow(na.num, nb.num); if (n.num == n.num && Math.Abs(n.num) < 1e10 && Math.Abs(n.num) > 1e-3) { numfix(n); insertnodup(tout, n); } } } } } } } SortedSet <node> ans = m[0, 9]; Debug.Write($"OK! total {ans.Count}\n"); //printf("OK! total %d\n", ans.size()); if (false) { //list all // for(mapt::iterator it=ans.begin();it!=ans.end();it++){ // printf("res %.17lg = ", (double)(it->num)); // printnode(*it,false); //printf("\n"); //} } if (true) { //do something meaningful double din = 0.0; double prec = 1e-15; node ntmp = new node(); //if (true) //{ //enumerate integer results // for (int i = 0; ; i++) // { // bool res = false; // din = (double)i; // ntmp.num = din - 1e-15; // node smallnode = new node(); // smallnode.num = -1; // var it = ans.GetViewBetween(smallnode, ntmp).First(); // for (; it != ans.end() && Math.Abs(it->num - din) <= prec; it++) // { // //printnode(*it,false); // //printf(" = %.17lg\n",(double)(it->num)); // res = true; // break; // get rid of multiple answers due to FP error // } // if (!res) // { // printf("%d no solution!\n", i); // break; // } // } //} } return(result); }
public static geometry FindGeoemertyFromNode(node daeNode, library_geometries geometries) { string mesh_id = daeNode.instance_geometry[0].url.Trim('#'); return(Array.Find(geometries.geometry, x => x.id == mesh_id)); }
void runparse(string[] splittedstring) { for (int i = 0; i < splittedstring.Length; i++) { if (!(splittedstring[i].Length == 0)) { if (!blacklist.Contains(splittedstring[i].ToLower())) //if the word is not in the blacklist { System.Uri asdfasdf; if (System.Uri.TryCreate(splittedstring[i], UriKind.Absolute, out asdfasdf)) { continue; //Don't want to add URIs to bot! } splittedstring[i] = splittedstring[i].ToLower(); //make all the letters of a sentence small. Possibly bad idea because of smilies. if (i == 0) { char firstchar = splittedstring[i][0]; splittedstring[i] = splittedstring[i].Remove(0, 1); splittedstring[i] = firstchar.ToString().ToUpper() + splittedstring[i]; } //make the first letter of the first word of a sentence a capital. if (i == splittedstring.Length - 1 && (splittedstring[i][splittedstring[i].Length - 1] != '.') && (splittedstring[i][splittedstring[i].Length - 1] != '!') && (splittedstring[i][splittedstring[i].Length - 1] != '?') ) { splittedstring[i] += "."; } //End the sentence with a period, if there's no other sentence-ending character. if (!translatenodes.Keys.Contains(splittedstring[i])) //if translatenodes' keys DOESNT contain the current word of the sentence { node newnode = new node(splittedstring[i]); //make a new node translatenodes.Add(splittedstring[i], newnode); //add new node to translatenodes } if (i < splittedstring.Length - 1) //if this is not the last word of the sentence { //if the current wordnode's childnodelist DOESNT contain the next word in the sentence if (!translatenodes[splittedstring[i]].childnodes.Keys.ToList().Exists(x => x.text == splittedstring[i + 1])) { //if the translatenodes dict DOES contain the node associated with the next word in the dictionary //(But it isn't part of the current node's childnode dictionary) if (translatenodes.ContainsKey(splittedstring[i + 1])) { translatenodes[splittedstring[i]].childnodes.Add(translatenodes[splittedstring[i + 1]], 5); //add the node from the translatenodes to the childnode of the current wordnode. } } //if the current wordnode's childnodelist DOES contain the next word in the sentence else { translatenodes[splittedstring[i]].childnodes[translatenodes[splittedstring[i + 1]]] += 5; //Up the current wordnode's next wordnode's value by one. } } } else { wordsignored++; } } } }
public static void ExportIOModelAsDAE(string FileName, IOModel m) { COLLADA colladaFile = new COLLADA(); List <geometry> list_geometries = new List <geometry>(m.Meshes.Count); if (m.HasMeshes) { foreach (IOMesh iomesh in m.Meshes) { geometry g = new geometry(); g.name = iomesh.Name; g.id = iomesh.Name + $"_{m.Meshes.IndexOf(iomesh)}"; List <double> list_positions = new List <double>(); List <double> list_normals = new List <double>(); List <double> list_uvs = new List <double>(); List <double> list_colors = new List <double>(); foreach (IOVertex v in iomesh.Vertices) { list_positions.Add(v.Position.X); list_positions.Add(v.Position.Y); list_positions.Add(v.Position.Z); list_normals.Add(v.Normal.X); list_normals.Add(v.Normal.Y); list_normals.Add(v.Normal.Z); list_uvs.Add(v.UV0.X); list_uvs.Add(v.UV0.Y); } // Position source source_position = new source(); { float_array floats = new float_array(); floats.count = (ulong)list_positions.Count; floats.id = g.id + "_pos_arr"; floats.Values = list_positions.ToArray(); source_position = CreateSource(list_positions.Count, 3, floats.id, floats, new param[] { new param() { name = "X", type = "float" }, new param() { name = "Y", type = "float" }, new param() { name = "Z", type = "float" } }); } // Normal source source_normal = new source(); { float_array floats = new float_array(); floats.count = (ulong)list_normals.Count; floats.id = g.id + "_nrm_arr"; floats.Values = list_normals.ToArray(); source_normal = CreateSource(list_normals.Count, 3, floats.id, floats, new param[] { new param() { name = "X", type = "float" }, new param() { name = "Y", type = "float" }, new param() { name = "Z", type = "float" } }); } // UV0 source source_uv0 = new source(); { float_array floats = new float_array(); floats.count = (ulong)list_uvs.Count; floats.id = g.id + "_uv0_arr"; floats.Values = list_uvs.ToArray(); source_uv0 = CreateSource(list_uvs.Count, 2, floats.id, floats, new param[] { new param() { name = "S", type = "float" }, new param() { name = "T", type = "float" } }); } // vertices vertices vertices = new vertices(); vertices.id = g.id + "_verts"; vertices.input = new InputLocal[] { new InputLocal() { source = "#" + source_position.id, semantic = "POSITION" }, new InputLocal() { source = "#" + source_normal.id, semantic = "NORMAL" }, new InputLocal() { source = "#" + source_uv0.id, semantic = "TEXCOORD" } }; // triangles triangles triangles = new triangles(); triangles.count = (ulong)iomesh.Indices.Count; triangles.input = new InputLocalOffset[] { new InputLocalOffset() { offset = 0, semantic = "VERTEX", source = "#" + vertices.id } }; triangles.p = string.Join(" ", iomesh.Indices); // creating mesh mesh geomesh = new mesh(); geomesh.source = new source[] { source_position, source_normal, source_uv0 }; geomesh.Items = new object[] { triangles }; geomesh.vertices = vertices; g.Item = geomesh; list_geometries.Add(g); } } library_geometries lib_geometry = new library_geometries(); lib_geometry.geometry = list_geometries.ToArray(); // controllers List <controller> list_controller = new List <controller>(); if (m.HasMeshes && m.HasSkeleton) { // create lists List <source> skinSources = new List <source>(); List <string> boneNames = new List <string>(); List <double> InverseBinds = new List <double>(); foreach (RBone b in m.Skeleton.Bones) { boneNames.Add(b.Name); InverseBinds.AddRange(new double[] { b.InvWorldTransform.M11, b.InvWorldTransform.M21, b.InvWorldTransform.M31, b.InvWorldTransform.M41, b.InvWorldTransform.M12, b.InvWorldTransform.M22, b.InvWorldTransform.M32, b.InvWorldTransform.M42, b.InvWorldTransform.M13, b.InvWorldTransform.M23, b.InvWorldTransform.M33, b.InvWorldTransform.M43, b.InvWorldTransform.M14, b.InvWorldTransform.M24, b.InvWorldTransform.M34, b.InvWorldTransform.M44, }); } // setup controllers foreach (IOMesh iomesh in m.Meshes) { controller controller = new controller() { id = iomesh.Name + "_" + m.Meshes.IndexOf(iomesh) + "_controller" }; list_controller.Add(controller); // create source for weights List <double> weights = new List <double>(); List <int> bones = new List <int>(); List <int> boneCount = new List <int>(); StringBuilder build_v = new StringBuilder(); foreach (IOVertex v in iomesh.Vertices) { int bcount = 0; if (v.BoneWeights.X > 0) { if (!weights.Contains(v.BoneWeights.X)) { weights.Add(v.BoneWeights.X); } build_v.Append($"{(int)v.BoneIndices.X} {weights.IndexOf(v.BoneWeights.X)} "); bcount++; } if (v.BoneWeights.Y > 0) { if (!weights.Contains(v.BoneWeights.Y)) { weights.Add(v.BoneWeights.Y); } build_v.Append($"{(int)v.BoneIndices.Y} {weights.IndexOf(v.BoneWeights.Y)} "); bcount++; } if (v.BoneWeights.Z > 0) { if (!weights.Contains(v.BoneWeights.Z)) { weights.Add(v.BoneWeights.Z); } build_v.Append($"{(int)v.BoneIndices.Z} {weights.IndexOf(v.BoneWeights.Z)} "); bcount++; } if (v.BoneWeights.W > 0) { if (!weights.Contains(v.BoneWeights.W)) { weights.Add(v.BoneWeights.W); } build_v.Append($"{(int)v.BoneIndices.W} {weights.IndexOf(v.BoneWeights.W)} "); bcount++; } boneCount.Add(bcount); } // skin Name_array arr_name = new Name_array(); arr_name.count = (ulong)boneNames.Count; arr_name.id = controller.id + "joints"; arr_name.Values = boneNames.ToArray(); source source_skin = CreateSource(boneNames.Count, 1, arr_name.id, arr_name, new param[] { new param() { name = "JOINT", type = "name" } }); // bind float_array arr_bind = new float_array(); arr_bind.count = (ulong)InverseBinds.Count; arr_bind.id = controller.id + "binds"; arr_bind.Values = InverseBinds.ToArray(); source source_binds = CreateSource(InverseBinds.Count, 16, arr_bind.id, arr_bind, new param[] { new param() { name = "TRANSFORM", type = "float4x4" } }); // weight source source_weight = new source(); { float_array floats = new float_array(); floats.count = (ulong)weights.Count; floats.id = controller.id + "_weights"; floats.Values = weights.ToArray(); source_weight = CreateSource(weights.Count, 1, floats.id, floats, new param[] { new param() { name = "WEIGHT", type = "float" }, }); } skin skin = new skin(); skin.source1 = "#" + iomesh.Name + $"_{m.Meshes.IndexOf(iomesh)}"; skin.source = new source[] { source_skin, source_binds, source_weight }; skin.joints = new skinJoints() { input = new InputLocal[] { new InputLocal() { semantic = "JOINT", source = "#" + source_skin.id }, new InputLocal() { semantic = "INV_BIND_MATRIX", source = "#" + source_binds.id } } }; //skin weights skin.vertex_weights = new skinVertex_weights(); skin.vertex_weights.count = (ulong)iomesh.Vertices.Count; skin.vertex_weights.input = new InputLocalOffset[] { new InputLocalOffset() { semantic = "JOINT", source = "#" + source_skin.id, offset = 0 }, new InputLocalOffset() { semantic = "WEIGHT", source = "#" + source_weight.id, offset = 1 } }; skin.vertex_weights.vcount = string.Join(" ", boneCount); skin.vertex_weights.v = build_v.ToString(); controller.Item = skin; } } library_controllers lib_controllers = new library_controllers(); lib_controllers.controller = list_controller.ToArray(); // scene nodes List <node> scene_nodes = new List <node>(); int visual_index = 0; if (m.HasSkeleton) { Dictionary <RBone, node> boneToNode = new Dictionary <RBone, node>(); foreach (RBone b in m.Skeleton.Bones) { // create bone node node node = new node(); node.name = b.Name; node.id = "bone" + visual_index++; node.sid = b.Name; node.type = NodeType.JOINT; // add transform matrix mat = new matrix() { Values = new double[] { b.Transform.M11, b.Transform.M21, b.Transform.M31, b.Transform.M41, b.Transform.M12, b.Transform.M22, b.Transform.M32, b.Transform.M42, b.Transform.M13, b.Transform.M23, b.Transform.M33, b.Transform.M43, b.Transform.M14, b.Transform.M24, b.Transform.M34, b.Transform.M44, } }; node.ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.matrix }; node.Items = new object[] { mat }; // deal with parenting boneToNode.Add(b, node); if (b.ParentID == -1) { scene_nodes.Add(node); } else { if (boneToNode[m.Skeleton.Bones[b.ParentID]].node1 == null) { boneToNode[m.Skeleton.Bones[b.ParentID]].node1 = new node[0]; } node[] parentnode = boneToNode[m.Skeleton.Bones[b.ParentID]].node1; Array.Resize <node>(ref parentnode, parentnode.Length + 1); parentnode[parentnode.Length - 1] = node; boneToNode[m.Skeleton.Bones[b.ParentID]].node1 = parentnode; } } } if (m.HasMeshes) { foreach (IOMesh iomesh in m.Meshes) { node node = new node() { id = "mesh" + visual_index++, name = iomesh.Name, type = NodeType.NODE }; if (m.HasSkeleton) { instance_controller controller = new instance_controller() { url = iomesh.Name + "_" + m.Meshes.IndexOf(iomesh) + "_controller" }; controller.skeleton = new string[] { "#bone0" }; node.instance_controller = new instance_controller[] { controller }; } scene_nodes.Add(node); } } // visual scene root library_visual_scenes scenes = new library_visual_scenes(); scenes.visual_scene = new visual_scene[] { new visual_scene() { id = "visualscene0", name = "rdmscene" } }; scenes.visual_scene[0].node = scene_nodes.ToArray(); // scene COLLADAScene scene = new COLLADAScene(); scene.instance_visual_scene = new InstanceWithExtra() { url = "#visualscene0" }; // putting it all together colladaFile.Items = new object[] { lib_geometry, lib_controllers, scenes }; colladaFile.scene = scene; colladaFile.Save(FileName); }
/// <summary> /// Invoked when <see cref="ToDTO"/> operation is about to return. /// </summary> /// <param name="dto"><see cref="nodeDto"/> converted from <see cref="node"/>.</param> static partial void OnDTO(this node entity, nodeDto dto);
/// <summary> /// Finds the path. Starts the 2D Astar algorithm and returns a path through the world array of nodes that avoids non-walkable spaces. /// </summary> /// <returns>The path.</returns> /// <param name="start">Start node.</param> /// <param name="goal">Goal node.</param> public List <node> findPath(node start, node goal) //IEnumerator //resetArray (); //makes a copy of the current world and resets nodes values //cloneWorldArrayIntoLocal (); //world.resetWorldArray(localWorldArray); { openList = new List <node> (); closedList = new List <node> (); openList.Add(start); start.onOpenList = true; start.g = 0; start.h = heuristic_Manhattan_distance(start, goal); start.f = start.g + start.h; node lowestF = new node(); //holds lowestFvalue node lowestF = null; while (openList.Count > 0) { node current = new node(); current = null; //didn't work out to increase performance //openList.Sort ((a, b) => a.f.CompareTo (b.f)); //current = openList[0]; //finds node on open list with lowest f value foreach (node check in openList) //slecects the node in the openList with the lowest f cost { if (current == null) { current = check; } if (check.f < current.f) { current = check; } } //goal state if (current == goal) // or when closedList.Contains(goal) { return(construct_path(current)); //current is the same as goal at this point } openList.Remove(current); current.onOpenList = false; closedList.Add(current); current.onClosedList = true; foreach (node neighbor in neighbors(current, goal)) { //no need to do this check just slows the prgram down //if (neighbor.onClosedList) { //closedList.Contains (neighbor) // continue; //} float tentative_gScore = current.g + directionalGCost(current, neighbor); // score to the new neighbor openList.Add(neighbor); neighbor.onOpenList = true; if ((tentative_gScore >= neighbor.g)) { continue; } neighbor.parent = current; neighbor.g = tentative_gScore; neighbor.f = neighbor.g + heuristic_Manhattan_distance(neighbor, goal); } } return(null); // no path exist }
void printnode(node n, bool brkt) { if (n.optype == 0) { if (n.num < 0.0) { Debug.Write($"({n.num})"); //printf("(%.10lg)", (double)n.num); } else { Debug.Write($"{n.num}"); //printf("%.10lg", (double)n.num); } } else { if (n.optype == 4) { Debug.Write($" +"); //printf(" +"); } if (brkt || n.optype == 4) { Debug.Write($"("); //putchar('('); } printnode(n.l, n.l.optype > 0 && n.l.optype < n.optype); if (n.optype == 1) { if (n.opneg == 0) { Debug.Write($" + "); // printf(" + "); } else { Debug.Write($" - "); //printf(" - "); } } else if (n.optype == 2) { if (n.opneg == 0) { Debug.Write($" * "); // printf(" * "); } else { Debug.Write($" / "); //printf(" / "); } } else if (n.optype == 3) { // right associativity Debug.Write($" ^ "); //printf(" ^ "); } else if (n.optype == 4) { Debug.Write($" +\"\"+ "); //printf(" +\"\"+ "); } printnode(n.r, n.r.optype > 0 && n.r.optype < n.optype); if (brkt || n.optype == 4) { Debug.Write($")"); //putchar(')'); } //printf(" /*%.10lg*/",(double)n.num); } }