private static NavigationNode PublicMenu(List<Category<ObjectId>> categories)
        {
            var root = new NavigationNode<PostsController>(x => x.List(1))
            {
                Order = 0,
                RenderTargets = new List<object> { RenderTarget.BreadCrumbs }
            };

            List<Category<ObjectId>> rootCategories =
                categories.Where(p => p.ParentCategoryID == null).ToList();
            List<IGrouping<ObjectId?, Category<ObjectId>>> categoryGroups =
                categories.GroupBy(p => p.ParentCategoryID).ToList();

            foreach (Category<ObjectId> category in rootCategories)
            {
                NavigationNode node = ToCategoryNode(category);

                IGrouping<ObjectId?, Category<ObjectId>> childCategories = categoryGroups
                    .FirstOrDefault(p => p.Key == category.CategoryID);
                if (childCategories != null)
                {
                    node.Children = childCategories.Select(p => ToCategoryNode(p)).ToList();
                    node.IsClickable = false;
                }

                root.Children.Add(node);
            }

            return root;
        }
 public static string GetClass(this NavigationViewModel model, NavigationNode node, string inputClass = null, string activeClass = "active")
 {
     if (node == null) return null;
     if (model.CurrentNode != null && (node.EqualsNode(model.CurrentNode.Value)))
     {
         if (!string.IsNullOrEmpty(inputClass))
         {
             inputClass = activeClass + " " + inputClass;
         }
         else
         {
             inputClass = activeClass;
         }
     }
     if (string.IsNullOrEmpty(node.CssClass))
     {
         return inputClass;
     }
     else
     {
         if (!string.IsNullOrEmpty(inputClass))
         {
             return inputClass + " " + node.CssClass;
         }
         return node.CssClass;
     }
 }
        public static string GetIcon(this NavigationViewModel model, NavigationNode node)
        {
            if (node == null) return string.Empty;
            if (string.IsNullOrEmpty(node.IconCssClass))
            {
                return string.Empty;

            }
            return "<i class='" + node.IconCssClass + "'></i> ";
        }
 private List<HorizontalSubMenuItem> GetSubItems(NavigationNode node)
 {
     List<HorizontalSubMenuItem> result = new List<HorizontalSubMenuItem>();
     foreach (NavigationNode childNode in node.Children)
     {
         HorizontalSubMenuItem menuItem = new HorizontalSubMenuItem(childNode.Text, childNode.Url);
         if (childNode.Children.Count > 0) menuItem.ChildItems.AddRange(GetSubItems(childNode));
         result.Add(menuItem);
     }
     return result;
 }
        public virtual List<NavigationNode> FindMatches(
            NavigationNode[] allNodes,
            DeleteNavigationNodesDefinitionBase typedDefinition,
            Func<string, string> resolveTokenizedUrlAction)
        {
            var nodesToDelete = new List<NavigationNode>();

            foreach (var nodeMatch in typedDefinition.NavigationNodes)
            {
                var foundByTitle = false;

                // search by Title, first
                if (!string.IsNullOrEmpty(nodeMatch.Title))
                {
                    var nodeByTitle = allNodes.FirstOrDefault(f =>
                        string.Equals(f.Title, nodeMatch.Title, StringComparison.OrdinalIgnoreCase));

                    if (nodeByTitle != null)
                    {
                        foundByTitle = true;

                        if (!nodesToDelete.Contains(nodeByTitle))
                        {
                            nodesToDelete.Add(nodeByTitle);
                        }
                    }
                }

                // give a try by Url, then
                if (!foundByTitle && !string.IsNullOrEmpty(nodeMatch.Url))
                {
                    var matchUrl = resolveTokenizedUrlAction(nodeMatch.Url);

                    // special char resolution, manual fix to avoid
                    // Add more tests for DeleteXXXnavigationNode scenarios #864
                    // https://github.com/SubPointSolutions/spmeta2/issues/864
                    matchUrl = HttpUtility.HtmlEncode(matchUrl);

                    var nodeByUrl = allNodes.FirstOrDefault(f =>
                        !string.IsNullOrEmpty(f.Url)
                        && f.Url.EndsWith(matchUrl, StringComparison.OrdinalIgnoreCase));

                    if (nodeByUrl != null)
                    {
                        if (!nodesToDelete.Contains(nodeByUrl))
                            nodesToDelete.Add(nodeByUrl);
                    }
                }
            }
            return nodesToDelete;
        }
        private void ValidateNode(NavigationNode qlNode, QuickLaunchNavigationNodeDefinition quickLaunchModel)
        {
            TraceUtils.WithScope(traceScope =>
            {
                var pair = new ComparePair<QuickLaunchNavigationNodeDefinition, NavigationNode>(quickLaunchModel, qlNode);

                traceScope.WriteLine(string.Format("Validating model:[{0}] node:[{1}]", quickLaunchModel, qlNode));

                traceScope.WithTraceIndent(trace => pair
                    .ShouldBeEqual(trace, m => m.Title, o => o.Title)
                    .ShouldBeEqual(trace, m => m.Url, o => o.Url)
                    .ShouldBeEqual(trace, m => m.IsVisible, o => o.IsVisible)
                    .ShouldBeEqual(trace, m => m.IsExternal, o => o.IsExternal));
            });
        }
        private static List<NavigationNode> AdminMenu(List<Category<ObjectId>> categories)
        {
            List<NavigationNode> adminNodes = new List<NavigationNode>();

            //posts
            var articlesParent = new NavigationNode()
            {
                Order = 0,
                RenderTargets = new List<object> { RenderTarget.AdminMenu },
                IsClickable = false,
                Title = GlobalContent.Menu_Posts
            };
            adminNodes.Add(articlesParent);

            articlesParent.Children.Add(new NavigationNode<PostsController>(x => x.Add(null, null))
            {
                Order = 0,
                RenderTargets = new List<object> { RenderTarget.AdminMenu },
                Title = GlobalContent.Menu_PostsAdd
            });

            articlesParent.Children.Add(new NavigationNode<PostsController>(x => x.EditList(1, null))
            {
                Order = 0,
                RenderTargets = new List<object> { RenderTarget.AdminMenu },
                Title = GlobalContent.Menu_PostsEditList
            });

            //manuals categories
            foreach (Category<ObjectId> category in categories)
            {
                NavigationNode node = ToCategoryNode(category);
                adminNodes.Add(node);
            }

            return adminNodes;
        }
