Esempio n. 1
0
        public bool HandlePathing(ref WorldPathingRequest request, Func <bool> breakFunc = null, Action onDone = null, bool ignoreMount = false)
        {
            if (request != null)
            {
                if (!ignoreMount && !HandleMounting(Vector3.zero))
                {
                    return(true);
                }

                if ((breakFunc?.Invoke()).GetValueOrDefault())
                {
                    request = null;
                }
                else if (request.IsRunning)
                {
                    request.Continue();
                }
                else
                {
                    request = null;
                    onDone?.Invoke();
                }

                return(true);
            }

            return(false);
        }
Esempio n. 2
0
        public void Travel()
        {
            if (!HandleMounting(Vector3.zero))
            {
                return;
            }

            if (HandlePathing(ref _travelPathingRequest))
            {
                return;
            }

            Albion_Direct.Worldmap worldmapInstance = GameGui.Instance.WorldMap;

            var currentCluster = _world.GetCurrentCluster();

            if (currentCluster.GetName() == _targetCluster.GetName())
            {
                Core.Log("[Traveling Done]");
                _state.Fire(Trigger.TravellingDone);
                return;
            }
            else
            {
                var worldPathing = new WorldmapPathfinder();
                if (worldPathing.TryFindPath(currentCluster, _targetCluster, StopClusterFunction, out var path, out var pivots))
                {
                    Core.Log("[Traveling Path found]");
                    _travelPathingRequest = new WorldPathingRequest(currentCluster, _targetCluster, path, _skipUnrestrictedPvPZones);
                }
Esempio n. 3
0
        public bool HandlePathing(ref WorldPathingRequest request, Func <bool> breakFunc = null, Action onDone = null, bool ignoreMount = false)
        {
            if (request != null)
            {
                if (!ignoreMount && !HandleMounting(Vector3.zero))
                {
                    //iCore.Log("Handle mounting via handlepathing worldpathing request");
                    return(true);
                }
                if ((breakFunc?.Invoke()).GetValueOrDefault())
                {
                    request = null;
                }
                else if (request.IsRunning)
                {
                    //Core.Log("Continue via handlepathing worldpathing request");
                    request.Continue();
                }
                else
                {
                    request = null;
                    onDone?.Invoke();
                    //Core.Log("Other via handlepathing worldpathing request");
                }
                //Core.Log("Defaulting to true handlepathing worldpathing request");
                return(true);
            }

            return(false);
        }
Esempio n. 4
0
        public void Bank()
        {
            _client = GameManager.GetInstance();
            if (_client.GetState() != GameState.Playing)
            {
                Core.Log("Client state not equal to Playing so we will wait");
                return;
            }

            var player = _localPlayerCharacterView.GetLocalPlayerCharacter();

            if (!HandleMounting(Vector3.zero))
            {
                Core.Log("Handle mounting");
                return;
            }

            if (!_isDepositing && _localPlayerCharacterView.GetLoadPercent() <= _percentageForBanking)
            {
                Core.Log("[Restart]");
                _state.Fire(Trigger.Restart);
                return;
            }

            if (HandlePathing(ref _worldPathingRequest))
            {
                return;
            }

            if (HandlePathing(ref _bankFindPathingRequest, () => _client.GetEntities <BankBuildingView>((x) => { return(true); }).Count > 0))
            {
                return;
            }

            if (HandlePathing(ref _bankPathingRequest, null))
            {
                return;
            }

            Worldmap worldmapInstance = GameGui.Instance.WorldMap;

            Vector3           playerCenter        = _localPlayerCharacterView.transform.position;
            ClusterDescriptor currentWorldCluster = _world.GetCurrentCluster();
            ClusterDescriptor townCluster         = worldmapInstance.GetCluster(TownClusterNames[_selectedTownClusterIndex]).Info;

            if (currentWorldCluster.GetName() == townCluster.GetName())
            {
                Core.Log("Arrived at town");

                if (_nextBankAction == new DateTime())
                {
                    Core.Log("Adding 3 seconds to banking wait time to avoid load issues.");
                    _nextBankAction = DateTime.UtcNow.AddSeconds(3);
                }

                if (waiting(_nextBankAction))
                {
                    return;
                }

                if (!moveToTownBank(currentWorldCluster))
                {
                    Core.Log("moving to Town Bank location");
                    return;
                }
                else
                {
                    Core.Log("Begin Banking.");

                    if (moveObjectsToBank())
                    {
                        return;
                    }
                    else
                    {
                        _nextBankAction = new DateTime();
                        _movingToBank   = false;
                        Core.Log("[Bank Done]");
                        _state.Fire(Trigger.BankDone);
                    }
                }
            }
            else
            {
                Core.Log("Not in town. Try to find path to town.");
                var pathfinder = new WorldmapPathfinder();
                if (pathfinder.TryFindPath(currentWorldCluster, townCluster, StopClusterFunction, out var path, out var pivots))
                {
                    Core.Log("Path Found to Town.");
                    _worldPathingRequest = new WorldPathingRequest(currentWorldCluster, townCluster, path, _skipUnrestrictedPvPZones);
                }
            }
        }
Esempio n. 5
0
        public void Bank()
        {
            if (!_localPlayerCharacterView.IsMounted)
            {
                if (_localPlayerCharacterView.IsMounting())
                {
                    return;
                }

                _localPlayerCharacterView.MountOrDismount();
                return;
            }

            if (_localPlayerCharacterView.GetLoadPercent() <= CapacityForBanking)
            {
                _localPlayerCharacterView.CreateTextEffect("[Restart]");
                _state.Fire(Trigger.Restart);
                return;
            }

            if (_worldPathingRequest != null)
            {
                if (_worldPathingRequest.IsRunning)
                {
                    if (!HandleMounting(Vector3.zero))
                    {
                        return;
                    }

                    _worldPathingRequest.Continue();
                }
                else
                {
                    _worldPathingRequest = null;
                }
                return;
            }


            if (_bankPathingRequest != null)
            {
                if (_bankPathingRequest.IsRunning)
                {
                    if (!HandleMounting(Vector3.zero))
                    {
                        return;
                    }

                    _bankPathingRequest.Continue();
                }
                else
                {
                    _bankPathingRequest = null;
                }

                return;
            }

            Vector3 playerCenter = _localPlayerCharacterView.transform.position;

            var currentWorldCluster = _world.CurrentCluster;
            var _townCluster        = _world.GetCluster(SelectedTownCluster);

            var currentCluster = new Cluster(currentWorldCluster.Info);
            var townCluster    = new Cluster(_townCluster.Info);

            Core.Log(string.Format(
                         $"CurrentCluster: {currentCluster.InternalName} {currentCluster.InternalName} {currentCluster.InternalName}"));
            Core.Log(string.Format(
                         $"CurrentCluster: {townCluster.InternalName} {townCluster.InternalName} {townCluster.InternalName}"));



            if (currentCluster.Name == townCluster.Name)
            {
                var banks = _client.GetEntities <BankBuildingView>((x) => { return(true); });

                if (banks.Count == 0)
                {
                    return;
                }

                _currentTarget = banks.First();

                /* Begin moving closer the target. */
                var targetCenter = _currentTarget.transform.position;
                playerCenter = _localPlayerCharacterView.transform.position;

                var centerDistance  = (targetCenter - playerCenter).magnitude;
                var minimumDistance = _currentTarget.GetColliderExtents() +
                                      _localPlayerCharacterView.GetColliderExtents() + 1.5f;

                if (centerDistance >= minimumDistance)
                {
                    if (!HandleMounting(targetCenter))
                    {
                        return;
                    }

                    if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), targetCenter, (v) => false,
                                                              out List <Vector3> pathing))
                    {
                        _bankPathingRequest =
                            new ClusterPathingRequest(_localPlayerCharacterView, _currentTarget, pathing);
                    }

                    return;
                }
                //Fixes position, if is slightly invalid and opens UI

                if (_currentTarget is BankBuildingView resource)
                {
                    _localPlayerCharacterView.Interact(resource);
                    //Get inventory
                    var playerStorage = GameGui.Instance.CharacterInfoGui.InventoryItemStorage;
                    var vaultStorage  = GameGui.Instance.BankBuildingVaultGui.BankVault.InventoryStorage;

                    var ToDeposit = new List <UIItemSlot>();

                    //Get all items we need
                    foreach (var slot in playerStorage.ItemsSlotsRegistered)
                    {
                        if (slot != null && slot.ObservedItemView != null)
                        {
                            var name = slot.ObservedItemView.name;
                            //TODO: Move this as part of new filter to Config
                            if (!name.Contains("JOURNAL") && (name.Contains("_ROCK") || name.Contains("_ORE") ||
                                                              name.Contains("_HIDE") || name.Contains("_WOOD") ||
                                                              name.Contains("_FIBER")))
                            {
                                ToDeposit.Add(slot);
                            }
                        }
                    }

                    foreach (var item in ToDeposit)
                    {
                        GameGui.Instance.MoveItemToItemContainer(item, vaultStorage.ItemContainerProxy);
                    }
                }
            }
            else
            {
                var path        = new List <WorldmapCluster>();
                var pivotPoints = new List <WorldmapCluster>();

                var worldPathing = new WorldmapPathfinder();

                if (worldPathing.TryFindPath(currentWorldCluster, _townCluster, (cluster) => false, out path, out pivotPoints, true, false))
                {
                    _worldPathingRequest = new WorldPathingRequest(currentWorldCluster, _townCluster, path);
                }
            }
            //_state.Fire(Trigger.Restart);
            //_localPlayerCharacterView.RequestMove(playerCenter);


            // TODO: If not in town, get request to exit towards town.

            // TODO: Get current cluster, is it town?

            // TODO: Move to bank

            // TODO: Near the bank, bank is open?

            // TODO: Bank is open, move items
        }
