public static void simpleTest() { TableGraph <int, int> graph = new TableGraph <int, int>(); string n1UUID = "node 1"; graph.addNode(10, n1UUID); string n2UUID = "node 2"; graph.addNode(11, n2UUID); graph.createEdgeOneWay(n1UUID, n2UUID, 9999); // N1 assertTrue(graph.containsNode(n1UUID)); assertEquals(graph.getNode(n1UUID).payload, 10); assertEquals(graph.getNode(n1UUID).nodeName, n1UUID); assertEquals(0, graph.getInboundEdges(n1UUID).Count, "inbound edges for n1 should be 0"); assertEquals(1, graph.getOutboundEdges(n1UUID).Count, "outbound edges for n1 should be 1"); // N2 assertTrue(graph.containsNode(n2UUID)); assertEquals(graph.getNode(n2UUID).payload, 11); assertEquals(graph.getNode(n2UUID).nodeName, n2UUID); assertEquals(1, graph.getInboundEdges(n2UUID).Count, "inbound edges for n2 should be 1"); assertEquals(0, graph.getOutboundEdges(n2UUID).Count, "outbound edges for n2 should be 0"); Debug.Log("Simple Test passed"); // Remove some stuff graph.removeEdge(n1UUID, n2UUID); assertEquals(0, graph.getOutboundEdges(n1UUID).Count); assertEquals(0, graph.getInboundEdges(n1UUID).Count); ////// // Test const time removal Edge <int, int> targetEdge = graph.createEdgeOneWay(n1UUID, n2UUID, -10); for (int i = 0; i < 20; i++) { Node <int> newNode = graph.addNode(i); graph.createEdgeOneWay(graph.getNode(n1UUID), newNode, i * 20); } assertEquals(21, graph.getOutboundEdges(n1UUID).Count, "outbound edges for n1 should be 21"); assertEquals(1, graph.getInboundEdges(n2UUID).Count, "inbound edges for n2 should be 1"); graph.removeEdge(n1UUID, n2UUID); assertEquals(20, graph.getOutboundEdges(n1UUID).Count, "One edge should have been removed."); assertTrue(!graph.getOutboundEdges(n1UUID).Contains(targetEdge), "Should not contain target edge"); Debug.Log("Removal tests pass"); }
public TableGraph GetTableGraph(string tableName) { TableGraph info = null; using (IDataReader reader = DataStore.ExecuteReader("TableData_Get", tableName)) { if (!reader.IsClosed && reader.Read()) { info = Hydrate <TableGraph>(reader); if (reader.NextResult()) { info.Columns = new List <ColumnInfo>(); while (reader.Read()) { ColumnInfo column = new ColumnInfo(); column.ColumnName = reader.GetValue <string>("COLUMN_NAME"); column.OrdinalPosition = reader.GetValue <int>("ORDINAL_POSITION"); column.DataType = reader.GetValue <string>("DATA_TYPE"); column.MaxCharacterLength = reader.GetValue <int?>("CHARACTER_MAXIMUM_LENGTH"); column.IsNullable = reader.GetValue <string>("IS_NULLABLE").Equals("NO", StringComparison.InvariantCultureIgnoreCase); column.DefaultValue = reader.GetValue <string>("COLUMN_DEFAULT"); column.Description = reader.GetValue <string>("Description"); info.Columns.Add(column); } } reader.Close(); } } return(info); }
private void InitializeFormResult() { Text = "Окно просмотра приятия решения"; MainMenu.Visible = false; TableLayoutPanelMain.RowStyles[0].Height = 0.0f; ButtonAddLayerP3.Visible = false; ButtonRemoveLayerP3.Visible = false; ButtonShowAnswer.Enabled = false; //Раскрашивание пройденного пути ответов пользователя и системы if (_userSystemDialog != null) { //Текущий граф TableGraph curTg = _graph.ListGraphs.Find(x => x.Id == _userSystemDialog.CurrentTableGraph.Id); if (curTg != null) { curTg.IsCurrentGraphForResult = true; curTg.LayerTreeNodeOwner.BackColor = Color.LightSeaGreen; } //Путь foreach (var tableLog in _userSystemDialog.TableLogs) { TableGraph tg = _graph.ListGraphs.Find(x => x.Id == tableLog.SystemTableGraph.Id); if (tg != null) { tg.IsPathForResult = true; } } } }
public UserSystemDialog([NotNull] RichTextBox chatRichTextBoxIn, [NotNull] TextBox userTextBoxIn) { _chatRichTextBox = chatRichTextBoxIn; _userTextBox = userTextBoxIn; CurrentTableGraph = null; TableLogs = new List <TableLog>(); _chatRichTextBox.Clear(); _userTextBox.Clear(); }
public void ShowNextQuestion([CanBeNull] string userAnswerIn, List <TableGraph> tableGraphsIn) { TableGraph resTableGraph = null; if (tableGraphsIn != null && tableGraphsIn.Count > 0) { if (!string.IsNullOrEmpty(userAnswerIn)) { var userAnswer = userAnswerIn.ToUpper(); if (CurrentTableGraph != null) { var childsEnumerable = from v in tableGraphsIn where v.ParentIds.Contains(CurrentTableGraph.Id) select v; bool isFindAnswer = false; foreach (TableGraph tableGraph in childsEnumerable) { if (tableGraph.UserAnswers == null) { continue; } string[] masStrings = tableGraph.UserAnswers.ToArray(); foreach (string st in masStrings) { if (userAnswer.Contains(st.ToUpper())) { resTableGraph = tableGraph; isFindAnswer = true; break; } } if (isFindAnswer) { break; } } if (!isFindAnswer) { PrintUserTextToChat(userAnswerIn); UserMistakeCount++; PrintSystemTextToChat("Я вас не понял, повторите ответ.", null); } } } else if (CurrentTableGraph == null) { //Начальный граф resTableGraph = tableGraphsIn[0]; } } if (resTableGraph != null) { MoveToTableGraph(userAnswerIn, resTableGraph); } }
private void Update() { if (true) { if (TimeOfDay.currentTimeOfDay < TimeOfDay.endTimeOfDay) { int num = Mathf.RoundToInt((TimeOfDay.currentTimeOfDay - TimeOfDay.startTimeOfDay) / (TimeOfDay.endTimeOfDay - TimeOfDay.startTimeOfDay) * (float)(timeOfDaySpawnMultipliers.Length - 1)); currentSpawnMinDelay = spawnMinDelay * (1f / (timeOfDaySpawnMultipliers[/*num*/ Mathf.Clamp(num, 0, timeOfDaySpawnMultipliers.Length)] + 0.001f)) / (float)Mathf.Max(1 + 1, 3); } if (Time.time > lastCitizenSpawn + citizenSpawnDelay) { lastCitizenSpawn = Time.time; if (UnityEngine.Random.value > 0.999f) { SpawnNewNPC(0, 1, 1); } else { SpawnNewNPC(0, 1, 0); } } if (Time.time > lastSpawnTime + (currentSpawnMinDelay + spawnAdditionalTimeRand)) { lastSpawnTime = Time.time; spawnAdditionalTimeRand = UnityEngine.Random.Range(0f, spawnMaxRand + 1f); if (currentNPCs < maxNPCs) { int num2 = 1; int npcWants = 1; float value = UnityEngine.Random.value; if (value > 0.9f) { num2 = 3; } else if (value > 0.7f) { num2 = 4; } else if (value > 0.2f) { num2 = 2; } if (TableGraph.FindUnoccupiedTableForGroup(num2) == -1) { npcWants = 0; } for (int i = 0; i < num2; i++) { SpawnNewNPC(npcWants, num2, 0); } } } } }
public TableGraph <NPayload, EPayload> mergeGraphs(TableGraph <NPayload, EPayload> otherGraph) { /** * Merge the given "otherGraph" into this graph * NOTE: The returned graph IS this graph. Either should be used, while the "otherGraph" * should be discarded. */ // Add all the KeyValuePairs from otherGraph into this graph otherGraph.allNodes.ToList().ForEach(kvp => this.allNodes.Add(kvp.Key, kvp.Value)); otherGraph.inboundEdges.ToList().ForEach(kvp => this.inboundEdges.Add(kvp.Key, kvp.Value)); otherGraph.outboundEdges.ToList().ForEach(kvp => this.outboundEdges.Add(kvp.Key, kvp.Value)); return(this); }
private void AddGraph(bool isReferenceIn) { TableGraph tableGraph = null; var maxItem = (from v in _graph.ListGraphs orderby v.Id descending select v).FirstOrDefault(); if (maxItem != null) { tableGraph = new TableGraph() { Id = maxItem.Id + 1, Rectangle = new RectangleF( new PointF(maxItem.Rectangle.X + TableGraph.GraphSize.Width * 2, maxItem.Rectangle.Y + TableGraph.GraphSize.Height * 2), TableGraph.GraphSize), IsReference = isReferenceIn }; } else { tableGraph = new TableGraph() { Rectangle = new Rectangle(Point.Empty, TableGraph.GraphSize), IsReference = isReferenceIn }; } //Получим номер графа в текущем дереве var idNode = 0; var countNodes = TreeViewP3?.SelectedNode?.Nodes.Count; if (countNodes != null) { foreach (var node in TreeViewP3.SelectedNode.Nodes) { if (node != null) { idNode++; } } } tableGraph.LayerTreeNodeOwner = AddObjectToLayer(idNode.ToString()); tableGraph.LayerTreeNodeOwner.Tag = tableGraph.Id; _graph.ListGraphs.Add(tableGraph); //Update object for repaint Panel0.Invalidate(); }
/*private void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info) * { * if (stream.isWriting) * { * Vector3 position = base.transform.position; * Quaternion rotation = base.transform.rotation; * stream.Serialize(ref position); * stream.Serialize(ref rotation); * } * else * { * Vector3 zero = Vector3.zero; * Quaternion rotation2 = Quaternion.Euler(0f, 0f, 0f); * stream.Serialize(ref zero); * stream.Serialize(ref rotation2); * base.transform.position = Vector3.Lerp(base.transform.position, zero, 0.2f); * base.transform.rotation = rotation2; * } * }*/ private void Start() { graph = GameObject.Find("!NavigationGraph").GetComponent <GraphScript>(); tableGraph = GameObject.Find("!TableNodes").GetComponent <TableGraph>(); foreach (Transform item in GameObject.Find("!AvoidNodes").transform) { avoidNodes.Add(item); } randomDistanceFromNodeBias = UnityEngine.Random.insideUnitSphere * 5f; randomDistanceFromNodeBias.y = 0f; speed *= UnityEngine.Random.Range(0.9f, 1.5f); FindExit(true); burgerIndex = UnityEngine.Random.Range(0, Menu.ItemNames.Length); //Debug.Log("Test Random Burger: " + burger); }
private bool IsShowGraph(TableGraph graph) { bool res = true; TreeNode node = graph.LayerTreeNodeOwner; while (node != null) { if (!node.Checked) { res = false; break; } node = node.Parent; } return(res); }
public void MoveToTableGraph([CanBeNull] string userAnswerIn, [NotNull] TableGraph tableGraphIn) { CurrentTableGraph = tableGraphIn; UserMistakeCount = 0; if (!string.IsNullOrEmpty(userAnswerIn)) { PrintUserTextToChat(userAnswerIn); } PrintSystemTextToChat(tableGraphIn.Question, tableGraphIn.IsShowConsultation ? tableGraphIn.Consultation : null); TableLog tableLog = new TableLog() { UserAnswer = userAnswerIn, SystemTableGraph = tableGraphIn }; TableLogs.Add(tableLog); }
private void DeleteGraph(TableGraph tableGraphIn) { foreach (TableGraph tg in _graph.ListGraphs) { if (tg.ParentIds.Contains(_graph.SelectedTableGraph.Id)) { tg.ParentIds.Remove(_graph.SelectedTableGraph.Id); } } if (tableGraphIn != null) { TreeViewP3.Nodes.Remove(tableGraphIn.LayerTreeNodeOwner); } _graph.ListGraphs.Remove(_graph.SelectedTableGraph); _graph.SelectedTableGraph = null; SetDataToControlsP1(_graph.SelectedTableGraph); }
private void SetDataToControlsP1(TableGraph tableGraph) { if (tableGraph != null) { TextBoxIdP1.Text = tableGraph.Id.ToString(); TextBoxNameObjectP1.Text = tableGraph.NameObject; TextBoxQuestionP1.Text = tableGraph.Question; TextBoxConsultationP1.Text = tableGraph.Consultation; CheckBoxConsultationP1.Checked = tableGraph.IsShowConsultation; TextBoxAnnotationP1.Text = tableGraph.Annotation; } else { TextBoxIdP1.Text = ""; TextBoxNameObjectP1.Text = ""; TextBoxQuestionP1.Text = ""; TextBoxConsultationP1.Text = ""; CheckBoxConsultationP1.Checked = false; TextBoxAnnotationP1.Text = ""; } }
private void Panel0_DoubleClick(object sender, EventArgs e) { if (_graph.SelectedPreviousTableGraph != null) { _graph.SelectedPreviousTableGraph.LayerTreeNodeOwner.BackColor = Color.White; _graph.SelectedPreviousTableGraph.IsDrawGraphBorderLine = false; Panel0.Invalidate(); } if (_graph.SelectedTableGraph != null && _graph.SelectedTableGraph.IsReference && _graph.SelectedTableGraph.ParentIds.Count > 0) { TableGraph tg = _graph.ListGraphs.Find(match => match.Id == _graph.SelectedTableGraph.ParentIds[0]); ShowOneAndFocusLayer(tg.LayerTreeNodeOwner.Parent); } else if (_graph.SelectedTableGraph != null) { _graph.SelectedTableGraph.LayerTreeNodeOwner.BackColor = Color.LightSeaGreen; _graph.SelectedTableGraph.IsDrawGraphBorderLine = true; _graph.SelectedTableGraph.LayerTreeNodeOwner.EnsureVisible(); Panel0.Invalidate(); } }
/// <summary> /// Находит граф, который попадает в область mousePointIn и возвращает его. /// </summary> /// <param name="mousePointIn"></param> /// <returns>TableGraph,null</returns> public TableGraph SelectGraph(PointF mousePointIn) { TableGraph tableGraph = null; foreach (var graph in ListGraphs) { if (!IsShowGraph(graph)) { continue; } //Обратные действия преобразования масштабирования и перемещения для точки PointF translateScaleMousePoint = GetTransformPointFromMatrix(_matrixTransform, mousePointIn); if (graph.Rectangle.Contains(translateScaleMousePoint)) { tableGraph = graph; break; } } return(tableGraph); }
private TableGraph GetGraph(IEnumerable<Table> tables) { var columns = from t in tables from p in t.Parameters where p.IsForeignKey select p ; var g = new TableGraph(); // add all the tables as a vertex foreach (var table in tables) { g.AddVertex(table); } foreach (var c in columns) { if (c.ForeignKeyTable == null) { continue; } // add an edge for each FK relationship g.AddEdge(new TableEdge(c)); } return g; }
private void DrawConnectionLine(TableGraph tableGraphIn, Graphics graphicsIn) { //Вывод соединительной линии foreach (var parentId in tableGraphIn.ParentIds) { TableGraph firstGraph = ListGraphs.FirstOrDefault(tg => tg.Id == parentId); if (firstGraph != null && IsShowGraph(firstGraph)) { Pen linePen = null; if ((tableGraphIn.IsCurrentGraphForResult || tableGraphIn.IsPathForResult) && !firstGraph.IsPathForResult) { linePen = new Pen(tableGraphIn.LineConstructorColor); } else if ((tableGraphIn.IsCurrentGraphForResult || tableGraphIn.IsPathForResult) && firstGraph.IsPathForResult) { linePen = new Pen(tableGraphIn.LineResultColor); } else { linePen = new Pen(tableGraphIn.LineConstructorColor); } float radToDeg = (float)(180.0 / Math.PI); float degToRad = (float)(Math.PI / 180.0); PointF firstLinePoint = new PointF(firstGraph.Rectangle.Left + firstGraph.Rectangle.Width / 2.0f, firstGraph.Rectangle.Top + firstGraph.Rectangle.Height / 2.0f); PointF secondLinePoint = new PointF(tableGraphIn.Rectangle.Left + tableGraphIn.Rectangle.Width / 2.0f, tableGraphIn.Rectangle.Top + tableGraphIn.Rectangle.Height / 2.0f); PointF vectorDirect = new PointF(secondLinePoint.X - firstLinePoint.X, secondLinePoint.Y - firstLinePoint.Y); /*//Ищем точки пересечения окружностей и прямой, что бы прямая не перекрывала окружность * float vecDirectLen = GetVecLength(vectorDirect); * PointF firstCrossPoint = GetPointOnVector(firstLinePoint, secondLinePoint, firstGraph.Rectangle.Height / 2.0f); * PointF secondCrossPoint = GetPointOnVector(firstLinePoint, secondLinePoint, vecDirectLen - tableGraphIn.Rectangle.Height / 2.0f);*/ PointF firstCrossPoint = new PointF(); PointF secondCrossPoint = new PointF(); float angleVecDirec = (float)Math.Atan2(vectorDirect.Y, vectorDirect.X) * radToDeg; SideEnum firstGraphSide = GetSideByDegrees(angleVecDirec); if (firstGraphSide == SideEnum.Top) { firstCrossPoint.X = firstGraph.Rectangle.Left + firstGraph.Rectangle.Width / 2.0f; firstCrossPoint.Y = firstGraph.Rectangle.Top; secondCrossPoint.X = tableGraphIn.Rectangle.Left + tableGraphIn.Rectangle.Width / 2.0f; secondCrossPoint.Y = tableGraphIn.Rectangle.Bottom; } else if (firstGraphSide == SideEnum.Left) { firstCrossPoint.X = firstGraph.Rectangle.Left; firstCrossPoint.Y = firstGraph.Rectangle.Top + firstGraph.Rectangle.Height / 2.0f; secondCrossPoint.X = tableGraphIn.Rectangle.Right; secondCrossPoint.Y = tableGraphIn.Rectangle.Top + tableGraphIn.Rectangle.Height / 2.0f; } else if (firstGraphSide == SideEnum.Bottom) { firstCrossPoint.X = firstGraph.Rectangle.Left + firstGraph.Rectangle.Width / 2.0f; firstCrossPoint.Y = firstGraph.Rectangle.Bottom; secondCrossPoint.X = tableGraphIn.Rectangle.Left + tableGraphIn.Rectangle.Width / 2.0f; secondCrossPoint.Y = tableGraphIn.Rectangle.Top; } else if (firstGraphSide == SideEnum.Right) { firstCrossPoint.X = firstGraph.Rectangle.Right; firstCrossPoint.Y = firstGraph.Rectangle.Top + firstGraph.Rectangle.Height / 2.0f; secondCrossPoint.X = tableGraphIn.Rectangle.Left; secondCrossPoint.Y = tableGraphIn.Rectangle.Top + tableGraphIn.Rectangle.Height / 2.0f; } //Чертим стрелочки направления прямой //Угол боковой стрелочки к прямой будет 45 градусов //Точку стрелочки боковой берем из формул полярных систем координат //x=r*cosY, y=r*sinY //Угол между прямой и началом координат через полярные систмы координат //angle=arctan(y/x) PointF vectorDirectNew = new PointF(secondCrossPoint.X - firstCrossPoint.X, secondCrossPoint.Y - firstCrossPoint.Y); float angleVecDirectRad = (float)Math.Atan2(vectorDirectNew.Y, vectorDirectNew.X) * radToDeg; float arrowLen = Settings.LengthArrow; float anglefirstArrowRad = (135.0f + angleVecDirectRad) * degToRad; float anglesecondArrowRad = (225.0f + angleVecDirectRad) * degToRad; PointF firstPointArrow = new PointF(arrowLen * (float)Math.Cos(anglefirstArrowRad), arrowLen * (float)Math.Sin(anglefirstArrowRad)); PointF secondPointArrow = new PointF(arrowLen * (float)Math.Cos(anglesecondArrowRad), arrowLen * (float)Math.Sin(anglesecondArrowRad)); //Смещаем относительно точки secondCrossPoint firstPointArrow.X += secondCrossPoint.X; firstPointArrow.Y += secondCrossPoint.Y; secondPointArrow.X += secondCrossPoint.X; secondPointArrow.Y += secondCrossPoint.Y; graphicsIn.DrawLine(linePen, firstCrossPoint, secondCrossPoint); graphicsIn.DrawLine(linePen, firstPointArrow, secondCrossPoint); graphicsIn.DrawLine(linePen, secondPointArrow, secondCrossPoint); linePen.Dispose(); linePen = null; } } }
private void Panel0_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (_graph.EditSizeState != EditSizeStateEnum.None) { if (_graph.SelectedTableGraph != null) { _mouseLeftClickPoint = e.Location; _oldSizeGraph = _graph.SelectedTableGraph.Rectangle.Size; } } else if (_graph.GraphState == GraphStateEnum.SetReference) { //Прописываем ссылку на другой слой TableGraph graph = _graph.SelectGraph(e.Location); if (graph != null) { if (graph.IsReference) { if (graph.ParentIds.Count > 0) { TableGraph tg = _graph.ListGraphs.Find(match => match.Id == graph.ParentIds[0]); MessageBox.Show($"Выбранная ссылка уже содержит переход на слой '{tg.LayerTreeNodeOwner.Parent.FullPath}'"); } else { _graph.SelectedTableGraph.ParentIds.Clear(); _graph.SelectedTableGraph.ParentIds.Add(graph.Id); graph.ParentIds.Clear(); graph.ParentIds.Add(_graph.SelectedTableGraph.Id); } } else { MessageBox.Show("Граф должен быть ссылкой."); } } _graph.GraphState = GraphStateEnum.None; } else { //Выделение графа var oldTableGraph = _graph.SelectedTableGraph; _graph.SelectedTableGraph = _graph.SelectGraph(e.Location); if (_graph.SelectedTableGraph != null && oldTableGraph != null && _graph.SelectedTableGraph.Id != oldTableGraph.Id || oldTableGraph != null && _graph.SelectedTableGraph == null) { _graph.SelectedPreviousTableGraph = oldTableGraph; } SetDataToControlsP1(_graph.SelectedTableGraph); if (_graph.SelectedTableGraph != null) { _graph.GraphState = GraphStateEnum.Move; } else { _graph.GraphState = GraphStateEnum.None; } } } else if (e.Button == MouseButtons.Middle) { _mouseRightClickPoint = e.Location; } else if (e.Button == MouseButtons.Right) { if (_graph.SelectedTableGraph != null) { _graph.GraphState = GraphStateEnum.ContextMenu; if (_graph.SelectedTableGraph.IsReference) { ContextMenu c = new ContextMenu(); c.MenuItems.Add("Переход на другой слой", (ob, ev) => { ContextMenu contextSub = new ContextMenu(); List <TreeNode> list = GetTreeNodesLayer(true); foreach (var node in list) { if (node.Tag != null) { continue; } MenuItem item = contextSub.MenuItems.Add(node.Text, (obSubIn, evSubIn) => { TreeNode treeNode = (TreeNode)((MenuItem)obSubIn).Tag; ShowOneAndFocusLayer(treeNode); _graph.GraphState = GraphStateEnum.SetReference; }); item.Tag = node; } contextSub.Show(Panel0, e.Location); }); c.MenuItems.Add("Изменить размер", (ob, ev) => { _graph.GraphState = GraphStateEnum.EditSize; }); c.MenuItems.Add("Удалить граф", (ob, ev) => { DeleteGraph(_graph.SelectedTableGraph); Panel0.Invalidate(); }); c.Show(Panel0, e.Location); } else { TableGraph selectSecondGraph = _graph.SelectGraph(e.Location); if (selectSecondGraph != null && selectSecondGraph != _graph.SelectedTableGraph) { ContextMenu c = new ContextMenu(); c.MenuItems.Add("Создать линию", (ob, ev) => { if (!selectSecondGraph.ParentIds.Contains(_graph.SelectedTableGraph.Id)) { selectSecondGraph.ParentIds.Add(_graph.SelectedTableGraph.Id); Panel0.Invalidate(); } }); c.Show(Panel0, e.Location); } else { ContextMenu c = new ContextMenu(); c.MenuItems.Add("Изменить размер", (ob, ev) => { _graph.GraphState = GraphStateEnum.EditSize; }); c.MenuItems.Add("Удалить граф", (ob, ev) => { DeleteGraph(_graph.SelectedTableGraph); Panel0.Invalidate(); }); c.MenuItems.Add("Удалить линии с этим графом", (ob, ev) => { foreach (TableGraph tg in _graph.ListGraphs) { if (tg.ParentIds.Contains(_graph.SelectedTableGraph.Id)) { tg.ParentIds.Remove(_graph.SelectedTableGraph.Id); } } Panel0.Invalidate(); }); c.Show(Panel0, e.Location); } } } } }
private void Update() { if (currentlyWants == wants.toEnter) { if (pathToFollow == null || pathToFollow.Count == 0) { CreatePath(graph.enterance.transform.position); } else { if ((pathToFollow[0].transform.position + randomDistanceFromNodeBias - transform.position).magnitude < 10f) { if (Enterance.npcsWaiting < 6) { pathToFollow.RemoveAt(0); } else { setWants(wants.toExitScene); pathToFollow = new List <NavigationScript>(); FindExit(false); CreatePath(exitNode.transform.position); } if (UnityEngine.Random.value > 0.5f) { randomDistanceFromNodeBias = UnityEngine.Random.insideUnitSphere * 5f; randomDistanceFromNodeBias.y = 0f; } } RaycastHit raycastHit; if (pathToFollow.Count == 0) { Enterance.npcsWaiting++; // System if (SceneManager.GetSceneAt(0).buildIndex == 2) { setWants(wants.toFindSeat); } else { pathToFollow.Add(graph.nodes.ToArray()[12]); setWants(wants.toOrder); //setWants(wants.toFindSeat); } } else if (Time.time > lastLinecastCheck + linecastCheckDelay && Physics.Linecast(transform.position, pathToFollow[0].transform.position, out raycastHit, pathfindLayerMask) && raycastHit.distance < 3f) { if (timesStuckPathfinding > 4) { gameObject.layer = 16; } randomDistanceFromNodeBias = UnityEngine.Random.insideUnitSphere * 0.2f; randomDistanceFromNodeBias.y = 0f; CreatePath(graph.enterance.transform.position); timesStuckPathfinding++; lastLinecastCheck = Time.time; } else { Vector3 vector = Vector3.zero; Vector3 a = Vector3.zero; vector += Seek(pathToFollow[0].transform.position + randomDistanceFromNodeBias) * followWeight; a = vector; a.y = 0f; vector += SeparateAvoidNodes() * avoidNodesWeight; vector.y = 0f; if (vector != Vector3.zero) { transform.rotation = Quaternion.LookRotation(a + transform.forward); } GetComponent <Rigidbody>().AddForce(vector.normalized * maxSpeed * 10f * Time.deltaTime); } } } else if (currentlyWants == NPC.wants.toExitScene) { if (pathToFollow == null || pathToFollow.Count == 0) { CreatePath(exitNode.transform.position); } else { if ((pathToFollow[0].transform.position + randomDistanceFromNodeBias - transform.position).magnitude < 10f) { pathToFollow.RemoveAt(0); if (UnityEngine.Random.value > 0.5f) { randomDistanceFromNodeBias = UnityEngine.Random.insideUnitSphere * 5f; randomDistanceFromNodeBias.y = 0f; } } RaycastHit raycastHit2; if (pathToFollow.Count == 0) { SpawnNPC.currentNPCs--; Destroy(gameObject); } else if (Time.time > lastLinecastCheck + linecastCheckDelay && Physics.Linecast(transform.position, pathToFollow[0].transform.position, out raycastHit2, layerMask) && raycastHit2.distance < 3f) { if (timesStuckPathfinding > 4) { gameObject.layer = 15; } randomDistanceFromNodeBias = UnityEngine.Random.insideUnitSphere * 0.2f; randomDistanceFromNodeBias.y = 0f; CreatePath(exitNode.transform.position); timesStuckPathfinding++; lastLinecastCheck = Time.time; } else { Vector3 vector2 = Vector3.zero; Vector3 a2 = Vector3.zero; vector2 += Seek(pathToFollow[0].transform.position + randomDistanceFromNodeBias) * followWeight; a2 = vector2; a2.y = 0f; vector2 += SeparateAvoidNodes() * avoidNodesWeight; vector2.y = 0f; if (vector2 != Vector3.zero) { transform.rotation = Quaternion.LookRotation(a2 + transform.forward); } GetComponent <Rigidbody>().AddForce(vector2.normalized * maxSpeed * 10f * Time.deltaTime); } } } else if (currentlyWants == wants.toIdle) { transform.rotation = Quaternion.LookRotation(transform.forward); Vector3 zero = Vector3.zero; GetComponent <Rigidbody>().AddForce(zero.normalized * maxSpeed * 10f * Time.deltaTime); if (Time.time > idleTimeMin + idleTimeRand + idleStartTime) { currentlyWants = previouslyWanted; if (currentlyWants == wants.toExitScene) { FindExit(false); CreatePath(exitNode.transform.position); } } } else if (currentlyWants == wants.toOrder) { GameObject orderPoint = GameObject.Find("OrderPoint"); Vector3 pointOrder = Vector3.zero; for (int i = 0; i < orderPoint.GetComponent <OrderScript>().npcs.ToArray().Length; i++) { if (orderPoint.GetComponent <OrderScript>().npcs.ToArray()[i] == gameObject) { pointOrder += Vector3.forward * i * 3; } } Vector3 vector3 = Vector3.zero; Vector3 a3 = Vector3.zero; if (pathToFollow.Count > 0) { vector3 += Seek(pathToFollow[0].transform.position + pointOrder) * followWeight * 1.5f; a3 = vector3; a3.y = 0f; vector3 += SeparateAvoidNodes() * avoidNodesWeight; vector3.y = 0f; if (vector3 != Vector3.zero) { transform.rotation = Quaternion.LookRotation(a3 + transform.forward); } GetComponent <Rigidbody>().AddForce(vector3.normalized * maxSpeed * 10f * Time.deltaTime); // Move if ((transform.position - pathToFollow[0].transform.position).magnitude < 3) { pathToFollow.RemoveAt(0); } } else { vector3 += Seek(orderPoint.transform.position + pointOrder) * followWeight * 1.5f; a3 = vector3; a3.y = 0f; vector3 += SeparateAvoidNodes() * avoidNodesWeight; vector3.y = 0f; if ((transform.position - (orderPoint.transform.position + pointOrder)).magnitude > 1) { if (vector3 != Vector3.zero) { transform.rotation = Quaternion.LookRotation(a3 + transform.forward); } GetComponent <Rigidbody>().AddForce(vector3.normalized * maxSpeed * 10f * Time.deltaTime); // Move } else { Transform tryGetObject = LookAtPlayer(15); if (tryGetObject) { transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, Quaternion.LookRotation(tryGetObject.position - transform.position).eulerAngles.y, 0), 4 * Time.deltaTime); } else { transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(180, 0, 180), 4 * Time.deltaTime); } } //Debug.Log((transform.position - (orderPoint.transform.position + pointOrder)).magnitude); } } else if (currentlyWants == wants.toFindSeat) { List <NPC> list = new List <NPC>(); int num = 0; int num2 = 0; list.Add(this); if (this.desiredGroupSize > 1) { GameObject[] array = GameObject.FindGameObjectsWithTag("NPC"); for (int i = 0; i < array.Length; i++) { GameObject gameObject = array[i]; //Debug.Log(gameObject.name + "; " + base.gameObject.name); //Debug.Log((gameObject != base.gameObject) + "; " + ((transform.position - gameObject.transform.position).magnitude < 40f)); if (gameObject != base.gameObject && (transform.position - gameObject.transform.position).magnitude < 40f) { NPC component = gameObject.GetComponent <NPC>(); if (num2 < desiredGroupSize - 1 && (component.currentlyWants == wants.toFindSeat || component.currentlyWants == wants.toIdle) && component.desiredGroupSize == desiredGroupSize) { list.Add(component); num2++; } } } } // System if (SceneManager.GetSceneAt(0).buildIndex == 3) { int randomNumber = 0; while (randomNumber != int.Parse(orderNumber.name.Substring(orderNumber.name.Length - 1))) { if (randomNumber == int.Parse(orderNumber.name.Substring(orderNumber.name.Length - 1))) { break; } randomNumber = UnityEngine.Random.Range(1, TableGraph.tables.Length + 1); } myNPCGroup = list; if (tableGraph == null) { tableGraph = GameObject.Find("!TableNodes").GetComponent <TableGraph>(); } num = randomNumber; print("Goal table: " + num); if (num >= 0) { foreach (NPC current in list) { if (current != this) { current.myNPCGroupLeader = this; current.setWants(wants.toGetToSeat); } foreach (TableNodes current2 in TableGraph.tables[num - 1].tableNodes) { if (!current2.occupied) { current.targetSeat = current2; current2.SetOccupied(true); current.setWants(wants.toGetToSeat); current.pathToFollow = graph.FindPath(FindClosestNode(current.transform.position), FindClosestVisibleNode(current.targetSeat.transform)); print(string.Concat(new object[] { "Found a seat for id[", list.IndexOf(current), "] @ ", num, " : ", TableGraph.tables[num - 1].tableNodes.IndexOf(current2) })); Enterance.npcsWaiting--; break; } } if (targetSeat == null) { print("Error: no free seat found?"); } } } else { if (desiredGroupSize == 4 && UnityEngine.Random.value > 0.8f) { setGroupSize(gameObject, 2); } myNPCGroup = new List <NPC>(); myNPCGroupLeader = null; setWants(wants.toIdle); idleStartTime = Time.time; idleTimeRand = UnityEngine.Random.Range(20f, 40f); } } else { if ((list.Count > 1 && list.Count == desiredGroupSize) || SceneManager.GetSceneAt(0).buildIndex == 3) { myNPCGroup = list; if (tableGraph == null) { tableGraph = GameObject.Find("!TableNodes").GetComponent <TableGraph>(); } num = TableGraph.FindUnoccupiedTableForGroup(myNPCGroup.Count); print("Goal table: " + num); if (num >= 0) { foreach (NPC current in list) { if (current != this) { current.myNPCGroupLeader = this; current.setWants(wants.toGetToSeat); } foreach (TableNodes current2 in TableGraph.tables[num - 1].tableNodes) { if (!current2.occupied) { current.targetSeat = current2; current2.SetOccupied(true); current.setWants(wants.toGetToSeat); current.pathToFollow = graph.FindPath(FindClosestNode(current.transform.position), FindClosestVisibleNode(current.targetSeat.transform)); print(string.Concat(new object[] { "Found a seat for id[", list.IndexOf(current), "] @ ", num, " : ", TableGraph.tables[num - 1].tableNodes.IndexOf(current2) })); Enterance.npcsWaiting--; break; } } if (targetSeat == null) { print("Error: no free seat found?"); } } } else { if (/*Network.isServer && */ desiredGroupSize == 4 && UnityEngine.Random.value > 0.8f) { setGroupSize(gameObject, 2); } myNPCGroup = new List <NPC>(); myNPCGroupLeader = null; setWants(wants.toIdle); idleStartTime = Time.time; idleTimeRand = UnityEngine.Random.Range(20f, 40f); } } else if (desiredGroupSize == 1) { if (tableGraph == null) { tableGraph = GameObject.Find("!TableNodes").GetComponent <TableGraph>(); } num = TableGraph.FindUnoccupiedTableForGroup(myNPCGroup.Count); if (num >= 0) { foreach (TableNodes current3 in TableGraph.tables[num - 1].tableNodes) { if (!current3.occupied) { targetSeat = current3; current3.SetOccupied(true); setWants(wants.toGetToSeat); pathToFollow = graph.FindPath(FindClosestNode(transform.position), FindClosestVisibleNode(targetSeat.transform)); Enterance.npcsWaiting--; break; } } } setWants(wants.toIdle); idleStartTime = Time.time; idleTimeRand = UnityEngine.Random.Range(20f, 40f); } else { myNPCGroup = new List <NPC>(); myNPCGroupLeader = null; setWants(wants.toIdle); idleStartTime = Time.time; idleTimeRand = UnityEngine.Random.Range(10f, 30f); } } //Debug.Log((list.Count > 1) + " " + (list.Count == desiredGroupSize)); //Debug.Log(list.Count + " " + desiredGroupSize); } else if (currentlyWants == wants.toGetToSeat) { Vector3 vector3 = Vector3.zero; Vector3 a3 = Vector3.zero; if (pathToFollow.Count > 0 && (pathToFollow[0].transform.position - transform.position).magnitude < 3f) { pathToFollow.RemoveAt(0); } RaycastHit raycastHit3; if (Physics.Linecast(transform.position, targetSeat.transform.position, out raycastHit3, layerMask)) { if (pathToFollow.Count > 0) { vector3 += Seek(pathToFollow[0].transform.position) * followWeight; a3 = vector3; a3.y = 0f; vector3 += SeparateAvoidNodes() * avoidNodesWeight; vector3.y = 0f; if (vector3 != Vector3.zero) { transform.rotation = Quaternion.LookRotation(a3 + transform.forward); } GetComponent <Rigidbody>().AddForce(vector3.normalized * maxSpeed * 8f * Time.deltaTime); } else { float num3 = 1f; if ((transform.position - targetSeat.transform.position).magnitude < 6f) { num3 = 0.2f; } if ((transform.position - targetSeat.transform.position).magnitude < 1f) { targetSeat.table.SetNPCAtTable(targetSeat.table.gameObject, gameObject); GetComponent <Rigidbody>().velocity = Vector3.zero; setWants(wants.toEat); /*if (Network.peerType == NetworkPeerType.Server) * { * targetSeat.table.GenerateFoodOrder(); * }*/ if (SceneManager.GetSceneAt(0).buildIndex == 3) { targetSeat.table.GenerateFoodOrder(burgerIndex); } else { targetSeat.table.GenerateFoodOrder(-1); } //targetSeat.table.GenerateFoodOrder(); foodWaitStartTime = Time.time; } vector3 += Seek(targetSeat.transform.position) * followWeight; a3 = vector3; a3.y = 0f; vector3 += SeparateAvoidNodes() * (avoidNodesWeight * num3); vector3.y = 0f; if (vector3 != Vector3.zero) { transform.rotation = Quaternion.LookRotation(a3 + transform.forward); } GetComponent <Rigidbody>().AddForce(vector3.normalized * maxSpeed * 10f * Time.deltaTime); } } else { if ((transform.position - targetSeat.transform.position).magnitude < 1f) { targetSeat.table.SetNPCAtTable(targetSeat.table.gameObject, gameObject); GetComponent <Rigidbody>().velocity = Vector3.zero; setWants(wants.toEat); /*if (Network.peerType == NetworkPeerType.Server) * { * targetSeat.table.GenerateFoodOrder(); * }*/ if (SceneManager.GetSceneAt(0).buildIndex == 3) { targetSeat.table.GenerateFoodOrder(burgerIndex); } else { targetSeat.table.GenerateFoodOrder(-1); } //targetSeat.table.GenerateFoodOrder(); foodWaitStartTime = Time.time; } vector3 += Seek(targetSeat.transform.position) * followWeight * 1.5f; a3 = vector3; a3.y = 0f; vector3 += SeparateAvoidNodes() * avoidNodesWeight; vector3.y = 0f; if (vector3 != Vector3.zero) { transform.rotation = Quaternion.LookRotation(a3 + transform.forward); } GetComponent <Rigidbody>().AddForce(vector3.normalized * maxSpeed * 10f * Time.deltaTime); } } else if (currentlyWants == wants.toLeave) { if (myNPCGroupLeader == null) { int num4 = 0; foreach (NPC current4 in myNPCGroup) { if (current4.currentlyWants == wants.toLeave) { num4++; } } if (num4 == myNPCGroup.Count) { print("Entire group wants to leave"); if (desiredGroupSize > 1) { foreach (NPC current5 in myNPCGroup) { current5.targetSeat.table.npcAtTable = null; //current5.targetSeat.table.ClearOrder(); current5.targetSeat.SetOccupied(false); current5.FindExit(false); current5.CreatePath(current5.exitNode.transform.position); current5.setWants(wants.toExitScene); } } else { targetSeat.table.npcAtTable = null; //targetSeat.table.ClearOrder(); targetSeat.SetOccupied(false); FindExit(false); CreatePath(exitNode.transform.position); setWants(wants.toExitScene); } } } } else if (currentlyWants == wants.toGetMenu) { if (Time.time > menuWaitStartTime + menuWaitBaseDuration) { currentlyWants = wants.toLeave; } } else if (currentlyWants == wants.toEat && Time.time > foodWaitStartTime + foodWaitBaseDuration) { currentlyWants = wants.toLeave; } if (SceneManager.GetSceneAt(0).buildIndex == 3) { gameObject.GetComponent <Collider>().enabled = currentlyWants != wants.toEat; gameObject.GetComponent <Rigidbody>().isKinematic = currentlyWants == wants.toEat; if (currentlyWants == wants.toEat) { transform.rotation = Quaternion.Euler(0, Quaternion.LookRotation(orderNumber.transform.position - transform.position).eulerAngles.y, 0); } } // System Scenes if (orderNumber) { switch (currentlyWants) { case wants.toGetToSeat: orderNumber.GetComponent <Rigidbody>().isKinematic = true; orderNumber.GetComponent <Collider>().enabled = false; orderNumber.transform.position = Vector3.Lerp(orderNumber.transform.position, transform.position + transform.forward * 2, 0.5f); orderNumber.transform.rotation = Quaternion.Lerp(orderNumber.transform.rotation, transform.rotation, 0.5f); break; case wants.toEat: orderNumber.transform.position = Vector3.Lerp(orderNumber.transform.position, targetSeat.table.transform.position + targetSeat.table.transform.up * 1.1f + targetSeat.table.transform.right * 3, 0.5f); orderNumber.transform.rotation = Quaternion.Lerp(orderNumber.transform.rotation, targetSeat.table.transform.rotation, 0.5f); break; case wants.toExitScene: orderNumber.GetComponent <Rigidbody>().isKinematic = false; orderNumber.GetComponent <Collider>().enabled = true; orderNumber = null; break; } } // If he got Order Number }
public void MoveGraph(TableGraph graph, PointF pointOffset) { PointF scaleTranslatePointF = GetTransformPointFromMatrix(_matrixTransform, pointOffset); graph.Rectangle.Location = scaleTranslatePointF; }