Esempio n. 8
0
 public static void onNavigationNodeChange(ref EntitiesIndexedByNavigationNodes p_entitiesIndexedByNavigationNodes,
                                           Entity p_entity, NavigationNode p_oldNavigationNode, NavigationNode p_newNavigationNode)
 {
     if (p_entity != null)
     {
         if (p_newNavigationNode != null)
         {
             addEntityToNavigationNode(ref p_entitiesIndexedByNavigationNodes, p_entity, p_newNavigationNode);
         }
         if (p_oldNavigationNode != null)
         {
             removeEntityToNavigationNode(ref p_entitiesIndexedByNavigationNodes, p_entity, p_oldNavigationNode);
         }
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Works out a graph of nodes on top of the navmesh.
        /// Each polygon is a node and a node is added a connecting edges of linked polygons.
        /// The node graph class member is filled in by running this method.
        /// It's quite likely this code isn't very optimal.
        /// </summary>
        /// <param name="polyStart">The polygon the entity is currently in.</param>
        /// <param name="polyEnd">The polygon the entity would like to be in.</param>
        /// <param name="from">The point in the entity is current positioned.</param>
        /// <param name="to">The point the entity would like to be positioned.</param>
        /// <param name="navMesh">The navigation mesh describing the polygons and their links.</param>
        /// <returns>The start and end nodes for the journey the player wants to take</returns>
        private Tuple<NavigationNode, NavigationNode> CreateNodeNetwork(ConvexPolygon polyStart, ConvexPolygon polyEnd, Point from, Point to, NavMesh navMesh)
        {
            _nodeGraph.Clear();
            // Store a map poly -> node to make it simple to work out the connection nodes.
            Dictionary<ConvexPolygon, NavigationNode> polyToNodeMap = new Dictionary<ConvexPolygon, NavigationNode>();

            NavigationNode startNode = null;
            NavigationNode endNode = null;

            // Create a node for the centroid of each polygon
            // Replace the postion of the start and end polygon.
            foreach (ConvexPolygon polygon in navMesh.PolygonList)
            {
                Point position;
                NavigationNode node;
                if (polyStart == polygon)
                {
                    position = from;
                    node = new NavigationNode(position);
                    startNode = node;
                }
                else if (polyEnd == polygon)
                {
                    position = to;
                    node = new NavigationNode(position);
                    endNode = node;
                }
                else
                {
                    position = polygon.CalculateCentroid();
                    node = new NavigationNode(position);
                }


                _nodeGraph.Add(node);
                polyToNodeMap.Add(polygon, node);
            }

            // Create the edge nodes and add the links
            // !* This is where you'd add several nodes per edge, if you wanted.
            foreach (PolygonLink link in navMesh.Links)
            {
                LineSegment line = link.GetShortestEdge();
                Point midPoint = line.GetMiddle();

                NavigationNode connectionNode = new NavigationNode(midPoint);

                // Add bidirectional links to connected polys and edge polys.
                polyToNodeMap[link.StartPoly].Neighbours.Add(connectionNode);
                connectionNode.Neighbours.Add(polyToNodeMap[link.StartPoly]);

                polyToNodeMap[link.EndPoly].Neighbours.Add(connectionNode);
                connectionNode.Neighbours.Add(polyToNodeMap[link.EndPoly]);

                _nodeGraph.Add(connectionNode);
            }

            return new Tuple<NavigationNode, NavigationNode>(startNode, endNode);
        }
Esempio n. 10
0
 /// <summary>
 /// Custom page elements initialization
 /// </summary>
 /// <param name="navigationNode"></param>
 protected virtual void InitializePageElements(NavigationNode navigationNode)
 {
     // do nothing in abstract class
 }
Esempio n. 11
0
        ComplexObjectModel GenComplexObjectModel(ComplexPropertyDescriptor navigationDescriptor, NavigationNode navigationNode, QueryModel queryModel)
        {
            TypeDescriptor navigationTypeDescriptor = EntityTypeContainer.GetDescriptor(navigationDescriptor.PropertyType);

            DbTable           dbTable      = navigationTypeDescriptor.Table;
            DbTableExpression tableExp     = new DbTableExpression(dbTable);
            string            alias        = queryModel.GenerateUniqueTableAlias(dbTable.Name);
            DbTableSegment    joinTableSeg = new DbTableSegment(tableExp, alias, queryModel.FromTable.Table.Lock);

            DbTable            aliasTable            = new DbTable(alias);
            ComplexObjectModel navigationObjectModel = navigationTypeDescriptor.GenObjectModel(aliasTable);

            navigationObjectModel.NullChecking = navigationObjectModel.PrimaryKey;

            PrimitivePropertyDescriptor foreignKeyPropertyDescriptor = navigationDescriptor.ForeignKeyProperty;
            DbExpression          foreignKeyColumn = this.GetPrimitiveMember(foreignKeyPropertyDescriptor.Property);
            DbExpression          joinCondition    = DbExpression.Equal(foreignKeyColumn, navigationObjectModel.PrimaryKey);
            DbJoinTableExpression joinTableExp     = new DbJoinTableExpression(foreignKeyPropertyDescriptor.IsNullable ? DbJoinType.LeftJoin : DbJoinType.InnerJoin, joinTableSeg, joinCondition);

            this.DependentTable.JoinTables.Add(joinTableExp);

            navigationObjectModel.DependentTable = joinTableExp;

            DbExpression condition = this.ParseCondition(navigationNode.Condition, navigationObjectModel, queryModel.ScopeTables);

            //AndWhere的条件放到join条件里去
            joinTableExp.AppendCondition(condition);

            navigationObjectModel.Filter = this.ParseCondition(navigationNode.Filter, navigationObjectModel, queryModel.ScopeTables);

            //queryModel.Filters.Add(navigationObjectModel.Filter);

            return(navigationObjectModel);
        }
Esempio n. 12
0
 public bool Equals(NavigationNode n)
 {
     return(Block == (n.Block));
 }
Esempio n. 13
0
    List <NavigationNode> FindPath(NavigationNode start, NavigationNode end, NavigationNode previousNode, int recurssionLevel)
    {
        int currentRecurssionLevel = recurssionLevel + 1; //infinite loop guard.

        if (currentRecurssionLevel > sceneNodes.Length)
        {
            //print("Reached max traversal range" + recurssionLevel ); //test
            return(null);
        }

        int results = 0;

        List <NavigationNode>[] resultPathsAtNode = new List <NavigationNode> [start.adjacentNodes.Length];    //there are max of n potential solutions per node; n = #of adjacent nodes.

        foreach (NavigationNode node in start.adjacentNodes)
        {
            List <NavigationNode> subPath = new List <NavigationNode>();

            if (node == end) //reached target
            {
                subPath.Add(node);
                subPath.Add(start);
                return(subPath);
            }
            else if (currentRecurssionLevel > 0 && start.adjacentNodes.Length == 1) //a dead end, only one adjacent node which is the one we came from. The first argument tests that
            {                                                                       //we aren't at start point, else algorithm would fail if we started from a room with one exit.
                return(null);
            }
            else if (node.nodeID != previousNode.nodeID)
            {
                subPath = FindPath(node, end, start, currentRecurssionLevel);
                if (subPath != null) //we have a solution for the current subnote, we add it to the solutions list (for current recussion-level) and increment results count.
                {
                    subPath.Add(start);
                    resultPathsAtNode[results] = subPath;
                    results++;
                }
            }
        }

        if (results < 1) //the loop above didn't return any valid path for all sub-nodes
        {
            return(null);
        }
        else if (results == 1) //we have only one solution
        {
            return(resultPathsAtNode[0]);
        }
        else    //we have multiple solutions, so we compared to find the shortest one
        {       //TODO modify the test bellow to acount for distance between nodes as well (more computational cost?)
            List <NavigationNode> shortestPath = resultPathsAtNode[0];

            for (int i = 1; i < results; i++)
            {
                if (resultPathsAtNode[i].Count < shortestPath.Count)
                {
                    shortestPath = resultPathsAtNode[i];
                }
            }
            return(shortestPath);
        }
    }
    public static Stack <NavigationNode> GetPath(NavigationNode start, NavigationNode end)
    {
        Heap <NavigationNode> frontier = new Heap <NavigationNode>(100);
        Dictionary <NavigationNode, NavigationNode> cameFrom = new Dictionary <NavigationNode, NavigationNode>();

        cameFrom.Add(start, null);
        Dictionary <NavigationNode, float> costSoFar = new Dictionary <NavigationNode, float>();

        costSoFar.Add(start, 0);
        start.cost = 0;
        frontier.Add(start);

        while (frontier.Count > 0)
        {
            NavigationNode current = frontier.Pop();
            if (current == end)
            {
                break;
            }

            foreach (NavigationNode next in current.connectedNodes)
            {
                float newCost = current.cost + Vector3.Distance(next.transform.position, current.transform.position);

                float oldCost   = 0;
                bool  keyExists = costSoFar.TryGetValue(next, out oldCost);

                if (!keyExists || newCost < oldCost)
                {
                    if (!keyExists)
                    {
                        costSoFar.Add(next, newCost);
                    }
                    else
                    {
                        costSoFar[next] = newCost;
                    }

                    next.cost = newCost + Heuristic(end, next); //Cost to be used with ICompareable

                    frontier.Add(next);
                    if (!cameFrom.ContainsKey(next))
                    {
                        cameFrom.Add(next, null);
                    }
                    cameFrom[next] = current;
                }
            }
        }

        Stack <NavigationNode> finalPath = new Stack <NavigationNode>();
        NavigationNode         n         = end;

        finalPath.Push(n);

        while (n != start)
        {
            n = cameFrom[n];
            finalPath.Push(n);
        }

        return(finalPath);
    }
Esempio n. 15
0
        private TreeViewItem CreateTreeViewItem(string text, string icon, string tooltip, NavigationNode node)
        {
            TreeViewItem child = new TreeViewItem();

            child.IsExpanded = true;
            child.Tag        = node;
            DockPanel pan = new DockPanel();

            if (!string.IsNullOrEmpty(tooltip))
            {
                child.ToolTip = tooltip;
            }

            if (string.IsNullOrEmpty(icon))
            {
                icon = "/UIShell.WpfShellPlugin;component/Assets/DefaultNode.png";
            }

            if (!string.IsNullOrEmpty(icon))
            {
                var         uri  = new Uri(icon, UriKind.RelativeOrAbsolute);
                BitmapImage logo = new BitmapImage();
                logo.BeginInit();
                logo.UriSource = uri;
                logo.EndInit();
                var image = new Image();
                image.Source = logo;
                image.Height = 16;
                image.Width  = 16;
                image.Margin = new Thickness(0, 0, 4, 0);
                pan.Children.Add(image);
            }

            pan.Children.Add(new TextBlock(new Run(text)));
            child.Header = pan;
            return(child);
        }
Esempio n. 16
0
 List <NavigationNode> FindPath(NavigationNode start, NavigationNode end)
 {
     return(FindPath(start, end, start, -1));
 }
Esempio n. 17
0
    private void Update()
    {
        SetTriggerAreaDirection();

        if (!CheckIfOnTransitionFloor())
        {
            navigation.CheckForCurrentFloor(transform, apostleCollisionHandler.CapsuleCollider2D, ref currentFloor,
                                            ref currentTransitionFloor);
        }
        else
        {
            if (apostleStatusVariables.isClimbingObstacle)
            {
                navigation.CheckForCurrentTransitionFloor(transform, apostleCollisionHandler.CapsuleCollider2D,
                                                          ref currentFloor,
                                                          ref currentTransitionFloor,
                                                          TransitionFloorType.Obstacle);
            }
            else if (apostleStatusVariables.isClimbingLadder)
            {
                navigation.CheckForCurrentTransitionFloor(transform, apostleCollisionHandler.CapsuleCollider2D,
                                                          ref currentFloor,
                                                          ref currentTransitionFloor,
                                                          TransitionFloorType.Ladder);
            }
            else if (apostleStatusVariables.isClimbingStairs)
            {
                navigation.CheckForCurrentTransitionFloor(transform, apostleCollisionHandler.CapsuleCollider2D,
                                                          ref currentFloor,
                                                          ref currentTransitionFloor,
                                                          TransitionFloorType.Stairs);
            }
        }


        if (Time.time >= currentAggroTime && apostleStatusVariables.isAggroed && !apostleStatusVariables.inAggroRange)
        {
            currentAimNode = new NavigationNode(startPointTransform, TransitionFloorType.None, null);
            apostleStatusVariables.isAggroed = false;
        }

        apostleStatusVariables.isPatrolling = !apostleStatusVariables.isAggroed;

        if (apostleStatusVariables.isPatrolling)
        {
            foreach (var node in navigationNodes)
            {
                if (currentAimNode.transform == node.transform &&
                    MathHelpers.Approximately(transform.position, node.transform.position,
                                              apostleCollisionHandler.CapsuleCollider2D.size.y / 2))
                {
                    var index = navigationNodes.FindIndex(lambdaExpression =>
                                                          lambdaExpression.Equals(node));

                    if (navigationNodes.Count == index + 1)
                    {
                        navigationNodes.Reverse();
                        break;
                    }


                    currentAimNode = navigationNodes[index + 1];
                    if (currentAimNode.type == TransitionFloorType.Obstacle)
                    {
                        if (currentAimNode.transform.position.y < transform.position.y)
                        {
                            currentAimNode = navigationNodes[index + 2];
                        }
                    }
                }
            }
        }


        if (currentAimNode.transform != null)
        {
            movementDirectionValue =
                MovementDirection(currentAimNode.transform.position);

            switch (currentAimNode.type)
            {
            case TransitionFloorType.None:
                if (currentAimNode.transform.gameObject.layer == LayerMask.NameToLayer("Player"))
                {
                    attackPressValue = false;
                    if (Physics2D.Raycast(transform.position,
                                          currentAimNode.transform.position - transform.position, rangeForAttack,
                                          LayerMask.GetMask("Player")).collider != null)
                    {
                        attackPressValue = true;
                    }
                }
                break;

            case TransitionFloorType.Ladder:
                break;

            case TransitionFloorType.Obstacle:
                climbObstacleValue =
                    MathHelpers.Approximately(transform.position, currentAimNode.transform.position,
                                              apostleCollisionHandler.CapsuleCollider2D.size.y);
                break;

            case TransitionFloorType.Stairs:
                break;

            case TransitionFloorType.Consecutive:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        //Debug.Log(!currentAimNode.Equals(null) ? currentAimNode.transform.name : "");
    }
Esempio n. 18
0
        public HomeWindowVM()
        {
            userName = Application.Current.Properties["LoggedInUserNameHome"].ToString();
            var version = ConfigurationManager.AppSettings["CurrentApplicationVersion"].ToString();

            AppVersion = string.Format("Diversified {0}", version);
            char[] objRolesSplit = new char[] { ',' };
            var    objRoles      = Application.Current.Properties["LoggedInUserRole"].ToString().Split(objRolesSplit);

            NavigationNode portStorageNode = null;

            if (objRoles.Contains(UserRoles.Administrator.GetUserRoleToCompare()))
            {
                NavigationNode adminNode = rootNavigationNode.AddChild("Admin");
                adminNode.Icon = "";
                adminNode.AddChild("Add New User", typeof(AddAdminUser)).Icon = "";
                adminNode.AddChild("Customer Admin", typeof(View.UserControls.CustomerAdmin.CustomerAdmin)).Icon = "";
                adminNode.AddChild("Code Admin", typeof(CodesTableAdmin)).Icon = "";
                adminNode.AddChild("Billing Period Admin", typeof(BillingPeriodAdmin)).Icon = "";
                adminNode.AddChild("System Settings Admin", typeof(SystemSettings)).Icon    = "";
                adminNode.AddChild("Company Information", typeof(CompanyInformation)).Icon  = "";
                //adminNode.AddChild("Add/Edit Billing Records", typeof(AddEditBillingRecords)).Icon = "";
            }
            if (objRoles.Contains(UserRoles.PortStorage.GetUserRoleToCompare()) || objRoles.Contains(UserRoles.Administrator.GetUserRoleToCompare()) || objRoles.Contains(UserRoles.Security.GetUserRoleToCompare()))
            {
                portStorageNode      = rootNavigationNode.AddChild("Port Storage");
                portStorageNode.Icon = "";

                if (objRoles.Contains(UserRoles.PortStorage.GetUserRoleToCompare()) || objRoles.Contains(UserRoles.Administrator.GetUserRoleToCompare()))
                {
                    portStorageNode.AddChild("Add-Edit PS Records", typeof(PortStorageVehicalLocator)).Icon    = "";
                    portStorageNode.AddChild("Request Processing", typeof(PostStorageRequestProcessing)).Icon  = "";
                    portStorageNode.AddChild("Date Out Processing", typeof(PostStorageDateOutProcessing)).Icon = "";
                    portStorageNode.AddChild("Storage Vehicle Outgate", typeof(StorageVehicleOutgate)).Icon    = "";
                }
                if (objRoles.Contains(UserRoles.Security.GetUserRoleToCompare()))
                {
                    var existingOutgateNode = portStorageNode.Children.Where(x => x.Name.Equals("Storage Vehicle Outgate", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if (existingOutgateNode == null)
                    {
                        portStorageNode.AddChild("Storage Vehicle Outgate", typeof(StorageVehicleOutgate)).Icon = "";
                    }
                }
                if (objRoles.Contains(UserRoles.PortStorage.GetUserRoleToCompare()) || objRoles.Contains(UserRoles.Administrator.GetUserRoleToCompare()))
                {
                    portStorageNode.AddChild("Port Storage Reports", typeof(View.Reports.Report)).Icon = "";

                    //portStorageNode.AddChild("Import/Export", typeof(PortStorageImportExport)).Icon = "";
                    portStorageNode.AddChild("Vehicle Import YMS", typeof(PortStorageVehicleImportYMSWindow)).Icon = "";
                    portStorageNode.AddChild("Location Import YMS", typeof(AppWorks.UI.View.PortStorageImportExport.PortStorageLocationImportYMSWindow)).Icon = "";
                    portStorageNode.AddChild("Customer Web Portal", typeof(WebPortalAdministration)).Icon = "";
                    portStorageNode.AddChild("Port Storage Inventory", typeof(PortStorageVehicleInventoryDetails)).Icon = "";
                }
            }

            if (objRoles.Contains(UserRoles.Administrator.GetUserRoleToCompare()))
            {
                NavigationNode billingNode = rootNavigationNode.AddChild("Billing");
                billingNode.Icon = "";
                billingNode.AddChild("Generate Invoices", typeof(GeneratePortStorageInvoices)).Icon  = "";
                billingNode.AddChild("Add-Edit Invoice Records", typeof(AddEditInvoiceRecords)).Icon = "";
                billingNode.AddChild("Billing Record Export", typeof(BillingRecordExport)).Icon      = "";
            }
            Nodes = new ObservableCollection <NavigationNode>(rootNavigationNode.Children);
            //select default node

            var addEditRecords = portStorageNode.Children.SingleOrDefault(c => c.Name == "Add-Edit PS Records");

            if (addEditRecords == null)
            {
                addEditRecords = portStorageNode.Children.FirstOrDefault();
            }

            if (addEditRecords != null && portStorageNode != null)
            {
                portStorageNode.IsExpanded       = true;
                addEditRecords.IsSelected        = true;
                addEditRecords.IsFirstTimeLoaded = true;
            }
            if (!objRoles.Contains(UserRoles.Security.GetUserRoleToCompare()))
            {
                AutoLogOffHelper.MakeAutoLogOffEvent += new AutoLogOffHelper.MakeAutoLogOff(LoginoutUser);
                AutoLogOffHelper.StartAutoLogoffOption();
            }

            NavigateTo(addEditRecords);
        }
Esempio n. 19
0
        ComplexObjectModel GenCollectionElementObjectModel(TypeDescriptor elementTypeDescriptor, NavigationNode navigationNode, QueryModel queryModel)
        {
            DbTable           dbTable      = elementTypeDescriptor.Table;
            DbTableExpression tableExp     = new DbTableExpression(dbTable);
            string            alias        = queryModel.GenerateUniqueTableAlias(dbTable.Name);
            DbTableSegment    joinTableSeg = new DbTableSegment(tableExp, alias, queryModel.FromTable.Table.Lock);

            DbTable            aliasTable         = new DbTable(alias);
            ComplexObjectModel elementObjectModel = elementTypeDescriptor.GenObjectModel(aliasTable);

            elementObjectModel.NullChecking = elementObjectModel.PrimaryKey;

            ComplexPropertyDescriptor navigationDescriptor = elementTypeDescriptor.ComplexPropertyDescriptors.Where(a => a.PropertyType == this.ObjectType).FirstOrDefault();

            if (navigationDescriptor == null)
            {
                throw new ChloeException($"You have to define a navigation property which type is '{this.ObjectType.FullName}' on class '{elementTypeDescriptor.Definition.Type.FullName}'.");
            }

            DbExpression          elementForeignKeyColumn = elementObjectModel.GetPrimitiveMember(navigationDescriptor.ForeignKeyProperty.Property);
            DbExpression          joinCondition           = DbExpression.Equal(this.PrimaryKey, elementForeignKeyColumn);
            DbJoinTableExpression joinTableExp            = new DbJoinTableExpression(DbJoinType.LeftJoin, joinTableSeg, joinCondition);

            this.DependentTable.JoinTables.Add(joinTableExp);

            elementObjectModel.DependentTable = joinTableExp;
            var condition = this.ParseCondition(navigationNode.Condition, elementObjectModel, queryModel.ScopeTables);

            //AndWhere的条件放到join条件里去
            joinTableExp.AppendCondition(condition);

            elementObjectModel.Filter = this.ParseCondition(navigationNode.Filter, elementObjectModel, queryModel.ScopeTables);

            bool orderByPrimaryKeyExists = queryModel.Orderings.Where(a => a.Expression == this.PrimaryKey).Any();

            if (!orderByPrimaryKeyExists)
            {
                //结果集分组
                DbOrdering ordering = new DbOrdering(this.PrimaryKey, DbOrderType.Asc);
                queryModel.Orderings.Add(ordering);
            }

            //queryModel.Filters.Add(elementObjectModel.Filter);

            return(elementObjectModel);
        }
Esempio n. 20
0
        private static void addEntityToNavigationNode(ref EntitiesIndexedByNavigationNodes p_entitiesIndexedByNavigationNodes, Entity p_entity, NavigationNode p_navigationNode)
        {
            if (!p_entitiesIndexedByNavigationNodes.Entities.ContainsKey(p_navigationNode))
            {
                p_entitiesIndexedByNavigationNodes.Entities.Add(p_navigationNode, new List <Entity>());
            }

            List <Entity> l_navigationNodeEntities = p_entitiesIndexedByNavigationNodes.Entities[p_navigationNode];

            if (!l_navigationNodeEntities.Contains(p_entity))
            {
                l_navigationNodeEntities.Add(p_entity);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Deletes a navigation node from the quickLaunch or top navigation bar
        /// </summary>
        /// <param name="web">Site to be processed - can be root web or sub site</param>
        /// <param name="nodeTitle">the title of node to delete</param>
        /// <param name="parentNodeTitle">if string.Empty, then will delete this node as top level node</param>
        /// <param name="navigationType">the type of navigation, quick launch, top navigation or search navigation</param>
        public static void DeleteNavigationNode(this Web web, string nodeTitle, string parentNodeTitle, NavigationType navigationType)
        {
            web.Context.Load(web, w => w.Navigation.QuickLaunch, w => w.Navigation.TopNavigationBar);
            web.Context.ExecuteQueryRetry();
            NavigationNode deleteNode = null;

            try
            {
                if (navigationType == NavigationType.QuickLaunch)
                {
                    var quickLaunch = web.Navigation.QuickLaunch;
                    if (string.IsNullOrEmpty(parentNodeTitle))
                    {
                        deleteNode = quickLaunch.SingleOrDefault(n => n.Title == nodeTitle);
                    }
                    else
                    {
                        foreach (var nodeInfo in quickLaunch)
                        {
                            if (nodeInfo.Title != parentNodeTitle)
                            {
                                continue;
                            }

                            web.Context.Load(nodeInfo.Children);
                            web.Context.ExecuteQueryRetry();
                            deleteNode = nodeInfo.Children.SingleOrDefault(n => n.Title == nodeTitle);
                        }
                    }
                }
                else if (navigationType == NavigationType.TopNavigationBar)
                {
                    var topLink = web.Navigation.TopNavigationBar;
                    if (string.IsNullOrEmpty(parentNodeTitle))
                    {
                        deleteNode = topLink.SingleOrDefault(n => n.Title == nodeTitle);
                    }
                    else
                    {
                        foreach (var nodeInfo in topLink)
                        {
                            if (nodeInfo.Title != parentNodeTitle)
                            {
                                continue;
                            }
                            web.Context.Load(nodeInfo.Children);
                            web.Context.ExecuteQueryRetry();
                            deleteNode = nodeInfo.Children.SingleOrDefault(n => n.Title == nodeTitle);
                        }
                    }
                }
                else if (navigationType == NavigationType.SearchNav)
                {
                    var nodeCollection = web.LoadSearchNavigation();
                    deleteNode = nodeCollection.SingleOrDefault(n => n.Title == nodeTitle);
                }
            }
            finally
            {
                deleteNode?.DeleteObject();
                web.Context.ExecuteQueryRetry();
            }
        }
Esempio n. 22
0
        // A*
        protected bool FindRoute(Block startBlock, Block endBlock, out List <Block> path)
        {
            List <NavigationNode> openList   = new List <NavigationNode>();
            List <Block>          closedList = new List <Block>();

            // we dont need to consider our starting point
            closedList.Add(startBlock);

            // but we have to start somewhere
            foreach (Block block in startBlock.AdjacentBlocks)
            {
                if (block.Traversable)
                {
                    openList.Add(new NavigationNode(null, block, block.NavigationWeight, CalculateHeuristic(block, endBlock)));
                }
                else
                {
                    closedList.Add(block);
                }
            }

            // run the algorithm
            while (openList.Count > 0)
            {
                // get the next block with lowest score
                openList.Sort((x, y) => x.MovementCost.CompareTo(y.MovementCost));
                NavigationNode currentNode = openList[0];
                openList.RemoveAt(0);
                closedList.Add(currentNode.Block);

                // if we are at the end we can leave
                if (currentNode.Block == endBlock)
                {
                    path = new List <Block>();
                    while (currentNode != null)
                    {
                        // path.Insert(path.Count, currentNode.Block);
                        path.Insert(0, currentNode.Block);
                        currentNode = currentNode.Parent;
                    }
                    return(true);
                }

                // calculate and add our adjacent blocks to the proper lists
                foreach (Block block in currentNode.Block.AdjacentBlocks)
                {
                    if (closedList.Contains(block))
                    {
                        continue;
                    }

                    // handle if we are already in the open list
                    int nExistingIndex = openList.FindIndex((x) => x.Block == block);
                    if (nExistingIndex < 0)
                    {
                        if (block.Traversable)
                        {
                            openList.Add(new NavigationNode(currentNode, block, currentNode.MovementCost + block.NavigationWeight, CalculateHeuristic(block, endBlock)));
                        }
                        else
                        {
                            closedList.Add(block);
                        }
                    }
                    else
                    {
                        // if a lower score, update the parent
                        NavigationNode existingNode = openList[nExistingIndex];
                        if (existingNode.Score < currentNode.Score)
                        {
                            existingNode.MovementCost = currentNode.MovementCost + 1.0f;
                            existingNode.Parent       = currentNode;
                        }
                    }
                }
            }


            // unable to find route
            path = null;
            return(false);
        }
Esempio n. 23
0
        public void Remove()
        {
            base.ThrowIfCannotActAsOwner();
            StoreObjectId nodeId = (StoreObjectId)base.GetParameter("srcNId");
            NavigationNodeGroupSection navigationNodeGroupSection = (NavigationNodeGroupSection)base.GetParameter("GS");
            NavigationNodeCollection   navigationNodeCollection   = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, navigationNodeGroupSection);
            List <OwaStoreObjectId>    list           = new List <OwaStoreObjectId>();
            NavigationNode             navigationNode = navigationNodeCollection.FindNavigationNodeByNodeId(nodeId);

            if (navigationNode == null)
            {
                base.RenderPartialFailure(-289549140, OwaEventHandlerErrorCode.NotSet);
            }
            else
            {
                OperationResult operationResult = (OperationResult)0;
                if (navigationNodeGroupSection != NavigationNodeGroupSection.First)
                {
                    List <NavigationNodeFolder> list2 = new List <NavigationNodeFolder>();
                    if (navigationNode is NavigationNodeFolder)
                    {
                        list2.Add(navigationNode as NavigationNodeFolder);
                    }
                    else if (navigationNode is NavigationNodeGroup)
                    {
                        NavigationNodeGroup navigationNodeGroup = navigationNode as NavigationNodeGroup;
                        foreach (NavigationNodeFolder item in navigationNodeGroup.Children)
                        {
                            list2.Add(item);
                        }
                    }
                    foreach (NavigationNodeFolder navigationNodeFolder in list2)
                    {
                        if (navigationNodeFolder.IsValid)
                        {
                            OwaStoreObjectId owaStoreObjectId = OwaStoreObjectId.CreateFromNavigationNodeFolder(base.UserContext, navigationNodeFolder);
                            MailboxSession   mailboxSession   = owaStoreObjectId.IsArchive ? ((MailboxSession)owaStoreObjectId.GetSession(base.UserContext)) : base.UserContext.MailboxSession;
                            if (navigationNodeFolder.IsFolderInSpecificMailboxSession(mailboxSession))
                            {
                                if (Utilities.IsSpecialFolderForSession(mailboxSession, navigationNodeFolder.FolderId))
                                {
                                    throw new OwaEventHandlerException("Cannot delete default folders.", LocalizedStrings.GetNonEncoded(-1164567320), true);
                                }
                                if (operationResult == (OperationResult)0)
                                {
                                    operationResult = OperationResult.Succeeded;
                                }
                                AggregateOperationResult aggregateOperationResult = mailboxSession.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                                {
                                    navigationNodeFolder.FolderId
                                });
                                if (aggregateOperationResult.OperationResult == OperationResult.Succeeded)
                                {
                                    list.Add(OwaStoreObjectId.CreateFromNavigationNodeFolder(base.UserContext, navigationNodeFolder));
                                }
                                else
                                {
                                    operationResult = OperationResult.PartiallySucceeded;
                                }
                            }
                        }
                    }
                    if (operationResult != (OperationResult)0 && list.Count == 0)
                    {
                        operationResult = OperationResult.Failed;
                    }
                    if (operationResult == OperationResult.Failed)
                    {
                        base.RenderPartialFailure(1041829989, OwaEventHandlerErrorCode.NotSet);
                    }
                    else if (operationResult == OperationResult.PartiallySucceeded)
                    {
                        base.RenderPartialFailure(995407892, OwaEventHandlerErrorCode.NotSet);
                    }
                }
                else
                {
                    NavigationNodeFolder navigationNodeFolder2 = navigationNode as NavigationNodeFolder;
                    if (navigationNodeFolder2 != null && navigationNodeFolder2.IsFilteredView)
                    {
                        OwaStoreObjectId owaStoreObjectId2 = OwaStoreObjectId.CreateFromNavigationNodeFolder(base.UserContext, navigationNodeFolder2);
                        using (SearchFolder searchFolder = SearchFolder.Bind(owaStoreObjectId2.GetSession(base.UserContext), owaStoreObjectId2.StoreObjectId, FolderList.FolderTreeQueryProperties))
                        {
                            searchFolder[FolderSchema.SearchFolderAllowAgeout] = true;
                            searchFolder.DisplayName = Utilities.GetRandomNameForTempFilteredView(base.UserContext);
                            searchFolder.Save();
                        }
                    }
                }
                if (operationResult == (OperationResult)0 || operationResult == OperationResult.Succeeded)
                {
                    if (navigationNodeCollection.RemoveFolderOrGroupByNodeId(nodeId) != null)
                    {
                        navigationNodeCollection.Save(base.UserContext.MailboxSession);
                    }
                }
                else if (operationResult == OperationResult.PartiallySucceeded)
                {
                    foreach (OwaStoreObjectId owaStoreObjectId3 in list)
                    {
                        navigationNodeCollection.RemoveFolderByLegacyDNandId(owaStoreObjectId3.MailboxOwnerLegacyDN ?? base.UserContext.MailboxOwnerLegacyDN, owaStoreObjectId3.StoreObjectId);
                    }
                    navigationNodeCollection.Save(base.UserContext.MailboxSession);
                }
            }
            NavigationTreeDirtyFlag navigationTreeDirtyFlag = NavigationTreeDirtyFlag.None;

            if (navigationNodeGroupSection == NavigationNodeGroupSection.First)
            {
                navigationTreeDirtyFlag = NavigationTreeDirtyFlag.Favorites;
            }
            else
            {
                if (list.Count > 0)
                {
                    List <FolderTreeNode> list3 = FolderTreeNode.CreateDeletedNodesWithDirtyCheck(base.UserContext, list, out navigationTreeDirtyFlag);
                    this.Writer.Write("<div id=tn>");
                    foreach (FolderTreeNode folderTreeNode in list3)
                    {
                        folderTreeNode.RenderUndecoratedNode(this.Writer);
                    }
                    this.Writer.Write("</div>");
                }
                switch (navigationNodeGroupSection)
                {
                case NavigationNodeGroupSection.Calendar:
                    navigationTreeDirtyFlag |= NavigationTreeDirtyFlag.Calendar;
                    break;

                case NavigationNodeGroupSection.Contacts:
                    navigationTreeDirtyFlag |= NavigationTreeDirtyFlag.Contact;
                    break;

                case NavigationNodeGroupSection.Tasks:
                    navigationTreeDirtyFlag |= NavigationTreeDirtyFlag.Task;
                    break;
                }
            }
            RenderingUtilities.RenderNavigationTreeDirtyFlag(this.Writer, base.UserContext, navigationTreeDirtyFlag, (NavigationModule[])base.GetParameter("cms"));
        }
Esempio n. 24
0
 public static float actionPointBetweenNavigationNodes(NavigationNode p_navigationNode1, NavigationNode p_navigationNode2)
 {
     return(worldDistanceToActionPoint(math.distance(p_navigationNode1.LocalPosition, p_navigationNode2.LocalPosition)));
 }
Esempio n. 25
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            if (sender is PlayerCommandSender player)
            {
                Player s = Player.Get(player.PlayerId);
                if (!s.CheckPermission("npc.all"))
                {
                    response = "Access denied!";
                    return(false);
                }
                if (!Round.IsStarted)
                {
                    response = "Round is not started!";
                    return(false);
                }
                if (arguments.Count == 0)
                {
                    response = "Available subcommands: [create, list, remove, clean, rebuild, sav, show]";
                    return(false);
                }
                NavigationNode created_node;
                Pickup         pickup;
                switch (arguments.At(0))
                {
                case "create":
                    string name = (++new_node_id).ToString();
                    if (!s.IsAlive)
                    {
                        response = "You must be alive to use this!";
                        return(false);
                    }
                    created_node = NavigationNode.Create(s.Position, name, s.CurrentRoom.Name.RemoveBracketsOnEndOfName());
                    if (arguments.Count > 1)
                    {
                        string[] AvailableItemTypes = arguments.At(1).Split(',');
                        foreach (string type in AvailableItemTypes)
                        {
                            created_node.PossibleItemTypes.Add(type.Trim());
                        }
                    }
                    pickup        = ItemType.SCP018.Spawn(1f, created_node.Position + new UnityEngine.Vector3(0, 0.5f, 0));
                    pickup.Locked = true;
                    foreach (NavigationNode d in NavigationNode.AllNodes.Values.Where(nd => nd != created_node && Vector3.Distance(nd.Position, created_node.Position) < Plugin.Instance.Config.NavNodeMapperMaxDistance))
                    {
                        created_node.LinkedNodes.Add(d);
                        d.LinkedNodes.Add(created_node);

                        Log.Info($"Linked {created_node.Name} and {d.Name}");
                    }
                    response = "Created node!";
                    break;

                case "list":
                    int id = 0;
                    foreach (NavigationNode node in NavigationNode.AllNodes.Values)
                    {
                        s.RemoteAdminMessage($"{id} - {node.Name}");
                    }
                    response = "List end";
                    break;

                case "remove":
                    if (arguments.Count <= 1)
                    {
                        response = "You need to provide node name!";
                        return(false);
                    }
                    try
                    {
                        NavigationNode rnode = NavigationNode.AllNodes[arguments.At(1)];
                        NavigationNode.AllNodes.Remove(rnode.Name);
                        UnityEngine.Object.Destroy(rnode);
                        response = "Node removed";
                    }
                    catch (KeyNotFoundException)
                    {
                        response = "Node not found!";
                        return(false);
                    }
                    break;

                case "clean":
                    NavigationNode.Clear();
                    response = "Removed all nodes!";
                    break;

                case "rebuild":
                    NavigationNode.Clear();
                    Methods.GenerateNavGraph();
                    response = "Rebuilt navigation graph";
                    break;

                case "sav":
                    Dictionary <string, List <NavigationNode.NavNodeSerializationInfo> > manual_mappings = new Dictionary <string, List <NavigationNode.NavNodeSerializationInfo> >();
                    IEnumerable <NavigationNode> to_serialize = NavigationNode.AllNodes.Values.Where(n => n.SInfo != null);
                    foreach (NavigationNode node in to_serialize)
                    {
                        node.SInfo.ItemTypes = new List <string>(node.PossibleItemTypes);
                        if (!manual_mappings.ContainsKey(node.Room.RemoveBracketsOnEndOfName()))
                        {
                            List <NavigationNode.NavNodeSerializationInfo> nodes = new List <NavigationNode.NavNodeSerializationInfo>
                            {
                                node.SInfo
                            };
                            manual_mappings.Add(node.Room.RemoveBracketsOnEndOfName(), nodes);
                        }
                        else
                        {
                            manual_mappings[node.Room.RemoveBracketsOnEndOfName()].Add(node.SInfo);
                        }
                    }
                    FileStream   fs         = File.Open(Config.NPCs_nav_mappings_path, FileMode.Truncate, FileAccess.Write);
                    StreamWriter sw         = new StreamWriter(fs);
                    var          serializer = new SerializerBuilder().Build();
                    var          yaml       = serializer.Serialize(manual_mappings);
                    sw.Write(yaml);
                    sw.Close();
                    response = "Saved manual navigation mappings!";
                    break;

                case "show":
                    foreach (NavigationNode node in NavigationNode.AllNodes.Values)
                    {
                        pickup        = ItemType.SCP018.Spawn(1f, node.Position + new UnityEngine.Vector3(0, 0.5f, 0));
                        pickup.Locked = true;
                    }
                    response = "Marked nodes!";
                    break;

                case "items":
                    if (arguments.Count <= 2)
                    {
                        response = "You need to provide node name and at least one item group!";
                        return(false);
                    }
                    try
                    {
                        NavigationNode rnode = NavigationNode.AllNodes[arguments.At(1)];
                        for (int i = 2; i < arguments.Count; i++)
                        {
                            if (rnode.PossibleItemTypes.Add(arguments.At(i)))
                            {
                                s.RemoteAdminMessage($"Added type: {arguments.At(i)}");
                            }
                        }
                        response = "";
                    }
                    catch (KeyNotFoundException)
                    {
                        response = "Node not found!";
                        return(false);
                    }
                    break;

                case "r_items":
                    if (arguments.Count <= 2)
                    {
                        response = "You need to provide node name and at least one item group!";
                        return(false);
                    }
                    try
                    {
                        NavigationNode rnode = NavigationNode.AllNodes[arguments.At(1)];
                        for (int i = 2; i < arguments.Count; i++)
                        {
                            if (rnode.PossibleItemTypes.Remove(arguments.At(i)))
                            {
                                s.RemoteAdminMessage($"Removed type: {arguments.At(i)}");
                            }
                        }
                        response = "";
                    }
                    catch (KeyNotFoundException)
                    {
                        response = "Node not found!";
                        return(false);
                    }
                    break;

                case "info":
                    if (arguments.Count <= 1)
                    {
                        response = "You need to provide node name!";
                        return(false);
                    }
                    try
                    {
                        NavigationNode rnode = NavigationNode.AllNodes[arguments.At(1)];
                        s.RemoteAdminMessage("Linked nodes:");
                        foreach (NavigationNode node in rnode.LinkedNodes)
                        {
                            s.RemoteAdminMessage(node.Name);
                        }
                        s.RemoteAdminMessage($"Attached door: {rnode.AttachedDoor?.DoorName}");
                        s.RemoteAdminMessage($"Attached elevator: {rnode.AttachedElevator}");
                        response = "";
                    }
                    catch (KeyNotFoundException)
                    {
                        response = "Node not found!";
                        return(false);
                    }
                    break;

                default:
                    response = "Unknown subcommand!";
                    return(false);
                }
            }
            else
            {
                response = "Only players can use this!";
                return(false);
            }
            return(true);
        }
Esempio n. 26
0
    /**
     * <summary>
     * Build navigation nodes
     * </summary>
     *
     * <returns>
     * void
     * </returns>
     */
    public void BuildNavigation()
    {
        Bounds  bounds     = this.Ground.GetComponent <Renderer>().bounds;
        Vector3 bottomLeft = new Vector3(bounds.min.x, bounds.max.y, bounds.min.z);
        Vector3 topRight   = new Vector3(bounds.max.x, bounds.max.y, bounds.max.z);

        // Initial new nodes dictionary
        this.nodes = new Dictionary <int, Dictionary <int, NavigationNode> >();

        Debug.Log("Building Navigation");

        int id = 0;

        // Map the mesh
        for (int x = Mathf.RoundToInt(bottomLeft.x); x < Mathf.RoundToInt(topRight.x); x++)
        {
            if (!this.nodes.ContainsKey(x))
            {
                this.nodes[x] = new Dictionary <int, NavigationNode>();
            }

            for (int z = Mathf.RoundToInt(bottomLeft.z); z < Mathf.RoundToInt(topRight.z); z++)
            {
                Vector3      rayPosition = new Vector3(x, bounds.max.y + 1f, z);
                RaycastHit[] hits        = Physics.RaycastAll(rayPosition, Vector3.down * Mathf.Abs(bounds.max.y));

                foreach (RaycastHit hit in hits)
                {
                    // Create navigation point
                    if (hit.transform.tag != "Navigation")
                    {
                        this.Obstructs.Add(new Vector3(x, 0, z));
                        continue;
                    }

                    Vector3 navigationPoint = hit.point;

                    GameObject newNavigationNode = MonoBehaviour.Instantiate(
                        Resources.Load("Prefabs/Navigations/Navigation Node") as GameObject
                        );

                    newNavigationNode.transform.position = navigationPoint;

                    // Build the navigation node
                    NavigationNode navigationNode = new NavigationNode();
                    navigationNode.ID = id;
                    navigationNode.X  = x;
                    navigationNode.Z  = z;

                    navigationNode.Position = navigationPoint;
                    //navigationNode.TemporaryReference = newNavigationNode;

                    this.nodes[x][z] = navigationNode;

                    id++;
                }
            }
        }

        // Build and set neighbouring nodes
        this.BuildNeighbours();

        // Set obstructions
        this.SetObstructions();
    }
Esempio n. 27
0
        public void Include(NavigationNode navigationNode, QueryModel queryModel, bool handleCollection)
        {
            TypeDescriptor     descriptor           = EntityTypeContainer.GetDescriptor(this.ObjectType);
            PropertyDescriptor navigationDescriptor = descriptor.GetPropertyDescriptor(navigationNode.Property);

            if (navigationDescriptor.Definition.Kind == TypeKind.Primitive)
            {
                throw new NotSupportedException($"'{navigationNode.Property.Name}' is not navigation property.");
            }

            ComplexObjectModel objectModel = null;

            if (navigationDescriptor.Definition.Kind == TypeKind.Complex)
            {
                objectModel = this.GetComplexMember(navigationNode.Property);

                if (objectModel == null)
                {
                    objectModel = this.GenComplexObjectModel(navigationDescriptor as ComplexPropertyDescriptor, navigationNode, queryModel);
                    this.AddComplexMember(navigationNode.Property, objectModel);
                }
                else
                {
                    DbExpression condition = this.ParseCondition(navigationNode.Condition, objectModel, queryModel.ScopeTables);

                    var joinTable = objectModel.DependentTable as DbJoinTableExpression;
                    joinTable.AppendCondition(condition);
                }
            }
            else
            {
                if (!handleCollection)
                {
                    this.IncludeCollections.Add(navigationNode);
                    return;
                }

                CollectionObjectModel collectionModel = this.GetCollectionMember(navigationNode.Property);
                if (collectionModel == null)
                {
                    Type               collectionType        = navigationDescriptor.PropertyType;
                    TypeDescriptor     elementTypeDescriptor = EntityTypeContainer.GetDescriptor(collectionType.GetGenericArguments()[0]);
                    ComplexObjectModel elementModel          = this.GenCollectionElementObjectModel(elementTypeDescriptor, navigationNode, queryModel);
                    collectionModel = new CollectionObjectModel(this.ObjectType, navigationNode.Property, elementModel);
                    this.AddCollectionMember(navigationNode.Property, collectionModel);
                }
                else
                {
                    DbExpression condition = this.ParseCondition(navigationNode.Condition, collectionModel.ElementModel, queryModel.ScopeTables);

                    var joinTable = collectionModel.ElementModel.DependentTable as DbJoinTableExpression;
                    joinTable.AppendCondition(condition);
                }

                objectModel = collectionModel.ElementModel;
            }

            if (navigationNode.Next != null)
            {
                objectModel.Include(navigationNode.Next, queryModel, handleCollection);
            }
        }
 private static float Heuristic(NavigationNode to, NavigationNode from)
 {
     return(Vector3.Distance(to.transform.position, from.transform.position));
 }
Esempio n. 29
0
        private void OptimisePath()
        {
            //tries to look ahead and skip nodes we have clear unobstructed path to already

            Vector3 pos = ParentObject.Transform.AbsoluteTransform.Translation;

            pos.Y = 0;
            int indexToRemove = -1;

            for (int i = 1; i < path.Count; i++)
            {
                NavigationNode nodeToExamine = path[i];


                bool centerClear = false;
                bool leftClear   = false;
                bool rightClear  = false;

                Vector3 toNode = nodeToExamine.WorldPosition - pos;

                Vector3 perpendicularVec = Vector3.Cross(toNode, Vector3.Up);
                perpendicularVec.Y = 0;
                //width
                perpendicularVec *= 0.01f;

                //don't optimize route when we cross a hazard line boundary
                if (mapHandler.IntersectsHazardLine(pos, nodeToExamine.WorldPosition))
                {
                    continue;
                }


                //if we pass all 3 of these tests, this means we have clear LOS
                //to this node, wide enough to squeeze through. So we can skip prior nodes.
                if (!mapHandler.IntersectsLevel(pos, nodeToExamine.WorldPosition))
                {
                    centerClear = true;
                    if (!mapHandler.IntersectsLevel(pos + perpendicularVec, nodeToExamine.WorldPosition + perpendicularVec))
                    {
                        leftClear = true;
                        if (!mapHandler.IntersectsLevel(pos - perpendicularVec, nodeToExamine.WorldPosition - perpendicularVec))
                        {
                            rightClear    = true;
                            indexToRemove = i;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }



                DebugShapeRenderer.AddLine(pos, nodeToExamine.WorldPosition, rightClear ? Color.Blue : Color.Red);
                DebugShapeRenderer.AddLine(pos + perpendicularVec, nodeToExamine.WorldPosition + perpendicularVec, leftClear ? Color.Blue : Color.Red);
                DebugShapeRenderer.AddLine(pos - perpendicularVec, nodeToExamine.WorldPosition - perpendicularVec, rightClear ? Color.Blue : Color.Red);
            }

            if (indexToRemove != -1)
            {
                path.RemoveRange(0, indexToRemove);
            }
        }
Esempio n. 30
0
        private static NavigationTree[] CreateNavigationTreeByFolderLists(UserContext userContext, FolderList[] folderLists, params NavigationNodeCollection[] collections)
        {
            if (folderLists == null || folderLists.Length == 0)
            {
                throw new ArgumentNullException("folderLists");
            }
            if (collections.Length == 0)
            {
                return(new NavigationTree[0]);
            }
            string[]        array  = new string[collections.Length];
            StoreObjectId[] array2 = new StoreObjectId[collections.Length];
            for (int i = 0; i < collections.Length; i++)
            {
                array[i] = NavigationNode.GetFolderClass(collections[i].GroupSection);
                if (ObjectClass.IsOfClass(array[i], "IPF.Note"))
                {
                    throw new ArgumentException("Invalid group section. Can only be Calendar, Contact, Task");
                }
                switch (collections[i].GroupSection)
                {
                case NavigationNodeGroupSection.Calendar:
                    array2[i] = Utilities.TryGetDefaultFolderId(userContext.MailboxSession, DefaultFolderType.Calendar);
                    break;

                case NavigationNodeGroupSection.Contacts:
                    array2[i] = Utilities.TryGetDefaultFolderId(userContext.MailboxSession, DefaultFolderType.Contacts);
                    break;

                case NavigationNodeGroupSection.Tasks:
                    array2[i] = Utilities.TryGetDefaultFolderId(userContext.MailboxSession, DefaultFolderType.Tasks);
                    break;

                default:
                    throw new ArgumentException("Invalid group section. Can only be Calendar, Contact, Task");
                }
            }
            Dictionary <string, StoreObjectId>[] array3 = new Dictionary <string, StoreObjectId> [collections.Length];
            for (int j = 0; j < array.Length; j++)
            {
                array3[j] = new Dictionary <string, StoreObjectId>();
            }
            foreach (FolderList folderList in folderLists)
            {
                foreach (StoreObjectId storeObjectId in folderList.GetFolderIds())
                {
                    string itemClass = folderList.GetFolderProperty(storeObjectId, StoreObjectSchema.ContainerClass) as string;
                    for (int m = 0; m < array.Length; m++)
                    {
                        if (ObjectClass.IsOfClass(itemClass, array[m]))
                        {
                            string key = folderList.MailboxSession.MailboxOwnerLegacyDN.ToLowerInvariant() + storeObjectId.ToString();
                            array3[m][key] = storeObjectId;
                            break;
                        }
                    }
                }
            }
            bool flag = false;

            NavigationNodeGroupSection[] array4 = new NavigationNodeGroupSection[collections.Length];
            StoreObjectId storeObjectId2        = userContext.TryGetMyDefaultFolderId(DefaultFolderType.ToDoSearch);
            List <NavigationNodeFolder> list    = new List <NavigationNodeFolder>();

            for (int n = 0; n < collections.Length; n++)
            {
                list.Clear();
                bool flag2 = false;
                bool flag3 = false;
                NavigationNodeCollection   navigationNodeCollection   = collections[n];
                NavigationNodeGroupSection navigationNodeGroupSection = navigationNodeCollection.GroupSection;
                array4[n] = navigationNodeGroupSection;
                foreach (NavigationNodeGroup navigationNodeGroup in navigationNodeCollection)
                {
                    foreach (NavigationNodeFolder navigationNodeFolder in navigationNodeGroup.Children)
                    {
                        if (navigationNodeFolder.IsValid && navigationNodeFolder.FolderId != null && !navigationNodeFolder.IsFlagSet(NavigationNodeFlags.PublicFolderFavorite))
                        {
                            bool flag4 = false;
                            foreach (FolderList folderList2 in folderLists)
                            {
                                if (navigationNodeFolder.IsFolderInSpecificMailboxSession(folderList2.MailboxSession))
                                {
                                    flag4 = true;
                                    break;
                                }
                            }
                            if (flag4)
                            {
                                string key2 = navigationNodeFolder.MailboxLegacyDN.ToLowerInvariant() + navigationNodeFolder.FolderId.ToString();
                                if (!array3[n].Remove(key2))
                                {
                                    if (navigationNodeGroupSection == NavigationNodeGroupSection.Tasks && storeObjectId2 != null && storeObjectId2.Equals(navigationNodeFolder.FolderId))
                                    {
                                        flag3 = true;
                                    }
                                    else
                                    {
                                        list.Add(navigationNodeFolder);
                                    }
                                }
                                if (navigationNodeFolder.FolderId.Equals(array2[n]))
                                {
                                    foreach (FolderList folderList3 in folderLists)
                                    {
                                        if (navigationNodeFolder.IsFolderInSpecificMailboxSession(folderList3.MailboxSession))
                                        {
                                            string text    = (string)folderList3.GetFolderProperty(navigationNodeFolder.FolderId, FolderSchema.DisplayName);
                                            string subject = navigationNodeFolder.Subject;
                                            if (text != null && !text.Equals(subject))
                                            {
                                                navigationNodeFolder.Subject = text;
                                                flag2 = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (navigationNodeGroupSection == NavigationNodeGroupSection.Tasks && !flag3 && storeObjectId2 != null)
                {
                    navigationNodeCollection.InsertToDoFolderToGroup(userContext);
                    flag2 = true;
                }
                if (array3[n].Count > 0)
                {
                    foreach (KeyValuePair <string, StoreObjectId> keyValuePair in array3[n])
                    {
                        StoreObjectId value = keyValuePair.Value;
                        string        key3  = keyValuePair.Key;
                        string        y     = key3.Substring(0, key3.LastIndexOf(value.ToString()));
                        foreach (FolderList folderList4 in folderLists)
                        {
                            if (StringComparer.OrdinalIgnoreCase.Equals(folderList4.MailboxSession.MailboxOwnerLegacyDN, y))
                            {
                                navigationNodeCollection.AddMyFolderToGroup(userContext, folderList4.MailboxSession, folderList4.GetFolderProperties(value), folderList4.QueryPropertyMap);
                                break;
                            }
                        }
                    }
                    flag2 = true;
                }
                if (list.Count > 0)
                {
                    foreach (NavigationNodeFolder navigationNodeFolder2 in list)
                    {
                        navigationNodeCollection.RemoveFolderOrGroupByNodeId(navigationNodeFolder2.NavigationNodeId.ObjectId);
                    }
                    flag2 = true;
                }
                if (flag2)
                {
                    navigationNodeCollection.Save(userContext.MailboxSession);
                    flag = true;
                }
            }
            if (flag)
            {
                collections = NavigationNodeCollection.TryCreateNavigationNodeCollections(userContext, userContext.MailboxSession, array4);
            }
            NavigationTree[] array5 = new NavigationTree[collections.Length];
            for (int num4 = 0; num4 < collections.Length; num4++)
            {
                NavigationNodeCollection navigationNodeCollection2 = collections[num4];
                NavigationTree           navigationTree            = new NavigationTree(userContext, new InvisibleRootTreeNode(userContext), navigationNodeCollection2.GroupSection);
                foreach (NavigationNodeGroup navigationNodeGroup2 in navigationNodeCollection2)
                {
                    if (!navigationNodeGroup2.IsNew)
                    {
                        if ((navigationNodeCollection2.GroupSection == NavigationNodeGroupSection.Contacts || navigationNodeCollection2.GroupSection == NavigationNodeGroupSection.Tasks) && NavigationNodeCollection.PeoplesFoldersClassId.Equals(navigationNodeGroup2.NavigationNodeGroupClassId))
                        {
                            bool flag5 = false;
                            foreach (NavigationNodeFolder navigationNodeFolder3 in navigationNodeGroup2.Children)
                            {
                                if (navigationNodeFolder3.NavigationNodeType != NavigationNodeType.SharedFolder)
                                {
                                    flag5 = true;
                                    break;
                                }
                            }
                            if (!flag5)
                            {
                                continue;
                            }
                        }
                        NavigationGroupHeaderTreeNode navigationGroupHeaderTreeNode = new NavigationGroupHeaderTreeNode(userContext, navigationNodeGroup2);
                        foreach (NavigationNodeFolder navigationNodeFolder4 in navigationNodeGroup2.Children)
                        {
                            if (((navigationNodeCollection2.GroupSection != NavigationNodeGroupSection.Contacts && navigationNodeCollection2.GroupSection != NavigationNodeGroupSection.Tasks) || navigationNodeFolder4.NavigationNodeType != NavigationNodeType.SharedFolder) && navigationNodeFolder4.IsValid && (navigationNodeFolder4.IsGSCalendar || navigationNodeFolder4.FolderId != null))
                            {
                                NavigationFolderTreeNode navigationFolderTreeNode = null;
                                foreach (FolderList folderList5 in folderLists)
                                {
                                    object[] array6 = null;
                                    if (navigationNodeFolder4.FolderId != null)
                                    {
                                        array6 = folderList5.GetFolderProperties(navigationNodeFolder4.FolderId);
                                    }
                                    if (array6 != null)
                                    {
                                        navigationFolderTreeNode = new NavigationFolderTreeNode(userContext, navigationNodeFolder4, null, array6, folderList5.QueryPropertyMap);
                                        break;
                                    }
                                }
                                if (navigationFolderTreeNode == null && (!navigationNodeFolder4.IsFolderInSpecificMailboxSession(userContext.MailboxSession) || (navigationNodeFolder4.FolderId != null && Utilities.IsDefaultFolderId(userContext.MailboxSession, navigationNodeFolder4.FolderId, DefaultFolderType.ToDoSearch))))
                                {
                                    navigationFolderTreeNode = new NavigationFolderTreeNode(userContext, navigationNodeFolder4);
                                }
                                if (navigationFolderTreeNode != null)
                                {
                                    navigationGroupHeaderTreeNode.AddChild(navigationFolderTreeNode);
                                }
                            }
                        }
                        navigationTree.RootNode.AddChild(navigationGroupHeaderTreeNode);
                    }
                }
                array5[num4] = navigationTree;
            }
            return(array5);
        }
Esempio n. 31
0
        public void Update(GameTime gameTime)
        {
            if (path == null)
            {
                return;
            }

            if (path.Count > 0)
            {
                if (path.Count > 1)
                {
                    OptimisePath();
                }


                NavigationNode currentNode = path[0];

                //check we can still see our node. Sometimes we can't, after
                //applying an unexpectedly large move.
                if (!CanStillPathToNode(currentNode) && currentNode.WorldPosition != mapHandler.LevelEnd)
                {
                    PathToPoint(path[path.Count - 1].WorldPosition);
                }


                Vector3 toTarget = currentNode.WorldPosition - ParentObject.Transform.AbsoluteTransform.Translation;
                if (toTarget.Length() < minDistanceToNode)
                {
                    path.RemoveAt(0);
                    return;
                }

                toTarget.Y = 0;
                toTarget.Normalize();


                Vector3 rightV = ParentObject.Transform.AbsoluteTransform.Right;
                rightV.Y = 0;
                rightV.Normalize();

                Vector3 forwardVec = ParentObject.Transform.AbsoluteTransform.Forward;
                forwardVec.Y = 0;
                forwardVec.Normalize();

                float dot = Vector3.Dot(toTarget, rightV);

                //game units are roughly 105 in a circle.
                //so 1 unit = 360 / 105 degrees
                //1 degree = 105 / 360
                var   angle      = MathHelper.ToDegrees(MonoMathHelper.GetAngleBetweenVectors(toTarget, forwardVec));
                float spinAmount = angle * (105f / 360);


                float heading = MathHelper.ToDegrees(MonoMathHelper.GetHeadingFromVector((currentNode.WorldPosition - ParentObject.Transform.AbsoluteTransform.Translation).ToVector2XZ()));
                heading = (heading + 360) % 360;
                //DebugText.Write(dot.ToString());
                // DebugText.Write(angle.ToString());
                // DebugText.Write(spinAmount.ToString());
                DebugText.Write("Heading: " + heading.ToString());



                if (dot > 0.1f)
                {
                    if (!turning)
                    {
                        //TurnLeft(2);
                        TurnLeftToHeading(heading);
                    }
                }
                if (dot < -0.1f)
                {
                    if (!turning)
                    {
                        //TurnRight(2);
                        TurnRightToHeading(heading);
                    }
                }

                if (dot > -movementRangeThreshold && dot < movementRangeThreshold)
                {
                    //the node we need is right behind us. Instigate a turn.
                    if (MonoMathHelper.AlmostEquals(180d, angle, 10))
                    {
                        TurnLeft(3);
                        return;
                    }

                    if (!moving)
                    {
                        //we're likely stuck. Try moving back
                        if (movementAttemptsWithNoPositionChange > 50)
                        {
                            MoveBackward(4);
                            movementAttemptsWithNoPositionChange = 0;
                        }
                        else
                        {
                            MoveForward(4);
                        }
                    }
                }


                FeelForward();
            }
            else
            {
                path = null;
            }
        }
Esempio n. 32
0
        public void Rename()
        {
            base.ThrowIfCannotActAsOwner();
            string text = ((string)base.GetParameter("SB")).Trim();
            string s    = text;
            NavigationNodeGroupSection navigationNodeGroupSection = (NavigationNodeGroupSection)base.GetParameter("GS");
            NavigationNodeCollection   navigationNodeCollection   = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, navigationNodeGroupSection);
            NavigationNode             navigationNode             = navigationNodeCollection.FindNavigationNodeByNodeId((StoreObjectId)base.GetParameter("srcNId"));

            if (navigationNode == null)
            {
                throw new OwaEventHandlerException("Cannot find specified navigation node", LocalizedStrings.GetNonEncoded(-289549140), true);
            }
            if (text.Length != 0)
            {
                if (navigationNode is NavigationNodeFolder)
                {
                    NavigationNodeFolder navigationNodeFolder = navigationNode as NavigationNodeFolder;
                    if (!navigationNodeFolder.IsValid)
                    {
                        throw new OwaInvalidRequestException("This is not a valid navigation node");
                    }
                    if (navigationNodeFolder.NavigationNodeType == NavigationNodeType.SmartFolder && !navigationNodeFolder.IsFilteredView)
                    {
                        throw new OwaInvalidRequestException("Cannot rename search folders");
                    }
                    OwaStoreObjectId owaStoreObjectId = OwaStoreObjectId.CreateFromNavigationNodeFolder(base.UserContext, navigationNodeFolder);
                    MailboxSession   mailboxSession   = owaStoreObjectId.IsArchive ? ((MailboxSession)owaStoreObjectId.GetSession(base.UserContext)) : base.UserContext.MailboxSession;
                    if (owaStoreObjectId.IsArchive && navigationNodeFolder.NavigationNodeType == NavigationNodeType.NormalFolder)
                    {
                        s = string.Format(LocalizedStrings.GetNonEncoded(-83764036), text, Utilities.GetMailboxOwnerDisplayName(mailboxSession));
                    }
                    if (navigationNodeFolder.IsFolderInSpecificMailboxSession(mailboxSession))
                    {
                        using (Folder folder = Folder.Bind(mailboxSession, navigationNodeFolder.FolderId, new PropertyDefinition[]
                        {
                            FolderSchema.ExtendedFolderFlags
                        }))
                        {
                            if (!Utilities.CanFolderBeRenamed(base.UserContext, folder))
                            {
                                throw new OwaInvalidRequestException("Folder cannot be renamed.");
                            }
                            folder.DisplayName = text;
                            FolderSaveResult folderSaveResult = folder.Save();
                            if (folderSaveResult.OperationResult != OperationResult.Succeeded)
                            {
                                if (Utilities.IsFolderNameConflictError(folderSaveResult))
                                {
                                    throw new OwaEventHandlerException("Folder rename did not return OperationResult.Succeeded", LocalizedStrings.GetNonEncoded(1602494619), OwaEventHandlerErrorCode.FolderNameExists, true);
                                }
                                throw new OwaAccessDeniedException(LocalizedStrings.GetNonEncoded(995407892));
                            }
                        }
                    }
                }
                navigationNode.Subject = text;
                navigationNodeCollection.Save(base.UserContext.MailboxSession);
                this.Writer.Write("<div id=tn>");
                Utilities.HtmlEncode(text, this.Writer, true);
                this.Writer.Write("</div><div id=ntn>");
                Utilities.HtmlEncode(s, this.Writer, true);
                this.Writer.Write("</div>");
                return;
            }
            if (navigationNode is NavigationNodeGroup)
            {
                throw new OwaEventHandlerException("User did not provide name for new group", LocalizedStrings.GetNonEncoded(-1749891264), true);
            }
            throw new OwaEventHandlerException("User did not provide name for new folder", LocalizedStrings.GetNonEncoded(-41080803), true);
        }
Esempio n. 33
0
        private IEnumerator <float> NavCoroutine()
        {
            Queue <Vector3> FollowTargetPosCache = new Queue <Vector3>();
            int             eta = 0;
            int             dormant_cache_update = 0;

            for (; ;)
            {
                if (FollowTarget != null)
                {
                    if (FollowTarget.IsAlive)
                    {
                        float dist = Vector3.Distance(FollowTarget.Position, NPCPlayer.Position);

                        //If we are far away...
                        if (dist >= Plugin.Instance.Config.MaxFollowDistance)
                        {
                            if (OnTargetLostBehaviour == TargetLostBehaviour.TELEPORT)
                            {
                                //... Teleport to player if allowed
                                NPCPlayer.Position = FollowTarget.Position;
                                eta = 0;
                                FollowTargetPosCache.Clear();
                            }
                            else
                            {
                                //Stop or try to search otherwise

                                FireEvent(new NPCTargetLostEvent(this, FollowTarget));

                                FollowTargetPosCache.Clear();
                                eta = 0;
                                Stop();
                                if (OnTargetLostBehaviour == TargetLostBehaviour.SEARCH)
                                {
                                    Room r = FollowTarget.CurrentRoom;
                                    if (r != null)
                                    {
                                        GotoRoom(r);
                                    }
                                }
                                continue;
                            }
                        }

                        //If target is not near
                        if (dist >= 1.5f)
                        {
                            //Update Pos cache each third tick
                            if (dormant_cache_update > 2)
                            {
                                FollowTargetPosCache.Enqueue(FollowTarget.Position);
                                dormant_cache_update = 0;
                            }
                            dormant_cache_update++;
                        }
                        else
                        {
                            //Otherwise just dont move
                            FollowTargetPosCache.Clear();
                            eta = 0;
                            Timing.KillCoroutines(MovementCoroutines.ToArray());
                            Move(MovementDirection.NONE);
                        }
                    }
                    else
                    {
                        // Target dead, reset
                        FollowTargetPosCache.Clear();
                        eta = 0;
                        FireEvent(new NPCFollowTargetDiedEvent(this, FollowTarget));
                        Stop();
                        continue;
                    }

                    //If we reached predicted target
                    if (eta <= 0)
                    {
                        //Schedule next position
                        if (!FollowTargetPosCache.IsEmpty())
                        {
                            float full_eta = GoTo(FollowTargetPosCache.Dequeue());
                            eta = (int)(full_eta / Plugin.Instance.Config.NavUpdateFrequency) - 1;
                        }
                    }
                    else
                    {
                        eta--;
                    }
                }
                else
                {
                    //Noone to follow, try taking nodes from nav queue

                    eta = 0;
                    FollowTargetPosCache.Clear();

                    if (CurrentNavTarget != null)
                    {
                        IsRunning = !DisableRun;
                        //There is current
                        float distance = Vector3.Distance(CurrentNavTarget.Position, NPCPlayer.Position);

                        if (distance < 3f && (!ProcessSCPLogic || NPCPlayer.Role != RoleType.Scp106))
                        {
                            //Try to open the door if there is one, so we wont collide with it
                            if (CurrentNavTarget.AttachedDoor != null && !CurrentNavTarget.AttachedDoor.NetworkisOpen)
                            {
                                ItemType prev = ItemHeld;
                                bool     open = NPCPlayer.IsBypassModeEnabled || (CurrentNavTarget.AttachedDoor.CheckpointDoor && NPCPlayer.ReferenceHub.characterClassManager.IsAnyScp());
                                if (!open)
                                {
                                    if (!CurrentNavTarget.AttachedDoor.CanBeOpenedWith(ItemHeld))
                                    {
                                        foreach (ItemType keycard in AvailableKeycards)
                                        {
                                            if (CurrentNavTarget.AttachedDoor.CanBeOpenedWith(keycard))
                                            {
                                                ItemHeld = keycard;
                                                open     = true;
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        open = true;
                                    }
                                }
                                if (open)
                                {
                                    //All is good
                                    Timing.KillCoroutines(MovementCoroutines.ToArray());
                                    Move(MovementDirection.NONE);
                                    while (CurrentNavTarget.AttachedDoor.locked)
                                    {
                                        yield return(0f);
                                    }
                                    yield return(Timing.WaitForSeconds(0.2f));

                                    CurrentNavTarget.AttachedDoor.NetworkisOpen = true;
                                    yield return(Timing.WaitForSeconds(0.1f));

                                    GoTo(CurrentNavTarget.Position);
                                    ItemHeld = prev;
                                }
                                else
                                {
                                    //Stop otherwise
                                    Stop();
                                    continue;
                                }
                            }
                        }

                        if (distance < 6)
                        {
                            NavigationNode NextNavTarget = NavigationQueue.First?.Value;

                            NavigationNode lift_node = null;
                            if (NextNavTarget != null)
                            {
                                if (NextNavTarget.AttachedElevator != null)
                                {
                                    lift_node = NextNavTarget;
                                }
                            }
                            //If there is an elevator, try to use it
                            if (CurrentNavTarget.AttachedElevator == null && lift_node != null)
                            {
                                bool val = lift_node.AttachedElevator.Value.Value.IsClosed(lift_node.AttachedElevator.Value.Key);
                                if (val)
                                {
                                    lift_node.AttachedElevator.Value.Value.UseLift();

                                    Timing.KillCoroutines(MovementCoroutines.ToArray());
                                    Move(MovementDirection.NONE);

                                    while (!lift_node.AttachedElevator.Value.Value.operative)
                                    {
                                        yield return(0.0f);
                                    }

                                    GoTo(CurrentNavTarget.Position);
                                }
                            }
                        }

                        if (CurMovementDirection == MovementDirection.NONE)
                        {
                            //Target reached - force position to it so we wont stuck
                            Vector3 forced = new Vector3(CurrentNavTarget.Position.x, NPCPlayer.Position.y, CurrentNavTarget.Position.z);
                            NPCPlayer.ReferenceHub.playerMovementSync.OverridePosition(forced, 0f, true);

                            //If we have AI item target reached, try to find and take item
                            if (CurrentAIItemNodeTarget != null && CurrentAIItemNodeTarget == CurrentNavTarget)
                            {
                                CurrentAIItemNodeTarget = null;
                                IEnumerable <Pickup> pickups = FindObjectsOfType <Pickup>().Where(pk => Vector3.Distance(pk.Networkposition, NPCPlayer.Position) <= 5f);
                                foreach (Pickup p in pickups)
                                {
                                    if (Utils.Utils.CheckItemType(CurrentAIItemGroupTarget, p.ItemId))
                                    {
                                        yield return(Timing.WaitForSeconds(GoTo(p.position)));

                                        TakeItem(p);
                                        break;
                                    }
                                }
                                CurrentAIItemGroupTarget = null;
                            }
                            CurrentNavTarget = null;
                        }
                    }
                    else if (NavigationQueue.Count > 0)
                    {
                        //No current, but there are pending targets
                        CurrentNavTarget = NavigationQueue.First.Value;
                        NavigationQueue.RemoveFirst();
                        if (CurrentNavTarget.AttachedElevator != null && Math.Abs(CurrentNavTarget.AttachedElevator.Value.Key.target.position.y - NPCPlayer.Position.y) > 2f)
                        {
                            CurrentNavTarget.AttachedElevator.Value.Value.UseLift();
                            while (CurrentNavTarget.AttachedElevator.Value.Value.status == Lift.Status.Moving)
                            {
                                yield return(0f);
                            }

                            CurrentNavTarget = null;
                        }
                        else
                        {
                            GoTo(CurrentNavTarget.Position);
                        }
                    }
                    else if (CurrentAIRoomTarget != null)
                    {
                        //No current, no pending - room reached
                        CurrentAIRoomTarget = null;
                    }
                }
                yield return(Timing.WaitForSeconds(Plugin.Instance.Config.NavUpdateFrequency));
            }
        }
Esempio n. 34
0
        private string GetParentNode(NavigationNode node, bool isOpened)
        {
            var output = RenderNodeAsHtml(node);

            return(string.Format(UlItemTemplate, output, isOpened ? "" : "display: none;"));
        }
Esempio n. 35
0
 public void AddNavTarget(NavigationNode node)
 {
     NavigationQueue.AddLast(node);
 }
        private async Task <TreeNode <NavigationNode> > BuildTreeInternal(NavigationTreeBuilderService service)
        {
            NavigationNode rootNav;

            var project = await projectService.GetCurrentProjectSettings();

            IPage homePage = null;

            if (
                project != null &&
                project.UseDefaultPageAsRootNode &&
                !string.IsNullOrEmpty(project.DefaultPageSlug)
                )
            {
                //make the home page the "root" which contains all the other pages
                homePage = await pageService.GetPageBySlug(project.DefaultPageSlug);
            }

            var rootList = await pageService.GetRootPages().ConfigureAwait(false);

            var rootListCount = rootList.Count();

            var urlHelper    = urlHelperFactory.GetUrlHelper(actionContextAccesor.ActionContext);
            var folderPrefix = prefixProvider.GetPrefix();

            if ((homePage != null) && project.UseDefaultPageAsRootNode)
            {
                rootNav = new NavigationNode();
                //rootNav.IsRootNode = true;
                rootNav.Key  = homePage.Id;
                rootNav.Text = homePage.Title;
                rootNav.Url  = pageRouteHelper.ResolveHomeUrl(urlHelper, folderPrefix); // urlHelper.Content("~/" + folderPrefix);
            }
            else
            {
                rootNav = new NavigationNode();
                //rootNav.IsRootNode = true;
                rootNav.Key   = "pagesRoot";
                rootNav.Title = "Home";
                rootNav.Text  = "Home";
                if (string.IsNullOrEmpty(folderPrefix))
                {
                    rootNav.Url = urlHelper.RouteUrl(pageRouteHelper.PageIndexRouteName);
                }
                else
                {
                    rootNav.Url = urlHelper.Content("~/" + folderPrefix);
                }
            }



            var treeRoot = new TreeNode <NavigationNode>(rootNav);


            var blogPosition = project.BlogPagePosition;

            if (project.AddBlogToPagesTree)
            {
                if (blogPosition > rootListCount)
                {
                    blogPosition = rootListCount;
                }
            }

            var didAddBlog = false;

            if (rootListCount <= 1)
            {   // if there are no pages we won't hit the loop below so go ahead and add the blog page
                if (project.AddBlogToPagesTree)
                {
                    var node = new NavigationNode();
                    node.Key = project.BlogPageText;
                    //node.ParentKey = "RootNode";
                    node.Text = project.BlogPageText;
                    if (project.BlogMenuLinksToNewestPost)
                    {
                        node.NamedRoute = blogRoutes.MostRecentPostRouteName;
                        node.Url        = urlHelper.RouteUrl(blogRoutes.MostRecentPostRouteName);
                    }
                    else
                    {
                        node.NamedRoute = blogRoutes.BlogIndexRouteName;
                        node.Url        = urlHelper.RouteUrl(blogRoutes.BlogIndexRouteName);
                    }

                    node.ComponentVisibility = project.BlogPageNavComponentVisibility;
                    var blogNode = treeRoot.AddChild(node);
                    didAddBlog = true;
                }
            }

            var rootPosition = 1;

            foreach (var page in rootList)
            {
                var node = new NavigationNode();
                if (!didAddBlog && (project.AddBlogToPagesTree && rootPosition == blogPosition))
                {
                    node.Key = project.BlogPageText;
                    //node.ParentKey = "RootNode";
                    node.Text = project.BlogPageText;
                    if (project.BlogMenuLinksToNewestPost)
                    {
                        node.NamedRoute = blogRoutes.MostRecentPostRouteName;
                        node.Url        = urlHelper.RouteUrl(blogRoutes.MostRecentPostRouteName);
                    }
                    else
                    {
                        node.NamedRoute = blogRoutes.BlogIndexRouteName;
                        node.Url        = urlHelper.RouteUrl(blogRoutes.BlogIndexRouteName);
                    }
                    node.ComponentVisibility = project.BlogPageNavComponentVisibility;
                    var blogNode = treeRoot.AddChild(node);

                    node = new NavigationNode(); // new it up again for use below
                }

                if (project.UseDefaultPageAsRootNode && (homePage != null && homePage.Id == page.Id))
                {
                    rootPosition += 1;
                    await AddChildNodes(treeRoot, project, folderPrefix).ConfigureAwait(false);

                    continue;
                }

                node.Key = page.Id;
                //node.ParentKey = page.ParentId;
                node.Text                = page.Title;
                node.ViewRoles           = page.ViewRoles;
                node.ComponentVisibility = page.MenuFilters;
                SetUrl(node, page, folderPrefix, urlHelper);

                // for unpublished pages PagesNavigationNodePermissionResolver
                // will look for projectid in CustomData and if it exists
                // filter node from view unless user has edit permissions
                if (!page.IsPublished || page.PubDate > DateTime.UtcNow)
                {
                    node.CustomData = project.Id;
                }

                var treeNode = treeRoot.AddChild(node);
                await AddChildNodes(treeNode, project, folderPrefix).ConfigureAwait(false);

                rootPosition += 1;
            }

            return(treeRoot);
        }
Esempio n. 37
0
 private static void removeEntityToNavigationNode(ref EntitiesIndexedByNavigationNodes p_entitiesIndexedByNavigationNodes, Entity p_entity, NavigationNode p_navigationNode)
 {
     if (p_entitiesIndexedByNavigationNodes.Entities.ContainsKey(p_navigationNode))
     {
         p_entitiesIndexedByNavigationNodes.Entities[p_navigationNode].Remove(p_entity);
     }
 }
        /// <summary>
        /// Build the Site Map Nodes before serialization
        /// </summary>
        /// <param name="nodes">Collection of nodes</param>
        /// <param name="entities">Collection of pages</param>
        /// <param name="matchFunc">The matching function.</param>
        /// <param name="mapperAction">The node mapping action.</param>
        /// <returns>
        /// Navigation Nodes
        /// </returns>
        private IEnumerable<NavigationNode> BuildSiteMapNodes(
            IList<NavigationNode> nodes, 
            IList<INavigationEntity> entities, 
            Func<INavigationEntity, NavigationNode, bool> matchFunc,
            Action<INavigationEntity, NavigationNode> mapperAction)
        {
            var currentUrl = SPContext.Current.ListItemServerRelativeUrl;

            // For each node, find linked list element
            for (var i = 0; i < nodes.Count; i++)
            {
                var node = nodes[i];

                // Map entities to nodes
                var linkedEntities = entities.Where(entity => matchFunc(entity, node)).ToList();
                for (var j = 0; j < linkedEntities.Count; j++)
                {
                    // For the first match, set the current node's parameters
                    // For subsequent matches, insert duplicate nodes.
                    var linkedEntity = linkedEntities.ElementAt(j);
                    if (j == 0)
                    {
                        mapperAction(linkedEntity, node);
                    }
                    else
                    {
                        var duplicateNode = new NavigationNode { IsDuplicate = true };
                        mapperAction(linkedEntity, duplicateNode);
                        nodes.Insert(i + j, duplicateNode);
                    }
                }

                // If child nodes, recurse call and build nodes
                if (node.ChildNodes != null)
                {
                    // ReSharper disable once PossibleMultipleEnumeration
                    var childNodes = node.ChildNodes.ToList();
                    if (childNodes.Any())
                    {
                        node.ChildNodes = this.BuildSiteMapNodes(childNodes, entities, matchFunc, mapperAction);
                    }
                }
            }

            // If top most level of nodes (no parent node set)
            // Set the current branch property on the nodes
            if (nodes.All(node => node.ParentNodeId.Equals(default(Guid))))
            {
                this.SetCurrentBranchNodes(nodes);
            }

            return nodes;
        }
Esempio n. 39
0
 /// <summary>
 /// Tick the <see cref="NavigationEngine"/> :
 ///     - Updates the position of the <paramref name="p_entity"/> on the <see cref="NavigationNode"/> indexed containers.
 ///     (see <see cref="EntitiesIndexedByNavigationNodes.onNavigationNodeChange(ref EntitiesIndexedByNavigationNodes, Entity, NavigationNode, NavigationNode)"/>).
 ///     - If the <paramref name="p_entity"/> is defined as an obstacle <see cref="_Navigation._Modifier.NavigationModifier"/>, then obstacles representation
 ///     of the <see cref="NavigationGraph"/> is updated (see <see cref="ObstacleStep.resolveNavigationObstacleAlterations(NavigationEngine, Entity, NavigationNode, NavigationNode)"/>).
 ///     - Calls the trigger events if elligible (see <see cref="TriggerResolutionStep.resolveTrigger(NavigationEngine, Entity, NavigationNode, NavigationNode)"/>).
 /// </summary>
 /// <param name="p_oldNavigationNode"> Thr old <see cref="NavigationNode"/> can be null. Meaning that the <paramref name="p_entity"/> wasn't positioned inside the <see cref="NavigationGraph"/> before. </param>
 /// <param name="p_newNavigationNode"> The target <see cref="NavigationNode"/> can be null. Meaning that the <paramref name="p_entity"/> have been destroyed. </param>
 public static List <AEvent> resolveEntityNavigationNodeChange(NavigationEngine p_navigationEngine,
                                                               Entity p_entity, NavigationNode p_oldNavigationNode, NavigationNode p_newNavigationNode)
 {
     p_navigationEngine.CachedProducedEventsStackByTriggers.Clear();
     EntitiesIndexedByNavigationNodes.onNavigationNodeChange(ref p_navigationEngine.EntitiesIndexedByNavigationNodes, p_entity, p_oldNavigationNode, p_newNavigationNode);
     ObstacleStep.resolveNavigationObstacleAlterations(p_navigationEngine, p_entity, p_oldNavigationNode, p_newNavigationNode);
     TriggerResolutionStep.resolveTrigger(p_navigationEngine, p_entity, p_oldNavigationNode, p_newNavigationNode);
     return(p_navigationEngine.CachedProducedEventsStackByTriggers);
 }