Esempio n. 6
0
        public void Bank()
        {
            if (!_localPlayerCharacterView.IsMounted)
            {
                if (_localPlayerCharacterView.IsMounting())
                {
                    return;
                }

                _localPlayerCharacterView.MountOrDismount();
                return;
            }

            if (_localPlayerCharacterView.GetLoadPercent() <= CapacityForBanking)
            {
                _localPlayerCharacterView.CreateTextEffect("[Restart]");
                _state.Fire(Trigger.Restart);
                return;
            }

            if (_worldPathingRequest != null)
            {
                if (_worldPathingRequest.IsRunning)
                {
                    if (!HandleMounting(Vector3.zero))
                    {
                        return;
                    }

                    _worldPathingRequest.Continue();
                }
                else
                {
                    _worldPathingRequest = null;
                }

                return;
            }

            var currentCluster = _world.CurrentCluster;
            var townCluster    = _world.GetCluster("Fort Sterling");

            var path        = new List <WorldmapCluster>();
            var pivotPoints = new List <WorldmapCluster>();

            var worldPathing = new WorldmapPathfinder();

            if (worldPathing.TryFindPath(currentCluster, townCluster, (cluster) => false, out path, out pivotPoints, true, false))
            {
                _worldPathingRequest = new WorldPathingRequest(currentCluster, townCluster, path);
            }


            // TODO: If not in town, get request to exit towards town.

            // TODO: Get current cluster, is it town?

            // TODO: Move to bank

            // TODO: Near the bank, bank is open?

            // TODO: Bank is open, move items
        }
Esempio n. 7
0
        // List<Tuple<string, int>> toCraftList;
        public void Collect()
        {
            // Core.Log("Here1 ");
            //_state.Fire(Trigger.GotItems);

            var player = _localPlayerCharacterView.GetLocalPlayerCharacter();

            if (!HandleMounting(Vector3.zero))
            {
                return;
            }

            //Core.Log("Here2");
            if (HandlePathing(ref _collectItemsWorldPathingRequest))
            {
                return;
            }
            // Core.Log("Here3");
            if (HandlePathing(ref _collectItemsBankPathingRequest))
            {
                return;
            }
            //Core.Log("Here4");
            API.Direct.Worldmap worldmapInstance = GameGui.Instance.WorldMap;

            Vector3           playerCenter        = _localPlayerCharacterView.transform.position;
            ClusterDescriptor currentWorldCluster = _world.GetCurrentCluster();
            ClusterDescriptor townCluster         = worldmapInstance.GetCluster(TownClusterNames[_selectedCraftTownClusterIndex]).Info;
            ClusterDescriptor bankCluster         = townCluster.GetExits().Find(e => e.GetDestination().GetName().Contains("Bank")).GetDestination();

            if (currentWorldCluster.GetName() == bankCluster.GetName())
            {
                //Core.Log("Collecting Items");
                var banks = _client.GetEntities <BankBuildingView>((x) => { return(true); });

                if (banks.Count == 0)
                {
                    return;
                }



                //  Core.Log("Moving To bank");

                _currentTarget = banks.First();
                if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), _currentTarget, IsBlockedWithExitCheck, out List <Vector3> pathing))
                {
                    Core.Log("Moving To bank");
                    _collectItemsBankPathingRequest = new ClusterPathingRequest(_localPlayerCharacterView, _currentTarget, pathing);
                    return;
                }



                if (_currentTarget is BankBuildingView resource)
                {
                    if (!GameGui.Instance.BankBuildingVaultGui.gameObject.activeInHierarchy)
                    {
                        _localPlayerCharacterView.Interact(resource);
                        return;
                    }

                    var playerStorage = GameGui.Instance.CharacterInfoGui.InventoryItemStorage;
                    var playerListBox = GameGui.Instance.CharacterInfoGui.InventoryListBox;
                    var vaultStorage  = GameGui.Instance.BankBuildingVaultGui.BankVault.InventoryStorage;
                    var vaultListBox  = GameGui.Instance.BankBuildingVaultGui.BankVault.VaultListBox;
                    var ToDeposit     = new List <UIItemSlot>();


                    //Get all items we need
                    if (!this.scanTest)
                    {
                        Core.Log("MOVING INTEMS FROM STORAGE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                        string     resourceTypes = "equipmentitem";
                        List <int> dontMoveSlots = new List <int> {
                            0, 1, 2, 3, 4
                        };
                        foreach (var slot in playerStorage.ItemsSlotsRegistered)
                        {
                            if (slot != null && slot.ObservedItemView != null)
                            {
                                var slotItemName = slot.ObservedItemView.name.ToLowerInvariant();
                                // Core.Log(slotItemName);
                                var slotObject = slot.gameObject;
                                var slotPos    = playerListBox.GetIndexOfVisibleItemObject(slotObject);
                                Core.Log($"Current Slot Pos {slotPos}");
                                // if (resourceTypes.Any(r => !slotItemName.Contains(r)))
                                if (dontMoveSlots.Contains(slotPos))
                                {
                                    if (slot.GetItemStackSize() > 1)
                                    {
                                        GameGui.Instance.ItemDetailsGui.ItemDetailsWindow.CloseImmediately();
                                        if (!GameGui.Instance.ItemDetailsGui.ItemDetailsView.gameObject.activeInHierarchy)
                                        {
                                            GameGui.Instance.ItemDetailsGui.Show(slot, new Vector3(1, 1, 1));
                                        }
                                        var detailsGui = GameGui.Instance.ItemDetailsGui;

                                        detailsGui.ItemDetailsView.SplitSlider.enabled = true;
                                        detailsGui.ItemDetailsView.SplitButton.enabled = true;

                                        Core.Log($"Itemdetails Gui is for {detailsGui.ItemDetailsWindow.ItemName.text}");

                                        if (detailsGui.ItemDetailsView.SplitButton.isActiveAndEnabled)
                                        {
                                            var slider = GameGui.Instance.ItemDetailsGui.ItemDetailsView.SplitSlider;
                                            detailsGui.ItemDetailsView.SplitSlider.value = 1;
                                            detailsGui.ItemDetailsView.OnClickSplit();
                                            GameGui.Instance.ItemDetailsGui.Close();
                                        }
                                    }
                                }
                                else
                                {
                                    //Core.Log($"Moving {slotPos}");
                                    ToDeposit.Add(slot);
                                }
                            }
                        }
                        _isDepositing = ToDeposit != null && ToDeposit.Count > 0;
                        foreach (var item in ToDeposit)
                        {
                            GameGui.Instance.MoveItemToItemContainer(item, vaultStorage.ItemContainerProxy);
                        }

                        if (_isDepositing)
                        {
                            return;
                        }
                        else
                        {
                            //Core.Log("Transfer To Storage Done");
                            // _state.Fire(Trigger.BankDone);
                        }
                    }


                    if (stackTimer == DateTime.MinValue)
                    {
                        stackTimer = DateTime.Now + TimeSpan.FromSeconds(3);
                    }

                    if (stackTimer > DateTime.Now)
                    {
                        GameGui.Instance.BankBuildingVaultGui.BankVault.InventoryUtil.Stack();
                        GameGui.Instance.BankBuildingVaultGui.BankVault.InventoryUtil.Sort();
                        Core.Log("Stacking");
                    }
                    else
                    {
                        //Core.Log("Stacked");
                        sortStack = true;
                    }


                    if (initialScan == null || initialScan.Count == 0)
                    {
                        Core.Log("MAKING NEW LIST FOR SCANNING");
                        initialScan = new List <Resource>();
                    }


                    if (this.scanTest && sortStack)
                    {
                        //Core.Log("ScanComplete");
                        //Core.Log("stopping Coroutine");
                        StopCoroutine(ScanCoroutine);
                    }
                    else if (sortStack)
                    {
                        ScanCoroutine = scanCheck();
                        StartCoroutine(ScanCoroutine);
                        IEnumerator scanCheck()
                        {
                            for (int ji = 0; ji < 3; ji++)
                            {
                                int oldCount = this.initialScan.Count;
                                this.initialScan = bankstorageScanner(this.initialScan);
                                int newCount = this.initialScan.Count;
                                Core.Log($" At coroutine iteration {ji}");
                                if (ji == 2)
                                {
                                    Core.Log($"Old Count {oldCount} New Count {newCount}");

                                    this.scanTest = (oldCount == newCount);
                                }
                                yield return(null);
                            }
                        }

                        return;
                    }
                    else
                    {
                        Core.Log("Not Sorted");
                        return;
                    }

                    if (resourceCollectList == null)
                    {
                        resourceCollectList = new List <Resource>();
                    }


                    Tuple <bool, List <Resource> > ResourceCount(List <Resource> RL, List <Resource> IS, string RecipeName)
                    {
                        bool canCraft = true;

                        for (int i = 0; i < RL.Count; i++)
                        {
                            string resname = RL[i].Name;

                            foreach (Resource R in IS)
                            {
                                if (R.Name.Contains(resname) && !R.Name.Contains("level"))
                                {
                                    RL[i].TotalAmount = RL[i].TotalAmount + R.StackSize;
                                }
                            }
                            Core.Log($"The Count of {RL[i].Name} is {RL[i].TotalAmount}. The base amount for {RecipeName} is {RL[i].BaseAmountForSelectedRecipe} ");
                            if (RL[i].TotalAmount == 0 || RL[i].TotalAmount < RL[i].BaseAmountForSelectedRecipe)
                            {
                                Core.Log($"Not Enough / Missing { RL[i].Name}");
                                canCraft = false;
                            }
                            else
                            {
                                Core.Log($"There is enough {RL[i].Name}. There is {RL[i].TotalAmount}");
                                RL[i].Available = true;
                            }
                        }
                        Core.Log("Resource Count Complete");
                        return(new Tuple <bool, List <Resource> >(canCraft, RL));
                    }

                    // Core.Log("here1");
                    List <Recipe> currentRecipes = getCurrentRecipes();
                    // Core.Log("here2");

                    // Core.Log("here3");



                    if (this.craftRec == null || !this.craftRec.ResourceListUpdated)
                    {
                        //List<Resource> resList = craftRec.Resources;

                        // Core.Log("here4");



                        foreach (Tuple <string, int> T in toCraftList)
                        {
                            Core.Log(T.Item1 + "\t");
                        }


                        for (int i = 0; i < toCraftList.Count; i++)
                        {
                            Core.Log("Getting resource list from recipe names");
                            Tuple <string, int> TCL = toCraftList[i];
                            this.craftRec = currentRecipes.First(R => R.RecipeName.Contains(toCraftList[i].Item1));
                            var result = ResourceCount(craftRec.Resources, initialScan, this.craftRec.RecipeName);

                            this.craftRec.AmountToCraft = TCL.Item2;

                            bool resourceAvailables = result.Item1;
                            this.craftRec.Resources = result.Item2;
                            Core.Log($"Can craft recipe {craftRec.RecipeName}?: {resourceAvailables}");
                            if (!resourceAvailables)
                            {
                                //Core.Log($"Not Enough ingredients to craft {craftRec.RecipeName}");

                                foreach (Resource CR in craftRec.Resources)
                                {
                                    if (!CR.Available)
                                    {
                                        if (currentRecipes.Any(R => R.RecipeName.Contains(CR.Name)))
                                        {
                                            var recipe = currentRecipes.First(R => R.RecipeName.Contains(CR.Name));
                                            if (!toCraftList.Any(R => R.Item1 == recipe.RecipeName))
                                            {
                                                Core.Log($"Adding {recipe.RecipeName} to craft list. Need {CR.BaseAmountForSelectedRecipe * craftRec.AmountToCraft}");

                                                toCraftList.Add(new Tuple <string, int>(recipe.RecipeName, CR.BaseAmountForSelectedRecipe * craftRec.AmountToCraft));
                                            }
                                            else
                                            {
                                                Core.Log($"Recipe for {recipe.RecipeName} is already in the craft list");
                                            }

                                            // toCraft.Add(recipe.RecipeName);
                                            //return;
                                        }
                                        else
                                        {
                                            if (i == toCraftList.Count - 1)
                                            {
                                                //Core.Log($"No recipe available for {CR.Name}");
                                                Core.Log($"Cannot Craft any recipes");
                                                _state.Fire(Trigger.CraftDone);
                                                return;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Core.Log($"There is enough {CR.Name} available");
                                    }
                                }
                            }
                            else
                            {
                                Core.Log($"Gathering resources to craft {craftRec.RecipeName}");
                                break;
                            }
                            // this.craftRec = null;
                        }



                        float totalRecipeWeight = 0;

                        for (int i = 0; i < this.craftRec.Resources.Count; i++)
                        {
                            //  Core.Log("here5");
                            Resource tempR = null;
                            for (int j = 0; j < initialScan.Count; j++)
                            {
                                if (initialScan[j].Name.Contains(this.craftRec.Resources[i].Name) && !initialScan[j].Name.Contains("level"))
                                {
                                    tempR = initialScan[j];
                                    break;
                                }
                            }

                            //this.craftRec.Resources[i].BaseAmountForSelectedRecipe = this.craftRec.ResourceRatio[i];
                            if (tempR != null)
                            {
                                this.craftRec.Resources[i].Weight = tempR.Weight;
                                // Core.Log("here6");
                                totalRecipeWeight = totalRecipeWeight + this.craftRec.Resources[i].Weight * this.craftRec.Resources[i].BaseAmountForSelectedRecipe;
                                this.craftRec.Resources[i].SlotPos = tempR.SlotPos;
                            }
                        }
                        Core.Log($"Recipe weight is {totalRecipeWeight}");
                        this.craftRec.TotalWeight = totalRecipeWeight;
                        float craftCount;
                        if (craftRec.AmountToCraft < 0)
                        {
                            craftCount = (float)Math.Floor(playermaxweight / this.craftRec.TotalWeight);
                        }
                        else if ((float)Math.Floor(playermaxweight / this.craftRec.TotalWeight) < craftRec.AmountToCraft)
                        {
                            craftCount = (float)Math.Floor(playermaxweight / this.craftRec.TotalWeight);
                        }
                        else
                        {
                            craftCount = craftRec.AmountToCraft;
                        }


                        foreach (Resource R in this.craftRec.Resources)
                        {
                            Core.Log($"{R.Name} initially has {R.TotalAmount}");
                        }

                        //check for resources in storage and calculate total amounts of each resource


                        //Core.Log("here7");

                        float    limitingResourceCount = 1e20f;
                        Resource limitingResource      = null;
                        foreach (Resource R in this.craftRec.Resources)
                        {
                            Core.Log($"{R.Name} has {R.TotalAmount} in total");
                            R.MaxAmountForselectedRecipe = craftCount * R.BaseAmountForSelectedRecipe;
                            if ((R.TotalAmount - (craftCount * R.BaseAmountForSelectedRecipe)) < limitingResourceCount)
                            {
                                limitingResource      = R;
                                limitingResourceCount = R.TotalAmount - (craftCount * R.BaseAmountForSelectedRecipe);
                            }
                        }

                        Core.Log($"Limiting amount of resources is {limitingResourceCount} from {limitingResource.Name}");
                        //check if weight is the limiting factor
                        if (limitingResourceCount < 0)
                        {
                            //limited by resources calculated new craftCount
                            Core.Log("Resources Limited Number Available");
                            craftCount = (float)Math.Floor(limitingResource.TotalAmount / limitingResource.BaseAmountForSelectedRecipe);
                        }



                        for (int i = 0; i < this.craftRec.Resources.Count; i++)
                        {
                            Core.Log($"Craft Count is {craftCount}");

                            this.craftRec.Resources[i].CurrentAmountNeeded = craftCount * this.craftRec.Resources[i].BaseAmountForSelectedRecipe;
                            Resource CR = this.craftRec.Resources[i];

                            Core.Log($"Need {CR.CurrentAmountNeeded} of {CR.Name} in total");

                            for (int j = 0; j < initialScan.Count(); j++)
                            {
                                Resource BR = initialScan[j];

                                if (BR.Name.Contains(CR.Name) && !BR.Name.Contains("level"))
                                {
                                    if (CR.CurrentAmountNeeded <= 0)
                                    {
                                        Core.Log("Resource Gathered list Complete");
                                        break;
                                    }


                                    if (BR.StackSize <= CR.CurrentAmountNeeded)
                                    {
                                        Core.Log($"Stack size {BR.StackSize} of {CR.Name} in slot {BR.SlotPos}");


                                        BR.NeededSplitting     = false;
                                        BR.Split               = true;
                                        BR.SplitAmount         = BR.StackSize;
                                        BR.Name                = CR.Name;
                                        CR.CurrentAmountNeeded = CR.CurrentAmountNeeded - BR.StackSize;
                                        Core.Log($"Need {CR.CurrentAmountNeeded} more of {CR.Name}. Last Split amount {BR.SplitAmount}");
                                        resourceCollectList.Add(BR);
                                    }
                                    else
                                    {
                                        Core.Log($"Stack size {BR.StackSize} of {CR.Name} in slot {BR.SlotPos}");
                                        BR.SplitAmount         = CR.CurrentAmountNeeded;
                                        BR.Name                = CR.Name;
                                        CR.CurrentAmountNeeded = CR.CurrentAmountNeeded - BR.SplitAmount;
                                        Core.Log($"Need {CR.CurrentAmountNeeded} more of {CR.Name}. Last Split amount {BR.SplitAmount}");
                                        resourceCollectList.Add(BR);
                                    }
                                }
                            }
                        }



                        //for (int i = 0; i < this.craftRec.Resources.Count; i++)
                        //{
                        //    craftRec.Resources[i].SplitAmount = (float)Math.Floor(craftCount * this.craftRec.Resources[i].BaseAmountForSelectedRecipe);
                        //    if (this.craftRec.Resources[i].SplitAmount == this.craftRec.Resources[i].TotalAmount)
                        //    {
                        //         Core.Log("This resource doesnt need splitting");
                        //        this.craftRec.Resources[i].NeededSplitting = false;
                        //        this.craftRec.Resources[i].Split = true;
                        //    }
                        //}


                        this.craftRec.ResourceListUpdated = true;
                        foreach (Resource R in resourceCollectList)
                        {
                            Core.Log($"Need {R.SplitAmount} of {R.Name}");
                        }
                    }
                    //Get inventory
                    playerStorage = GameGui.Instance.CharacterInfoGui.InventoryItemStorage;
                    vaultStorage  = GameGui.Instance.BankBuildingVaultGui.BankVault.InventoryStorage;
                    vaultListBox  = GameGui.Instance.BankBuildingVaultGui.BankVault.VaultListBox;

                    int arrayLength = vaultStorage.ItemsSlotsRegistered.Count;
                    int firstItem   = vaultListBox.FirstVisibleItem;
                    int lastItem    = vaultListBox.LastVisibleItem;


                    bool allSplit = resourceCollectList.All <Resource>(r => r.Split == true);


                    if (!allSplit)
                    {
                        //coroutine = itemSplit();
                        //StartCoroutine(coroutine);
                        //vaultListBox.SetFirstVisibleRowVertical(2);

                        itemSplit();
                        return;
                    }
                    else
                    {
                        //Core.Log("stopping Coroutine");
                        //StopCoroutine(coroutine);
                    }


                    //IEnumerator
                    void itemSplit()
                    {
                        for (int i = 0; i < resourceCollectList.Count; i++)
                        {
                            if (resourceCollectList[i].Split)
                            {
                                Core.Log($"{resourceCollectList[i].Name} is Split");
                                // GameGui.Instance.CloseAllGui();
                            }
                            else
                            {
                                if ((firstItem < resourceCollectList[i].SlotPos && lastItem > resourceCollectList[i].SlotPos))
                                {
                                    foreach (var slot in vaultStorage.ItemsSlotsRegistered)
                                    {
                                        if (slot != null && slot.ObservedItemView != null)
                                        {
                                            var slotItemName = slot.ObservedItemView.name.ToLowerInvariant();

                                            int stackSize  = slot.GetItemStackSize();
                                            var slotObject = slot.gameObject;
                                            var slotPos    = vaultListBox.GetIndexOfVisibleItemObject(slotObject);

                                            if (slotItemName.Contains(resourceCollectList[i].Name) && !slotItemName.Contains("level") && resourceCollectList[i].SplitAmount < stackSize)
                                            {
                                                Core.Log($"Name Found. {resourceCollectList[i].Name} was contained in {slotItemName}.  ");


                                                if (slotPos == resourceCollectList[i].SlotPos)
                                                {
                                                    GameGui.Instance.ItemDetailsGui.ItemDetailsWindow.CloseImmediately();
                                                    if (!GameGui.Instance.ItemDetailsGui.ItemDetailsView.gameObject.activeInHierarchy)
                                                    {
                                                        GameGui.Instance.ItemDetailsGui.Show(slot, new Vector3(1, 1, 1));
                                                        //return;
                                                    }
                                                    var detailsGui = GameGui.Instance.ItemDetailsGui;

                                                    detailsGui.ItemDetailsView.SplitSlider.enabled = true;
                                                    detailsGui.ItemDetailsView.SplitButton.enabled = true;



                                                    Core.Log($"Itemdetails Gui is for {detailsGui.ItemDetailsWindow.ItemName.text}");

                                                    if (detailsGui.ItemDetailsView.SplitButton.isActiveAndEnabled && !resourceCollectList[i].Split)
                                                    {
                                                        float sliderValue = (resourceCollectList[i].SplitAmount) / (stackSize - 1);

                                                        var slider = GameGui.Instance.ItemDetailsGui.ItemDetailsView.SplitSlider;

                                                        var sliderType = slider.GetType();

                                                        detailsGui.ItemDetailsView.SplitSlider.value = sliderValue;



                                                        detailsGui.ItemDetailsView.OnClickSplit();
                                                        resourceCollectList[i].Split = true;
                                                        Core.Log($"{slotItemName} Split into {sliderValue * (stackSize - 1)} from slot {slotPos}");
                                                        resourceCollectList[i].SlotPos = initialScan.Count + splitCounter;
                                                        splitCounter++;
                                                        Core.Log($"{slotItemName} Split into {sliderValue * (stackSize - 1)} from slot {slotPos}. Split item slot pos is {resourceCollectList[i].SlotPos}");
                                                        GameGui.Instance.ItemDetailsGui.Close();
                                                        //GameGui.Instance.CloseAllGui();
                                                        vaultListBox.Panel.ResetPosition();
                                                        return;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    int row = (int)Math.Floor((double)resourceCollectList[i].SlotPos / 5) - 2;
                                    vaultListBox.SetFirstVisibleRowVertical(row);
                                    Core.Log($"Moving slider to row {row}");
                                    //yield break;
                                    return;
                                }
                            }
                            // yield return new WaitForSeconds(.1f);
                        }
                    }

                    if (timeCooldownMin > DateTime.Now)
                    {
                        return;
                    }


                    bool allRetrieved = resourceCollectList.All <Resource>(r => r.Retrieved == true);
                    bool allMoved     = resourceCollectList.All <Resource>(r => r.Moved == true);

                    if (ToRetrieve == null || ToRetrieve.Count == 0)
                    {
                        ToRetrieve = new List <UIItemSlot>();
                    }

                    //  Core.Log($"Slots to retrieve length is {ToRetrieve.Count}");

                    foreach (Resource R in resourceCollectList)
                    {
                        // Core.Log($"Resource Name {R.Name}");
                        //  Core.Log($"Split: {R.Split} Retrieved: {R.Retrieved} Moved: {R.Moved}");
                    }
                    // Core.Log($"All Split: {allSplit} All Retrieved: {allRetrieved} All Moved: {allMoved}");



                    Core.Log($"Resource Count {resourceCollectList.Count}");
                    if (allSplit && !allRetrieved)
                    {
                        for (int i = 0; i < resourceCollectList.Count; i++)
                        {
                            //  Core.Log($"Count i = {i}");

                            // Core.Log($"Resource Name {resourceCollectList[i].Name}");

                            if (resourceCollectList[i].Retrieved)
                            {
                                //   Core.Log("Item is retrieved");
                            }
                            else
                            {
                                Core.Log("Item NOT retrieved");
                                firstItem = vaultListBox.FirstVisibleItem;
                                lastItem  = vaultListBox.LastVisibleItem;
                                //if (lastItem >= vaultStorage.ItemsSlotsRegistered.Count - 2)
                                //{
                                //    vaultListBox.Panel.ResetPosition();
                                //    Core.Log("Resetting Panel Slider");
                                //}
                                //else
                                //{
                                //    vaultListBox.Panel.currentMomentum = new Vector3(0f, .5f, 0f);

                                //}

                                if ((firstItem < resourceCollectList[i].SlotPos && lastItem > resourceCollectList[i].SlotPos))
                                {
                                    vaultStorage.UpdateStorage();
                                    playerStorage.UpdateStorage();
                                    foreach (var slot in vaultStorage.ItemsSlotsRegistered)
                                    {
                                        if (slot != null && slot.ObservedItemView != null)
                                        {
                                            var slotItemName = slot.ObservedItemView.name.ToLowerInvariant();
                                            var slotObject   = slot.gameObject;
                                            var slotPos      = vaultListBox.GetIndexOfVisibleItemObject(slotObject);

                                            if (slotItemName.Contains(resourceCollectList[i].Name) && !slotItemName.Contains("level"))
                                            {
                                                Core.Log($"SECOND TIME: Name Found. {resourceCollectList[i].Name} was contained in {slotItemName} ");

                                                Core.Log($"Slot stack Size {slot.GetItemStackSize()}. Required resource stack size {resourceCollectList[i].SplitAmount}");

                                                if (slot.GetItemStackSize() < resourceCollectList[i].SplitAmount + 1 && slot.GetItemStackSize() > resourceCollectList[i].SplitAmount - 1)
                                                {
                                                    GameGui.Instance.MoveItemToItemContainer(slot, playerStorage.ItemContainerProxy);

                                                    _localPlayerCharacterView.RequestMove(playerCenter + _localPlayerCharacterView.transform.forward * -1);
                                                    resourceCollectList[i].Retrieved = true;
                                                    timeCooldownMin = DateTime.Now + TimeSpan.FromSeconds(1);

                                                    return;
                                                    // break;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    int row = (int)Math.Floor((double)resourceCollectList[i].SlotPos / 5) - 2;
                                    vaultListBox.SetFirstVisibleRowVertical(row);
                                    Core.Log($"Moving slider to row {row}");
                                    //yield break;
                                    timeCooldownMin = DateTime.Now + TimeSpan.FromSeconds(1);
                                    return;
                                }
                            }
                        }
                    }


                    if (allRetrieved)
                    {
                        _state.Fire(Trigger.GotItems);
                        _localPlayerCharacterView.CreateTextEffect("Finished banking");
                        Core.Log("[Bank Done]");
                        ResetCriticalVariables();
                        // ResetCraftingVariables();
                    }
                }
            }
            else
            {
                _localPlayerCharacterView.CreateTextEffect($"Finding Path to Bank in {bankCluster.GetName()}");
                var pathfinder = new WorldmapPathfinder();
                if (pathfinder.TryFindPath(currentWorldCluster, bankCluster, StopClusterFunction, out var path, out var pivots))
                {
                    _collectItemsWorldPathingRequest = new WorldPathingRequest(currentWorldCluster, bankCluster, path, _skipUnrestrictedPvPZones);
                }
            }
        }
Esempio n. 8
0
        public void Bank()
        {
            var player = _localPlayerCharacterView.GetLocalPlayerCharacter();

            if (!HandleMounting(Vector3.zero))
            {
                return;
            }

            //if (!_isDepositing && _localPlayerCharacterView.GetLoadPercent() <= _percentageForBanking)
            //{
            //    Core.Log("[Restart]");
            //    _state.Fire(Trigger.Restart);
            //    return;
            //}

            if (HandlePathing(ref _worldPathingRequest))
            {
                return;
            }

            if (HandlePathing(ref _bankPathingRequest))
            {
                return;
            }

            API.Direct.Worldmap worldmapInstance = GameGui.Instance.WorldMap;

            Vector3           playerCenter        = _localPlayerCharacterView.transform.position;
            ClusterDescriptor currentWorldCluster = _world.GetCurrentCluster();
            ClusterDescriptor townCluster         = worldmapInstance.GetCluster(TownClusterNames[_selectedTownClusterIndex]).Info;
            ClusterDescriptor bankCluster         = townCluster.GetExits().Find(e => e.GetDestination().GetName().Contains("Bank")).GetDestination();

            if (currentWorldCluster.GetName() == bankCluster.GetName())
            {
                var banks = _client.GetEntities <BankBuildingView>((x) => { return(true); });

                if (banks.Count == 0)
                {
                    return;
                }

                _currentTarget = banks.First();
                if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), _currentTarget, IsBlockedWithExitCheck, out List <Vector3> pathing))
                {
                    _bankPathingRequest = new ClusterPathingRequest(_localPlayerCharacterView, _currentTarget, pathing);
                    return;
                }

                if (_currentTarget is BankBuildingView resource)
                {
                    if (!GameGui.Instance.BankBuildingVaultGui.gameObject.activeInHierarchy)
                    {
                        _localPlayerCharacterView.Interact(resource);
                        return;
                    }

                    //Get inventory
                    var playerStorage = GameGui.Instance.CharacterInfoGui.InventoryItemStorage;
                    var vaultStorage  = GameGui.Instance.BankBuildingVaultGui.BankVault.InventoryStorage;
                    var playerListBox = GameGui.Instance.CharacterInfoGui.InventoryListBox;
                    var ToDeposit     = new List <UIItemSlot>();

                    //Get all items we need
                    //    var resourceTypes = Enum.GetNames(typeof(ResourceType)).Select(r => r.ToLowerInvariant()).ToArray();
                    //    foreach (var slot in playerStorage.ItemsSlotsRegistered)
                    //        if (slot != null && slot.ObservedItemView != null)
                    //        {
                    //            var slotItemName = slot.ObservedItemView.name.ToLowerInvariant();
                    //            if (resourceTypes.Any(r => slotItemName.Contains(r)))
                    //                ToDeposit.Add(slot);
                    //        }

                    //    _isDepositing = ToDeposit != null && ToDeposit.Count > 0;
                    //    foreach (var item in ToDeposit)
                    //    {
                    //        GameGui.Instance.MoveItemToItemContainer(item, vaultStorage.ItemContainerProxy);
                    //    }

                    //    if (_isDepositing)
                    //        return;
                    //    else
                    //    {
                    //        Core.Log("[Bank Done]");
                    //        _state.Fire(Trigger.BankDone);
                    //    }
                    //}

                    List <int> dontMoveSlots = new List <int> {
                        0, 1, 2, 3, 4
                    };
                    foreach (var slot in playerStorage.ItemsSlotsRegistered)
                    {
                        if (slot != null && slot.ObservedItemView != null)
                        {
                            var slotItemName = slot.ObservedItemView.name.ToLowerInvariant();
                            // Core.Log(slotItemName);
                            var slotObject = slot.gameObject;
                            var slotPos    = playerListBox.GetIndexOfVisibleItemObject(slotObject);
                            Core.Log($"Current Slot Pos {slotPos}");
                            // if (resourceTypes.Any(r => !slotItemName.Contains(r)))
                            if (dontMoveSlots.Contains(slotPos))
                            {
                                if (slot.GetItemStackSize() > 1)
                                {
                                    GameGui.Instance.ItemDetailsGui.ItemDetailsWindow.CloseImmediately();
                                    if (!GameGui.Instance.ItemDetailsGui.ItemDetailsView.gameObject.activeInHierarchy)
                                    {
                                        GameGui.Instance.ItemDetailsGui.Show(slot, new Vector3(1, 1, 1));
                                    }
                                    var detailsGui = GameGui.Instance.ItemDetailsGui;

                                    detailsGui.ItemDetailsView.SplitSlider.enabled = true;
                                    detailsGui.ItemDetailsView.SplitButton.enabled = true;

                                    Core.Log($"Itemdetails Gui is for {detailsGui.ItemDetailsWindow.ItemName.text}");

                                    if (detailsGui.ItemDetailsView.SplitButton.isActiveAndEnabled)
                                    {
                                        var slider = GameGui.Instance.ItemDetailsGui.ItemDetailsView.SplitSlider;
                                        detailsGui.ItemDetailsView.SplitSlider.value = 1;
                                        detailsGui.ItemDetailsView.OnClickSplit();
                                        GameGui.Instance.ItemDetailsGui.Close();
                                    }
                                }
                            }
                            else
                            {
                                //Core.Log($"Moving {slotPos}");
                                ToDeposit.Add(slot);
                            }
                        }
                    }
                    _isDepositing = ToDeposit != null && ToDeposit.Count > 0;
                    foreach (var item in ToDeposit)
                    {
                        GameGui.Instance.MoveItemToItemContainer(item, vaultStorage.ItemContainerProxy);
                    }

                    if (_isDepositing)
                    {
                        return;
                    }
                    else
                    {
                        Core.Log("Transfer To Storage Done");
                        _state.Fire(Trigger.BankDone);
                    }
                }
            }
            else
            {
                var pathfinder = new WorldmapPathfinder();
                if (pathfinder.TryFindPath(currentWorldCluster, bankCluster, StopClusterFunction, out var path, out var pivots))
                {
                    _worldPathingRequest = new WorldPathingRequest(currentWorldCluster, bankCluster, path, _skipUnrestrictedPvPZones);
                }
            }
        }
Esempio n. 9
0
        public void Repair()
        {
            var player = _localPlayerCharacterView.GetLocalPlayerCharacter();

            //Core.Log("Repairing");
            if (HandlePathing(ref _worldPathingRequest))
            {
                return;
            }

            if (HandlePathing(ref _repairFindPathingRequest, () => _client.GetEntities <RepairBuildingView>((x) => { return(true); }).Count > 0))
            {
                return;
            }

            if (HandlePathing(ref _repairPathingRequest, null, () => _reachedPointInBetween = true))
            {
                return;
            }

            Worldmap worldmapInstance = GameGui.Instance.WorldMap;

            Vector3           playerCenter        = _localPlayerCharacterView.transform.position;
            ClusterDescriptor currentWorldCluster = _world.GetCurrentCluster();
            ClusterDescriptor townCluster         = worldmapInstance.GetCluster(TownClusterNames[_selectedTownClusterIndex]).Info;

            //Core.Log("Repairing 4");
            if (currentWorldCluster.GetName() == townCluster.GetName())
            {
                var repairs = _client.GetEntities <RepairBuildingView>((x) => { return(true); });
                //Core.Log("Repairing 5");
                if (repairs.Count == 0)
                {
                    var exitPositionPoint = _world.GetCurrentCluster().GetExits().Find(e => e.GetDestination().GetName().Contains("Bank")).GetPosition();
                    var exitPosition      = new Vector2(exitPositionPoint.GetX(), exitPositionPoint.GetY());
                    var targetPosition    = new Vector3(exitPosition.x, 0, exitPosition.y);
                    //Core.Log("Repairing 6");
                    if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), targetPosition, IsBlockedWithExitCheck, out List <Vector3> pathing))
                    {
                        Core.Log("[No RepairStation found - moving to bank]");
                        _repairFindPathingRequest = new PositionPathingRequest(_localPlayerCharacterView, targetPosition, pathing);
                    }
                    else
                    {
                        Core.Log("Bank not found either. Moving forward more");
                        _localPlayerCharacterView.RequestMove(playerCenter + _localPlayerCharacterView.transform.forward * 5);
                    }

                    //Core.Log("Repairing 7");
                    return;
                }

                _currentTarget = repairs.First();
                if (_currentTarget is RepairBuildingView repairer)
                {
                    if (!repairer.IsInUseRange(_localPlayerCharacterView.LocalPlayerCharacter))
                    {
                        if (!_reachedPointInBetween)
                        {
                            var repairCollider         = repairer.GetComponentsInChildren <Collider>().First(c => c.name.ToLowerInvariant().Contains("clickable"));
                            var repairColliderPosition = new Vector2(repairCollider.transform.position.x, repairCollider.transform.position.z);
                            var exitPositionPoint      = _world.GetCurrentCluster().GetExits().Find(e => e.GetDestination().GetName().Contains("Bank")).GetPosition();
                            var exitPosition           = new Vector2(exitPositionPoint.GetX(), exitPositionPoint.GetY());
                            var clampedPosition        = Vector2.MoveTowards(repairColliderPosition, exitPosition, 10);
                            var targetPosition         = new Vector3(clampedPosition.x, 0, clampedPosition.y);

                            Core.Log("[Move closer to RepairStation]");
                            if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), targetPosition, IsBlockedWithExitCheck, out List <Vector3> pathing))
                            {
                                _repairPathingRequest = new PositionPathingRequest(_localPlayerCharacterView, targetPosition, pathing);
                            }
                        }
                        else
                        {
                            Core.Log("[Start Interacting with RepairStation]");
                            _localPlayerCharacterView.Interact(repairer);
                        }
                    }
                    else
                    {
                        if (_localPlayerCharacterView.GetLocalPlayerCharacter().HasAnyBrokenItem())
                        {
                            if (_localPlayerCharacterView.IsItemRepairing())
                            {
                                return;
                            }

                            var repairUsage = GameGui.Instance.BuildingUsageAndManagementGui.BuildingUsage;
                            var silverUI    = GameGui.Instance.PaySilverDetailGui;

                            if (silverUI.UserData == repairUsage.RepairItemView && silverUI.gameObject.activeInHierarchy)
                            {
                                Core.Log("[Paying silver costs]");
                                silverUI.OnPay();
                                return;
                            }

                            if (repairUsage.gameObject.activeInHierarchy)
                            {
                                Core.Log("[Reparing all]");
                                repairUsage.RepairItemView.OnClickRepairAllButton();
                                return;
                            }

                            Core.Log("[Interact with RepairStation]");
                            _localPlayerCharacterView.Interact(repairer);
                        }
                        else
                        {
                            _reachedPointInBetween = false;
                            Core.Log("[Repair Done]");
                            _state.Fire(Trigger.RepairDone);
                        }
                    }
                }
            }
            else
            {
                Core.Log("Heading To Town For Repairing");
                var pathfinder = new WorldmapPathfinder();
                if (pathfinder.TryFindPath(currentWorldCluster, townCluster, StopClusterFunction, out var path, out var pivots))
                {
                    _worldPathingRequest = new WorldPathingRequest(currentWorldCluster, townCluster, path, _skipUnrestrictedPvPZones);
                }
            }
        }
Esempio n. 10
0
        public void Repair()
        {
            _client = GameManager.GetInstance();
            if (_client.GetState() != GameState.Playing)
            {
                Core.Log("Client state not equal to Playing so we will wait");
                return;
            }

            var player = _localPlayerCharacterView.GetLocalPlayerCharacter();

            if (HandlePathing(ref _worldPathingRequest))
            {
                return;
            }

            if (HandlePathing(ref _repairFindPathingRequest, () => _client.GetEntities <RepairBuildingView>((x) => { return(true); }).Count > 0))
            {
                return;
            }

            if (HandlePathing(ref _repairPathingRequest, null))
            {
                return;
            }

            Worldmap worldmapInstance = GameGui.Instance.WorldMap;

            Vector3           playerCenter        = _localPlayerCharacterView.transform.position;
            ClusterDescriptor currentWorldCluster = _world.GetCurrentCluster();
            ClusterDescriptor townCluster         = worldmapInstance.GetCluster(TownClusterNames[_selectedTownClusterIndex]).Info;

            if (currentWorldCluster.GetName() == townCluster.GetName())
            {
                Core.Log("Arrived at town");
                if (_nextRepairAction == new DateTime())
                {
                    Core.Log("Adding 3 seconds to Repair wait time to avoid load issues.");
                    _nextRepairAction = DateTime.UtcNow.AddSeconds(3);
                }

                if (waiting(_nextRepairAction))
                {
                    return;
                }

                if (!moveToTownRepair(currentWorldCluster))
                {
                    Core.Log("moving to Town Repair location");
                    return;
                }
                else
                {
                    Core.Log("Begin Repairing.");
                    if (_localPlayerCharacterView.GetLocalPlayerCharacter().HasAnyDamagedItem())
                    {
                        if (!repairItems())
                        {
                            return;
                        }
                    }
                    else
                    {
                        _nextRepairAction = new DateTime();
                        _movingToRepair   = false;

                        _localPlayerCharacterView.RequestMove(GetDefaultBankPosition(currentWorldCluster.GetName().ToLowerInvariant()));

                        Core.Log("[Repair Done]");
                        _state.Fire(Trigger.RepairDone);
                    }
                }
            }
            else
            {
                Core.Log("Not in town. Try to find path to town.");
                var pathfinder = new WorldmapPathfinder();
                if (pathfinder.TryFindPath(currentWorldCluster, townCluster, StopClusterFunction, out var path, out var pivots))
                {
                    Core.Log("Path Found to Town.");
                    _worldPathingRequest = new WorldPathingRequest(currentWorldCluster, townCluster, path, _skipUnrestrictedPvPZones);
                }
            }
        }
Esempio n. 11
0
        public void Craft()
        {
            Worldmap worldmapInstance = GameGui.Instance.WorldMap;

            Vector3 playerCenter = _localPlayerCharacterView.transform.position;

            ClusterDescriptor currentWorldCluster = _world.GetCurrentCluster();

            ClusterDescriptor townCluster = worldmapInstance.GetCluster(TownClusterNames[_selectedCraftTownClusterIndex]).Info;

            //Vector2 buildingSize = Vector2.zero;

            Collider buildingCollider;

            Vector3 building3dcenter;

            Vector2 building2dcenter;

            Vector3 building2d3dcenter;

            Vector3 closestpoint;

            ClusterMapUI clustermapinstance = null;

            List <Vector3> posBoundary = null;



            if (HandlePathing(ref _worldPathingRequest))
            {
                return;
            }
            //Core.Log("Here 66");
            //if (HandlePathing(ref _craftFindPathingRequest, () => _client.GetEntities<RepairBuildingView>((x) => { return true; }).Count > 0))
            //    return;

            //if (HandlePathing(ref _craftFindPathingRequest, () => _client.GetEntities<CraftBuildingView>((x) => { return true; }).Count > 0))
            //   return;

            if (HandlePathing(ref _craftingClusterPathingRequest))
            {
                return;
            }


            if (HandlePathing(ref _craftingPathingRequest, null, () => _craftreachedPointInBetween = true))
            {
                return;
            }

            //Core.Log($"CraftreachedPointInBetween {_craftreachedPointInBetween}");

            // Core.Log("Here 67");
            //GameManager.GetInstance().GetLocalPlayerCharacterView().useGUILayout
            if (currentWorldCluster.GetName() == townCluster.GetName())
            {
                try
                {
                    // Core.Log("Number of buildings " + Convert.ToString(Town._building.Length));
                    //Core.Log("Notes2");
                }
                catch (NullReferenceException)
                {
                }

                if (Town == null || Town._building.Length <= 0)
                {
                    try
                    {
                        if (!GameGui.Instance.ClusterMapGui.gameObject.activeInHierarchy)

                        {
                            Core.Log("Opening Map");
                            GameGui.Instance.ClusterMapGui.Show();
                            // Core.Log("here3");
                        }


                        if (GameGui.Instance.ClusterMapGui.gameObject.activeInHierarchy)
                        {
                            // Core.Log("Map is open");
                            clustermapinstance = GameGui.Instance.ClusterMapGui;
                            List <ClusterBuilding> tempClusterBuildingList = new List <ClusterBuilding>();
                            List <int>             idlist = new List <int>();
                            // Core.Log("here4");
                            for (int i = 0; i < 2000; i++)
                            {
                                try
                                {
                                    ClusterBuilding tempClusterBuilding = clustermapinstance.GetBuilding(i);

                                    if (tempClusterBuilding.CanUse)
                                    {
                                        tempClusterBuildingList.Add(tempClusterBuilding);
                                        idlist.Add(i);

                                        //Core.Log($"added {i}");
                                    }
                                }
                                catch (NullReferenceException)
                                {
                                    //Core.Log("caught");
                                }
                            }
                            Building[] buildingArray = new Building[tempClusterBuildingList.Count];
                            int        counter       = 0;
                            // Core.Log("here5");
                            foreach (ClusterBuilding CB in tempClusterBuildingList)
                            {
                                GameGui.Instance.ClusterMapGui.ShowDetails(CB);
                                string Title = GameGui.Instance.ClusterMapGui.BuildingUI.Title.text;
                                string Owner = GameGui.Instance.ClusterMapGui.BuildingUI.Owner.text;
                                // string objTitle = CB.Hitbox.name;

                                //Core.Log("making buidling");
                                string UsageFeeS   = GameGui.Instance.ClusterMapGui.BuildingUI.UsageFee.text;
                                string DurabilityS = GameGui.Instance.ClusterMapGui.BuildingUI.Durability.text;
                                string FoodS       = GameGui.Instance.ClusterMapGui.BuildingUI.Food.text;

                                String[] substringsDurabilityS = DurabilityS.Split('%');

                                String[] substringsUsageFee = UsageFeeS.Split(' ', '%');

                                String[] substringsFood = FoodS.Split(' ', '%');

                                // Core.Log(FoodS);
                                float Food = Convert.ToSingle(substringsFood[0]);


                                float DurabilityF = Convert.ToSingle(substringsDurabilityS[0]);

                                float UsageFeeF = Convert.ToSingle(substringsUsageFee[1]);
                                //Core.Log("making buidling2");
                                bool CanUse = CB.CanUse;

                                Vector2 Size = CB.Size;
                                //Core.Log("making buidling2");
                                int Tier = Convert.ToInt32(CB.Tier);



                                Vector2  Position = CB.Position;
                                Collider collider = CB.Hitbox;

                                GameObject obj = collider.gameObject;
                                // Core.Log($" collider object name {obj.name}");
                                var pP = obj.transform.position.c();

                                var point = pP;

                                float Buildingy = _landscape.GetTerrainHeight(point, out RaycastHit hit);

                                long ID = idlist[counter];

                                Building tempBuilding = new Building(Title, Tier, Food, CanUse, Position, Owner, Size, collider, Buildingy, UsageFeeF, ID, DurabilityF);

                                buildingArray[counter] = tempBuilding;
                                counter++;
                            }

                            Town = new Town(buildingArray);
                            Core.Log("Town made");
                        }

                        //if (!GameGui.Instance.ClusterMapGui.gameObject.activeInHierarchy)

                        //{
                        //    Core.Log("Closing Map");
                        //    GameGui.Instance.ClusterMapGui.Close();
                        //}
                        // GameGui.Instance.CloseAllGui();
                    }

                    catch (NullReferenceException)
                    {
                        //Core.Log("here2");
                        //return;
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        Core.Log("here3");
                    }
                }

                else
                {
                    try
                    {
                        int minTier = 1;

                        //Building[] clusterBuildings = Town._building;
                        //for(int i = 0; i < clusterBuildings.Length;i++)
                        //{
                        //   Core.Log($" {clusterBuildings[i].Title}");
                        //}

                        //string bname = "toolmaker";
                        string bname = craftRec.CraftBuilding;
                        // Core.Log("Here 7");
                        //var TchosenB = clusterBuildings.TakeWhile( b => b.Title.ToLowerInvariant().Contains(bname) && b.Tier > minTier);

                        //var TchosenB = clusterBuildings.First(b => b.Title.ToLowerInvariant().Contains(bname) && b.Tier > minTier);

                        // var TchosenB = clusterBuildings.Where(BItem => BItem.Tier > minTier)
                        //.Where(BItem => BItem.Title.ToLowerInvariant().Contains(bname))
                        //   .Select(BItem =>BItem.Title);

                        //var minUsage = TchosenB.Min(b => b.UsageFee);

                        //Building B1 = (Building)TchosenB.Select(b => b.UsageFee == minUsage);



                        // Core.Log(chosenB.);


                        // Building[] minTierBuildings = clusterBuildings.All<Building>(B)
                        //Core.Log("here");
                        List <Building> reducedBuildings = new List <Building>();
                        foreach (Building B in Town)
                        {
                            //Core.Log($"{ B.Title}");
                            if (B.Title.ToLowerInvariant().Contains(bname) && B.Durability > 50 && B.Food >= 4)
                            {
                                if (B.Tier > minTier)
                                {
                                    reducedBuildings.Add(B);
                                }
                            }
                        }

                        if (reducedBuildings.Count <= 0)
                        {
                            Core.Log("There are no builings available for crafting");
                            return;
                        }


                        // Core.Log($"Number of buildings { reducedBuildings.Count}");
                        //var minUsage = reducedBuildings.Min(b => b.UsageFee);
                        var minUsage = 1e20;
                        for (int i = 0; i < reducedBuildings.Count; i++)
                        {
                            if (reducedBuildings[i].UsageFee < minUsage)
                            {
                                minUsage = reducedBuildings[i].UsageFee;
                                // Core.Log("min feeset");
                            }
                        }



                        foreach (Building bb in reducedBuildings)
                        {
                            if (bb.UsageFee == minUsage)
                            {
                                // Core.Log("Found min. Building chosen");
                                this.craftBuilding = bb;
                                break;
                            }
                            else
                            {
                                // Core.Log("not min");
                            }
                        }
                        // Core.Log($"made it{B1.Title}");
                        //Building B1 = reducedBuildings.First(b => (b.UsageFee == minUsage));

                        for (int i = 0; i < reducedBuildings.Count; i++)
                        {
                            // Core.Log($" {reducedBuildings[i].UsageFee}");
                        }



                        building2dcenter = this.craftBuilding.Position;


                        if (this._buildingSize == Vector2.zero)
                        {
                            // Core.Log("setting building size");
                            this._buildingSize = this.craftBuilding.Size;
                        }
                        else
                        {
                            // Core.Log("building size is set");
                        }


                        buildingCollider = this.craftBuilding.BuildingCollider;

                        float buildingy = this.craftBuilding.Buildingy;

                        List <Vector3> getPosBoundary(Vector2 _size, Vector2 _center, float buildingH)
                        {
                            float sizecheck = 0.1f;

                            if (_size.x > 5)
                            {
                                sizecheck = 0.1f;
                            }
                            float _xmax = _center.x + (_size.x / 2);
                            float _xmin = _center.x - (_size.x / 2);
                            float _ymax = _center.y + (_size.y / 2);
                            float _ymin = _center.y - (_size.y / 2);

                            List <Vector3> _posBoundary = new List <Vector3>();

                            for (float i = _xmin; i < _xmax; i++)
                            {
                                Vector3 temp = new Vector3(i, buildingH, _ymin);

                                _posBoundary.Add(temp);
                            }

                            for (float i = _ymin; i < _ymax; i++)
                            {
                                Vector3 temp = new Vector3(_xmax, buildingH, i);

                                _posBoundary.Add(temp);
                            }

                            for (float i = _xmax; i > _xmin; i--)
                            {
                                Vector3 temp = new Vector3(i, buildingH, _ymax);

                                _posBoundary.Add(temp);
                            }

                            for (float i = _ymax; i > _ymin; i--)
                            {
                                Vector3 temp = new Vector3(_xmax, buildingH, i);

                                _posBoundary.Add(temp);
                            }
                            return(_posBoundary);
                        }


                        bool Mover(List <Vector3> vList)
                        {
                            bool pathFound      = false;
                            int  failedAttempts = 1;
                            int  iterator       = 1;

                            foreach (Vector3 tryV in vList)
                            {
                                if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), tryV, IsBlockedWithExitCheck, out List <Vector3> pathing))
                                {
                                    pathFound = true;
                                    Core.Log($"PATH FOUND TO {tryV} !!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
                                    finalDestination = tryV;

                                    _craftingPathingRequest = new PositionPathingRequest(_localPlayerCharacterView, tryV, pathing, true, true);
                                    if (GameGui.Instance.ClusterMapGui.gameObject.activeInHierarchy)

                                    {
                                        Core.Log("Closing Map");
                                        GameGui.Instance.ClusterMapGui.Close();
                                    }
                                    return(pathFound);
                                }
                                else
                                {
                                    Core.Log($"No path to {tryV} found. Attempt {iterator} / {vList.Count}");
                                    failedAttempts++;

                                    _failedFindAttempts = 0;
                                }
                                iterator++;
                            }

                            return(pathFound);
                        }

                        List <List <Vector3> > ListReducer(List <Vector3> full)
                        {
                            var lShort        = new List <List <Vector3> >();
                            int maxListLength = 2;

                            for (int i = 0; i < full.Count; i += maxListLength)
                            {
                                lShort.Add(full.GetRange(i, Math.Min(maxListLength, full.Count - i)));
                            }

                            return(lShort);
                        }

                        //if (_craftreachedPointInBetween)
                        //    return;
                        var     distanceToFinalDestination = 0f;
                        Vector2 PC2D = new Vector2(playerCenter.x, playerCenter.z);
                        Vector2 FD2D = new Vector2(finalDestination.x, finalDestination.z);

                        var distanceToBuildingCentre = Vector2.Distance(building2dcenter, PC2D);
                        var minimumDistance          = -40f;
                        if (FD2D != Vector2.zero)
                        {
                            distanceToFinalDestination = Vector2.Distance(PC2D, FD2D);
                            minimumDistance            = 40f;
                        }
                        //If gets stuck
                        // if (_craftreachedPointInBetween && finalDestination != Vector3.zero && distanceToFinalDestination>minimumDistance)
                        List <CraftBuildingView> craftBuildings        = null;
                        List <CraftBuildingView> reducedCraftBuildings = new List <CraftBuildingView>();
                        craftBuildings = _client.GetEntities <CraftBuildingView>((x) => { return(true); });

                        if (this._craftTarget == null)
                        {
                            for (int i = 0; i < craftBuildings.Count; i++)
                            {
                                // Core.Log($"Building name {craftBuildings[i].PrefabName}");

                                string craftname = craftBuildings[i].PrefabName.ToLowerInvariant();

                                string B1name = this.craftBuilding.Title.ToLowerInvariant();

                                B1name    = B1name.Replace(" ", "");
                                craftname = craftname.Replace(" ", "");

                                if (B1name.Contains(craftname))
                                {
                                    Core.Log($"Target Acquired with {craftname} using string {B1name}. Adding to reduced list ");
                                    reducedCraftBuildings.Add(craftBuildings[i]);
                                }
                            }

                            Core.Log($"Reduced Craft building list count is {reducedCraftBuildings.Count}");


                            if (reducedCraftBuildings != null && reducedCraftBuildings.Count > 0)
                            {
                                float closestDistance = 1e20f;

                                for (int i = 0; i < reducedCraftBuildings.Count; i++)
                                {
                                    var CB                    = reducedCraftBuildings[i];
                                    var CBC                   = CB.GetComponentsInChildren <Collider>().First(c => c.name.ToLowerInvariant().Contains("clickable"));
                                    var CBCpos                = new Vector2(CBC.transform.position.x, CBC.transform.position.z);
                                    var finalDestination2D    = new Vector2(finalDestination.x, finalDestination.z);
                                    var maxDistanceToCollider = Vector2.Distance(this.craftBuilding.Position, new Vector2(this.craftBuilding.Position.x + this.craftBuilding.Size.x * 0.5f, this.craftBuilding.Position.y + this.craftBuilding.Size.y * 0.5f));
                                    var distanceBetween       = Vector2.Distance(CBCpos, this.craftBuilding.Position);
                                    Core.Log($"Reduced Building name {reducedCraftBuildings[i].PrefabName}");
                                    Core.Log($"Collider {CBC}");
                                    Core.Log($"Collider Position {CBCpos}");
                                    Core.Log($"Building Center {this.craftBuilding.Position}");
                                    Core.Log($"Max distance Between Collider and Center {maxDistanceToCollider}");
                                    Core.Log($"Final Destination {finalDestination2D}");
                                    Core.Log($"Distance Between {distanceBetween}");
                                    Core.Log($"Closest distance {closestDistance}");
                                    if (distanceBetween < maxDistanceToCollider)
                                    {
                                        //closestDistance = distanceBetween;
                                        //Core.Log($"Closest distance {closestDistance}");
                                        Core.Log($"Craft Target Located ");
                                        this._craftTarget = reducedCraftBuildings[i];
                                    }
                                }
                                if (_craftreachedPointInBetween && finalDestination != Vector3.zero)
                                {
                                    Vector3 rangedFinalDestination = Vector3.zero;
                                    if (stuckTimer < DateTime.Now)
                                    {
                                        isMovingUpdate();
                                    }
                                    else
                                    {
                                        _localPlayerCharacterView.RequestMove(randomSpot);
                                        return;
                                    }

                                    if (!IsMoving)
                                    {
                                        Core.Log("Not Moving. Going To random Spot");
                                        stuckTimer             = DateTime.Now + TimeSpan.FromSeconds(2);
                                        randomSpot             = new Vector3(UnityEngine.Random.Range(-100f, 100f), 0, UnityEngine.Random.Range(-100f, 100f)) + _localPlayerCharacterView.transform.position;
                                        rangedFinalDestination = new Vector3(finalDestination.x + UnityEngine.Random.Range(-10f, 10f), finalDestination.y + UnityEngine.Random.Range(-10f, 10f), finalDestination.z + UnityEngine.Random.Range(-10f, 10f));
                                    }
                                    else
                                    {
                                        Core.Log("Moving CLoser with request move 1");


                                        _localPlayerCharacterView.RequestMove(rangedFinalDestination);
                                        return;
                                    }
                                }
                                //if (_craftreachedPointInBetween)
                                //{
                                //    if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), finalDestination, IsBlockedGathering, out List<Vector3> pathing))
                                //    {
                                //        Core.Log("Creating new path from crafting ");
                                //        _craftingPathingRequest = new PositionPathingRequest(_localPlayerCharacterView, finalDestination, pathing, true, true, _skipUnrestrictedPvPZones );

                                //    }
                                //    Core.Log($"Still not at destination. {distanceToFinalDestination} away");
                                //    return;

                                //}
                            }
                            else
                            {
                                if (_craftreachedPointInBetween && finalDestination != Vector3.zero)
                                {
                                    Vector3 rangedFinalDestination = Vector3.zero;
                                    if (stuckTimer < DateTime.Now)
                                    {
                                        isMovingUpdate();
                                    }
                                    else
                                    {
                                        _localPlayerCharacterView.RequestMove(randomSpot);
                                        return;
                                    }

                                    if (!IsMoving)
                                    {
                                        Core.Log("Not Moving. Going To random Spot");
                                        stuckTimer = DateTime.Now + TimeSpan.FromSeconds(2);
                                        randomSpot = new Vector3(UnityEngine.Random.Range(-100f, 100f), 0, UnityEngine.Random.Range(-100f, 100f)) + _localPlayerCharacterView.transform.position;
                                        //rangedFinalDestination = new Vector3(finalDestination.x + UnityEngine.Random.Range(-10f, 10f), finalDestination.y + UnityEngine.Random.Range(-10f, 10f), finalDestination.z + UnityEngine.Random.Range(-10f, 10f));
                                    }
                                    else
                                    {
                                        Core.Log($"Moving CLoser with request move to final destination at {finalDestination}");


                                        _localPlayerCharacterView.RequestMove(finalDestination);
                                        return;
                                    }
                                }
                            }
                        }
                        else if (!reachedFinalDestination)
                        {
                            if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), this._craftTarget, IsBlockedWithExitCheck, out List <Vector3> pathing))
                            {
                                Core.Log("FOUND A CLUSTER PATH");
                                _craftingClusterPathingRequest = new ClusterPathingRequest(_localPlayerCharacterView, this._craftTarget, pathing);
                                return;
                            }
                            else
                            {
                                Core.Log("Couldnt find a cluster path");
                            }
                        }



                        //if (this._craftTarget != null && this._craftTarget is CraftBuildingView cb)
                        //{
                        //    Core.Log("Close Enough ");
                        //    _craftingPathingRequest = null;
                        //    _craftreachedPointInBetween = false;
                        //    return;
                        //}


                        //if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), finalDestination, IsBlockedGathering, out List<Vector3> pathing))
                        //{
                        //    Core.Log("Creating new path from crafting ");
                        //    _craftingPathingRequest = new PositionPathingRequest(_localPlayerCharacterView, finalDestination, pathing, true, true);

                        //}
                        //else
                        //{
                        //    Core.Log($" Not Moving Timer {notMovingTimer}");
                        //    Core.Log($"Time Now {DateTime.Now}");
                        //    if (DateTime.Now > notMovingTimer)
                        //    {
                        //        Core.Log("Moving from crafting");

                        //        isMovingUpdate();
                        //    }
                        //    else
                        //    {
                        //        Core.Log($"Moving To random position (Crafting) {randomSpot}");
                        //        _localPlayerCharacterView.RequestMove(randomSpot);
                        //        return;
                        //    }

                        //    if (!IsMoving)
                        //    {
                        //        Core.Log("Not moving called from Crafting");
                        //        randomSpot = (_localPlayerCharacterView.transform.position + new Vector3(UnityEngine.Random.Range(-100f, 100f), 0, UnityEngine.Random.Range(-100f, 100f)));
                        //        notMovingTimer = DateTime.Now + TimeSpan.FromSeconds(2);
                        //    }
                        //}


                        //if (_craftreachedPointInBetween)
                        //{
                        //    Core.Log("Pathing Request Restarting");
                        //    _craftPathFound = !_craftreachedPointInBetween;
                        //}

                        if (!this._craftPathFound)
                        {
                            Core.Log("[Move closer to craftStation]");


                            if (posBoundary == null || posBoundary.Count <= 0)
                            {
                                posBoundary = getPosBoundary(_buildingSize, building2dcenter, buildingy);
                            }

                            var shortPosBoundary = ListReducer(posBoundary);

                            Core.Log($"Counter at {pathFindingCounter} out of {shortPosBoundary.Count}");
                            Core.Log($"current building size {_buildingSize}");

                            if (pathFindingCounter < shortPosBoundary.Count && !this._craftPathFound)
                            {
                                this._craftPathFound = Mover(shortPosBoundary[pathFindingCounter]);
                                pathFindingCounter++;
                            }

                            else
                            {
                                Core.Log("Increasing Boundary Size by 0.5");
                                _buildingSize = new Vector2(_buildingSize.x + .5f, _buildingSize.x + .5f);
                                posBoundary   = getPosBoundary(_buildingSize, building2dcenter, buildingy);

                                Core.Log($"Changed building size {_buildingSize}");

                                pathFindingCounter = 0;
                            }
                        }


                        Core.Log($" Distance is { distanceToFinalDestination} between points {PC2D} and {FD2D}. {reachedFinalDestination}");



                        if (distanceToFinalDestination > minimumDistance && reachedFinalDestination == false)
                        {
                            //if (_localPlayerCharacterView.TryFindPath(new ClusterPathfinder(), finalDestination, IsBlockedGathering, out List<Vector3> pathing))
                            //{
                            //    Core.Log("Creating new path from crafting ");
                            //    _craftingPathingRequest = new PositionPathingRequest(_localPlayerCharacterView, finalDestination, pathing, true, true);

                            //}
                            Core.Log($"Still not at destination. {distanceToFinalDestination} away");
                            return;
                        }
                        else
                        {
                            Core.Log($" Distance { distanceToFinalDestination} between points {playerCenter} and {finalDestination}. {reachedFinalDestination}");
                            Core.Log("At final Destination");
                            reachedFinalDestination = true;
                        }



                        //Core.Log($"Target building name {this.craftBuilding.Title.ToLowerInvariant()}");



                        if (this._craftTarget == null)
                        {
                            Core.Log("No Craft Target");
                            return;
                        }


                        //Core.Log("Ready to interact2");

                        if (this._craftTarget is CraftBuildingView craftbuilding)
                        {
                            string name = this._craftTarget.PrefabName;
                            // Core.Log($"Building is {this.craftBuilding.Title}");
                            // Core.Log("Current Target is " + name);
                            GameGui.Instance.MessageBox.CloseImmediately();

                            if (!GameGui.Instance.BuildingUsageAndManagementGui.gameObject.activeInHierarchy)
                            {
                                if (!craftbuilding.IsInUseRange(_localPlayerCharacterView.LocalPlayerCharacter))
                                {
                                    if (stuckTimer < DateTime.Now)
                                    {
                                        isMovingUpdate();
                                    }
                                    else
                                    {
                                        _localPlayerCharacterView.RequestMove(randomSpot);
                                        return;
                                    }

                                    if (!IsMoving)
                                    {
                                        Core.Log("Not Moving. Going To random Spot");
                                        stuckTimer = DateTime.Now + TimeSpan.FromSeconds(2);
                                        randomSpot = new Vector3(UnityEngine.Random.Range(-100f, 100f), 0, UnityEngine.Random.Range(-100f, 100f)) + _localPlayerCharacterView.transform.position;
                                    }
                                    else
                                    {
                                        Core.Log("getcloser");
                                        _localPlayerCharacterView.Interact(craftbuilding);
                                        return;
                                    }
                                }
                                else
                                {
                                    Core.Log($"Close Enough {playerCenter}");
                                }
                            }

                            else
                            {
                                var craftUsage = GameGui.Instance.BuildingUsageAndManagementGui.BuildingUsage;

                                var silverUI = GameGui.Instance.PaySilverDetailGui;

                                //Select the correct craft tab
                                if (!GameGui.Instance.ItemCraftingGui.gameObject.activeInHierarchy)
                                {
                                    BigTabEntry[] BTE     = craftUsage.TabButtons.TabEntries;
                                    string        tabname = craftRec.CraftTab;
                                    foreach (BigTabEntry BT in BTE)
                                    {
                                        string tabn = BT.Tooltip.TextToDisplay.ToLowerInvariant();
                                        craftUsage.OnShowCrafting();
                                        if (tabn.Contains(tabname))
                                        {
                                            Core.Log($"{tabn} contains{BT.Tooltip.TextToDisplay}. Setting tab to display");
                                            BT.OnClickTab();
                                        }
                                    }
                                }

                                if (!craftUsage.CraftItemView.FilterListToggle.value)
                                {
                                    craftUsage.CraftItemView.FilterListToggle.value = true;
                                    return;
                                }

                                if (timeCooldownMax == DateTime.MaxValue)
                                {
                                    timeCooldownMax = DateTime.Now + TimeSpan.FromSeconds(1);
                                }

                                if (timeCooldownMax > DateTime.Now)
                                {
                                    Core.Log($"Time Now {DateTime.Now}");
                                    return;
                                }


                                // Core.Log("Here2");
                                if (silverUI.gameObject.activeInHierarchy)
                                {
                                    Core.Log("[Paying silver costs]");
                                    silverUI.OnPay();
                                    return;
                                }

                                if (craftUsage.gameObject.activeInHierarchy)
                                {
                                    if (_localPlayerCharacterView.IsCrafting())
                                    {
                                        return;
                                    }


                                    //craftUsage.OnShowCrafting();


                                    else
                                    {
                                        KguiCraftItemSlot[] craftSlots = craftUsage.GetComponentsInChildren <KguiCraftItemSlot>();
                                        // Core.Log("Here3");
                                        //Core.Log($"Number of Slots craftitem {comps.Length}");
                                        if (craftUsage.CraftItemView.gameObject.activeInHierarchy)
                                        {
                                            if (craftUsage.CraftItemView.FilterListToggle.value)
                                            {
                                                if (!GameGui.Instance.ItemCraftingGui.gameObject.activeInHierarchy)
                                                {
                                                    Core.Log("Activating CraftingGui");
                                                    KguiCraftItemSlot craftSlot = craftSlots[craftSlots.Length - 1];


                                                    try
                                                    {
                                                        if (craftSlots.Length < 1)
                                                        {
                                                            Core.Log("Cannot craft any items");
                                                            return;
                                                        }

                                                        if (craftSlots.Length > 1)
                                                        {
                                                            for (int i = 0; i < craftSlots.Length; i++)
                                                            {
                                                                string   recipeName;
                                                                string[] subRecipeName;
                                                                string   keyWord;
                                                                string   slotLabelName = craftSlots[i].ItemNameLabel.text.ToLowerInvariant();
                                                                slotLabelName = slotLabelName.Replace(" ", "");
                                                                if (craftRec.AltName == null)
                                                                {
                                                                    recipeName = craftRec.RecipeName;

                                                                    subRecipeName = recipeName.Split('_');
                                                                    keyWord       = subRecipeName[subRecipeName.Length - 1];
                                                                }
                                                                else
                                                                {
                                                                    keyWord = craftRec.AltName;
                                                                }


                                                                // string recipeName = "t3_2h_tool_pick";

                                                                if (slotLabelName.Contains(keyWord))
                                                                {
                                                                    Core.Log($"{slotLabelName} CONTAINED {keyWord} ");
                                                                    craftSlot = craftSlots[i];
                                                                    craftUsage.CraftItemView.OnCraftSlotClicked(craftSlot);
                                                                    // buildingLoaded = false;
                                                                    //timeCooldownMax = DateTime.MaxValue;
                                                                    return;
                                                                }
                                                                else
                                                                {
                                                                    Core.Log($"{slotLabelName} didn't contain {keyWord} ");
                                                                    //return;
                                                                }
                                                                // Core.Log($"{slot.ItemNameLabel.text}");
                                                            }



                                                            return;
                                                        }

                                                        craftUsage.CraftItemView.OnCraftSlotClicked(craftSlot);
                                                        Core.Log("CraftingGui activated");
                                                        return;
                                                    }
                                                    catch (IndexOutOfRangeException)
                                                    {
                                                        Core.Log("You dont have the resources");
                                                        //TODO add trigger to get the resources
                                                    }
                                                    return;
                                                }
                                                else
                                                {
                                                    if (craftSlots.Length > 0 && !_localPlayerCharacterView.IsCrafting())
                                                    {
                                                        var craftUi = GameGui.Instance.ItemCraftingGui.CraftingView;

                                                        if (craftUi.QuantityInput.isActiveAndEnabled)
                                                        {
                                                            craftUi.QuantityInput.value = 1;
                                                        }

                                                        var craftUiType = craftUi.GetType();

                                                        var onCraftButtonmethod = craftUiType.GetMethod("OnCraftButton", BindingFlags.NonPublic | BindingFlags.Instance);

                                                        onCraftButtonmethod.Invoke(craftUi, null);
                                                    }
                                                    else
                                                    {
                                                        Core.Log("Crafting Done. Getting Items");
                                                        ResetCraftingVariables();
                                                        ResetCriticalVariables();

                                                        GameGui.Instance.MessageBox.CloseImmediately();
                                                        GameGui.Instance.ItemCraftingGui.CraftingView.Close();
                                                        _state.Fire(Trigger.GetItems);
                                                        Core.Log("Trigger Change");
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                Core.Log("not filtered");
                                                return;
                                            }
                                        }
                                    }
                                    return;
                                }
                            }
                        }
                    }
                    catch (NullReferenceException)
                    {
                        Core.Log("here 6");
                    }
                }
            }         //_isUIshown = true;

            else
            {
                var pathfinder = new WorldmapPathfinder();
                Core.Log("Finding path to cluser");
                if (pathfinder.TryFindPath(currentWorldCluster, townCluster, StopClusterFunction, out var path, out var pivots))
                {
                    _worldPathingRequest = new WorldPathingRequest(currentWorldCluster, townCluster, path, _skipUnrestrictedPvPZones);
                }
            }
            void reset()
            {
                _buildingSize = Vector2.zero;

                buildingCollider = null;

                building3dcenter = Vector3.zero;

                building2dcenter = Vector3.zero;

                building2d3dcenter = Vector3.zero;

                closestpoint = Vector3.zero;

                CraftBuildingView _craftTarget = null;
            }
        }