Exemplo n.º 1
0
    // Assign types of bricks to every position in the chunk's map
    private void createMapFromScratch()
    {
        int seed = LandscapeManager.getSeed();

        for (int x = 0; x < ChunkWidth; x++)
        {
            for (int z = 0; z < ChunkWidth; z++)
            {
                int height = (int)(Mathf.PerlinNoise(((int)transform.position.x + x + seed) / detailScale, ((int)transform.position.z + z + seed) / detailScale) * heightScale);
                for (int y = 0; y < ChunkHeight; y++)
                {
                    if (y < height)
                    {
                        map[x, y, z] = 0; // space below visible block. Not visible
                    }
                    else if (y == height)
                    {
                        map[x, y, z] = 1; // visible block
                    }
                    else
                    {
                        map[x, y, z] = 2; // space above visible blocks. Not visible
                    }
                }
            }
        }
    }
Exemplo n.º 2
0
        /// <summary>
        /// Called when this instance is updated.
        /// </summary>
        private void Update()
        {
            HotKey();

            if (_client.GetState() == GameState.Playing)
            {
                if (refresh)
                {
                    _client    = GameManager.GetInstance();
                    _world     = ObjectManager.GetInstance();
                    _landscape = _client.GetLandscapeManager();
                    _localPlayerCharacterView = _client.GetLocalPlayerCharacterView();
                    refresh = false;
                }
                if (DateTime.Now < _nextUpdate)
                {
                    return;
                }

                OnUpdate();

                _nextUpdate = DateTime.Now + UpdateDelay;
            }
            else
            {
                refresh = true;
            }
        }
Exemplo n.º 3
0
        public override EntityPosition GetPosition(IDynamicEntity owner)
        {
            var pos = new EntityPosition();

            if (!owner.EntityState.IsBlockPicked)
            {
                return(pos);
            }

            // Get the chunk where the entity will be added and check if another entity is present inside this block
            var workingchunk = LandscapeManager.GetChunkFromBlock(owner.EntityState.NewBlockPosition);

            foreach (var entity in workingchunk.Entities.OfType <IBlockLocationRoot>())
            {
                if (entity.BlockLocationRoot == BlockLocationRoot)
                {
                    // IBlockLocationRoot Entity already present at this location
                    return(pos);
                }
            }

            pos.Position = new Vector3D(owner.EntityState.NewBlockPosition.X + 0.5f,
                                        owner.EntityState.NewBlockPosition.Y,
                                        owner.EntityState.NewBlockPosition.Z + 0.5f);

            pos.Rotation = Quaternion.Identity;
            pos.Valid    = true;

            return(pos);
        }
Exemplo n.º 4
0
    void Start()
    {
        meshFilter   = GetComponent <MeshFilter>();
        meshCollider = GetComponent <MeshCollider>();

        createMapFromScratch();
        StartCoroutine(CreateVisualMesh());

        // Reskin neighbor chunk meshes for boundary cases
        GameObject leftChunk = LandscapeManager.FindChunk(transform.position + new Vector3(-1, 0, 0));

        if (leftChunk != null)
        {
            StartCoroutine(leftChunk.GetComponent <ChunkManager>().CreateVisualMesh());
        }
        GameObject rightChunk = LandscapeManager.FindChunk(transform.position + new Vector3(ChunkWidth, 0, 0));

        if (rightChunk != null)
        {
            StartCoroutine(rightChunk.GetComponent <ChunkManager>().CreateVisualMesh());
        }
        GameObject frontChunk = LandscapeManager.FindChunk(transform.position + new Vector3(0, 0, -1));

        if (frontChunk != null)
        {
            StartCoroutine(frontChunk.GetComponent <ChunkManager>().CreateVisualMesh());
        }
        GameObject backChunk = LandscapeManager.FindChunk(transform.position + new Vector3(0, 0, ChunkWidth));

        if (backChunk != null)
        {
            StartCoroutine(backChunk.GetComponent <ChunkManager>().CreateVisualMesh());
        }
    }
Exemplo n.º 5
0
        public IToolImpact Use(IDynamicEntity owner)
        {
            IToolImpact checkImpact;

            if (!CanDoBlockAction(owner, out checkImpact))
            {
                return(checkImpact);
            }

            var impact = new BlockToolImpact
            {
                SrcBlueprintId = BluePrintId
            };

            var cursor = LandscapeManager.GetCursor(owner.EntityState.PickedBlockPosition);

            if (cursor == null)
            {
                impact.Dropped = true;
                return(impact);
            }

            cursor.OwnerDynamicId = owner.DynamicId;

            var selectedCube = cursor.Read();

            var  treeSystem = new TreeLSystem();
            bool removed    = false;

            foreach (var soul in EntityFactory.LandscapeManager.AroundChunks(owner.Position, 16).SelectMany(c => c.Entities.Enumerate <TreeSoul>()))
            {
                var treeBlueprint = EntityFactory.Config.TreeBluePrintsDico[soul.TreeTypeId];

                if (selectedCube != treeBlueprint.TrunkBlock && selectedCube != treeBlueprint.FoliageBlock)
                {
                    continue;
                }

                var blocks = treeSystem.Generate(soul.TreeRndSeed, BlockHelper.EntityToBlock(soul.Position), treeBlueprint);

                if (blocks.Any(b => b.WorldPosition == owner.EntityState.PickedBlockPosition))
                {
                    cursor.RemoveEntity(soul.GetLink());
                    removed = true;
                    break;
                }
            }

            if (!removed)
            {
                impact.Message = "This is not an alive tree";
                return(impact);
            }

            TakeFromPlayer(owner);
            return(impact);
        }
Exemplo n.º 6
0
    private void Awake()
    {
        m_Type             = ManagerType.GAME_MANAGER;
        m_PlayerManager    = (PlayerManager)ServiceLocator.Instance.GetService(ManagerType.PLAYER_MANAGER);
        m_EnemyManager     = (EnemyManager)ServiceLocator.Instance.GetService(ManagerType.ENEMY_MANAGER);
        m_LandscapeManager = (LandscapeManager)ServiceLocator.Instance.GetService(ManagerType.LANDSCAPE_MANAGER);
        m_GUIManager       = ServiceLocator.Instance.GetService <GUIManager>(ManagerType.GUI_MANAGER);

        m_PlayerManager.OnAllDead += Loose;
    }
Exemplo n.º 7
0
        /// <summary>
        /// Called when this instance is enabled.
        /// </summary>
        private void OnEnable()
        {
            _client    = GameManager.GetInstance();
            _world     = ObjectManager.GetInstance();
            _landscape = _client.GetLandscapeManager();
            _collision = _world.GetCollisionManager();
            _localPlayerCharacterView = _client.GetLocalPlayerCharacterView();
            _nextUpdate = DateTime.Now;

            Camera.onPostRender += OnCameraPostRender;
        }
Exemplo n.º 8
0
 /// <summary>
 /// Stops the server and releases all related resources
 /// </summary>
 public void Dispose()
 {
     Clock.Dispose();
     AreaManager.Dispose();
     ConnectionManager.Dispose();
     LandscapeManager.Dispose();
     Services.Dispose();
     GlobalStateManager.Dispose();
     Scheduler.Dispose();
     EntityManager.Dispose();
 }
Exemplo n.º 9
0
        public IToolImpact Use(IDynamicEntity owner)
        {
            IToolImpact checkImpact;

            if (!CanDoEntityAction(owner, out checkImpact))
            {
                return(checkImpact);
            }

            var impact = new EntityToolImpact();

            if (owner.EntityState.PickedEntityLink.IsDynamic)
            {
                impact.Message = "Only static entities allowed to use";
                return(impact);
            }

            var entity = owner.EntityState.PickedEntityLink.ResolveStatic(LandscapeManager);

            if (entity == null)
            {
                impact.Message = "There is no entity by this link";
                return(impact);
            }

            //Trigger item activation (Make it play sound, open, ...)
            if (entity is IUsableEntity)
            {
                var usable = (IUsableEntity)entity;
                usable.Use();
                impact.Success  = true;
                impact.EntityId = entity.StaticId;
                return(impact);
            }

            var cursor = LandscapeManager.GetCursor(entity.Position);

            if (cursor == null)
            {
                impact.Dropped = true;
                return(impact);
            }

            if (!entity.IsPickable)
            {
                impact.Message = "You need a special tool to pick this item";
                return(impact);
            }

            cursor.OwnerDynamicId = owner.DynamicId;
            return(TakeImpact(owner, entity, impact, cursor, this));
        }
    void Awake()
    {
        //Check if instance already exists
        if (instance == null)
        {
            //if not, set instance to this
            instance = this;
        }
        //If instance already exists and it's not this:
        else if (instance != this)
        {
            //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
            Destroy(gameObject);
        }

        //Get a component reference to the attached LandscapeManager script
        landscapeManager = GetComponent <LandscapeManager>();
        landscapeManager.init();
        monsterManager = GetComponent <MonsterManager>();
        audioSource    = GetComponent <AudioSource>();
    }
Exemplo n.º 11
0
        public IToolImpact Use(IDynamicEntity owner)
        {
            IToolImpact checkImpact;

            if (!CanDoEntityAction(owner, out checkImpact))
            {
                return(checkImpact);
            }

            var impact = new EntityToolImpact {
                SrcBlueprintId = BluePrintId
            };

            if (owner.EntityState.PickedEntityLink.IsDynamic)
            {
                impact.Message = "Only static entities allowed to use";
                return(impact);
            }

            var entity = owner.EntityState.PickedEntityLink.ResolveStatic(LandscapeManager);

            if (entity == null)
            {
                impact.Message = "Unable to resolve the link";
                return(impact);
            }

            var cursor = LandscapeManager.GetCursor(entity.Position);

            if (cursor == null)
            {
                impact.Dropped = true;
                return(impact);
            }

            cursor.OwnerDynamicId = owner.DynamicId;
            return(HandTool.TakeImpact(owner, entity, impact, cursor, this));
        }
Exemplo n.º 12
0
    public byte GetByte(int x, int y, int z)
    {
        if (y < 0)
        {
            return(0);
        }
        else if (y >= ChunkHeight)
        {
            return(2);
        }

        if ((x < 0) || (z < 0) || (x >= ChunkWidth) || (z >= ChunkWidth))
        {
            Vector3    worldPos = new Vector3(x, y, z) + transform.position;
            GameObject chunk    = LandscapeManager.FindChunk(worldPos);
            if (chunk == null)
            {
                return(1);
            }

            return(chunk.GetComponent <ChunkManager>().GetByte(worldPos));
        }
        return(map[x, y, z]);
    }
Exemplo n.º 13
0
        private IToolImpact BlockHit(IDynamicEntity owner)
        {
            var impact = new BlockToolImpact {
                SrcBlueprintId = BluePrintId,
                Position       = owner.EntityState.PickedBlockPosition
            };

            var cursor = LandscapeManager.GetCursor(owner.EntityState.PickedBlockPosition);

            if (cursor == null)
            {
                //Impossible to find chunk, chunk not existing, event dropped
                impact.Message = "Block not existing, event dropped";
                impact.Dropped = true;
                return(impact);
            }
            cursor.OwnerDynamicId = owner.DynamicId;

            if (cursor.PeekProfile().Indestructible)
            {
                impact.Message = "Indestrutible cube, cannot be removed !";
                return(impact);
            }

            DamageTag damage;

            var cube = cursor.Read(out damage);

            if (cube != WorldConfiguration.CubeId.Air)
            {
                impact.CubeId = cube;
                var profile  = cursor.PeekProfile();
                var hardness = profile.Hardness;

                if (damage == null)
                {
                    damage = new DamageTag {
                        Strength      = (int)hardness,
                        TotalStrength = (int)hardness
                    };
                }

                var toolBlockDamage = Damage;

                if (SpecialDamages != null)
                {
                    var index = SpecialDamages.FindIndex(cd => cd.CubeId == cube);

                    if (index != -1)
                    {
                        toolBlockDamage = SpecialDamages[index].Damage;
                    }
                }

                damage.Strength -= toolBlockDamage;

                if (toolBlockDamage > 0 && SoundEngine != null)
                {
                    if (profile.HitSounds.Count > 0)
                    {
                        var random = new Random();
                        var sound  = profile.HitSounds[random.Next(0, profile.HitSounds.Count)];
                        SoundEngine.StartPlay3D(sound, owner.EntityState.PickedBlockPosition + new Vector3(0.5f));
                    }
                }

                if (damage.Strength <= 0)
                {
                    var chunk = LandscapeManager.GetChunkFromBlock(owner.EntityState.PickedBlockPosition);
                    if (chunk == null)
                    {
                        //Impossible to find chunk, chunk not existing, event dropped
                        impact.Message = "Chunk is not existing, event dropped";
                        impact.Dropped = true;
                        return(impact);
                    }
                    chunk.Entities.RemoveAll <BlockLinkedItem>(e => e.Linked && e.LinkedCube == owner.EntityState.PickedBlockPosition, owner.DynamicId);
                    cursor.Write(WorldConfiguration.CubeId.Air);

                    #region TreeSoul remove logic
                    foreach (var treeSoul in EntityFactory.LandscapeManager.AroundEntities(owner.EntityState.PickedBlockPosition, 16).OfType <TreeSoul>())
                    {
                        var treeBp = EntityFactory.Config.TreeBluePrintsDico[treeSoul.TreeTypeId];

                        if (cube != treeBp.FoliageBlock && cube != treeBp.TrunkBlock)
                        {
                            continue;
                        }

                        var treeLSystem = new TreeLSystem();

                        var treeBlocks = treeLSystem.Generate(treeSoul.TreeRndSeed, (Vector3I)treeSoul.Position, treeBp);

                        // did we remove the block of the tree?
                        if (treeBlocks.Exists(b => b.WorldPosition == owner.EntityState.PickedBlockPosition))
                        {
                            treeSoul.IsDamaged = true;

                            // count removed trunk blocks
                            var totalTrunks = treeBlocks.Count(b => b.BlockId == treeBp.TrunkBlock);

                            var existsTrunks = treeBlocks.Count(b =>
                            {
                                if (b.BlockId == treeBp.TrunkBlock)
                                {
                                    cursor.GlobalPosition = b.WorldPosition;
                                    return(cursor.Read() == treeBp.TrunkBlock);
                                }
                                return(false);
                            });

                            if (existsTrunks < totalTrunks / 2)
                            {
                                treeSoul.IsDying = true;
                            }
                        }
                    }
                    #endregion

                    if (SoundEngine != null && EntityFactory.Config.ResourceTake != null)
                    {
                        SoundEngine.StartPlay3D(EntityFactory.Config.ResourceTake, owner.EntityState.PickedBlockPosition + new Vector3(0.5f));
                    }

                    var charEntity = owner as CharacterEntity;
                    if (charEntity == null)
                    {
                        impact.Message = "Charater entity is expected";
                        return(impact);
                    }

                    var putItems = new List <KeyValuePair <IItem, int> >();
                    putItems.Add(new KeyValuePair <IItem, int>((IItem)EntityFactory.CreateFromBluePrint(cube), 1));

                    if (profile.Transformations != null)
                    {
                        var random = new FastRandom(owner.EntityState.PickedEntityPosition.GetHashCode() ^ owner.EntityState.Entropy);
                        foreach (var itemTransformation in profile.Transformations)
                        {
                            if (random.NextDouble() < itemTransformation.TransformChance)
                            {
                                // don't give the block
                                putItems.Clear();
                                foreach (var slot in itemTransformation.GeneratedItems)
                                {
                                    putItems.Add(new KeyValuePair <IItem, int>((Item)EntityFactory.CreateFromBluePrint(slot.BlueprintId), slot.Count));
                                }
                                break;
                            }
                        }
                    }

                    // in case of infinite resources we will not add more than 1 block entity
                    var existingSlot = charEntity.FindSlot(s => s.Item.BluePrintId == cube);

                    if (!EntityFactory.Config.IsInfiniteResources || existingSlot == null)
                    {
                        if (!charEntity.Inventory.PutMany(putItems))
                        {
                            impact.Message = "Can't put the item(s) to inventory";
                        }
                    }

                    impact.CubeId = WorldConfiguration.CubeId.Air;
                }
                else if (damage.Strength >= hardness)
                {
                    cursor.Write(cube);
                }
                else
                {
                    cursor.Write(cube, damage);
                }

                impact.Success = true;
                return(impact);
            }

            impact.Message = "Cannot hit air block";
            return(impact);
        }
Exemplo n.º 14
0
        public void Continue()
        {
            if (_timeout > DateTime.Now)
            {
                // Core.Log($"WORLD PATHING REQUEST TIMED OUT Current State {_state}");
                return;
            }
            switch (_state.State)
            {
            case State.Pause:
            {
                var player = _client.GetLocalPlayerCharacterView();
                if (DateTime.Now > _stuckTimer)
                {
                    _state.Fire(Trigger.ReachedDestination);
                }


                //Core.Log($"Moving to RandomSpot {_randomSpot}");
                player.RequestMove(_randomSpot);

                break;
            }


            case State.Start:
            {
                if (_path.Count > 0)
                {
                    _state.Fire(Trigger.ApproachDestination);
                }
                else
                {
                    _state.Fire(Trigger.ReachedDestination);
                }

                break;
            }

            case State.Running:
            {
                var nextCluster    = _path[0];
                var currentCluster = _world.GetCurrentCluster();
                var player         = _client.GetLocalPlayerCharacterView();
                isMovingUpdate();
                //Core.Log($"{IsMoving}");
                if (!IsMoving)
                {
                    Core.Log("World pathing Request not moving");
                    _randomSpot = new Vector3(UnityEngine.Random.Range(-100f, 100f), 0, UnityEngine.Random.Range(-100f, 100f)) + player.transform.position;
                    _stuckTimer = DateTime.Now + TimeSpan.FromSeconds(2);
                    _state.Fire(Trigger.Stuck);
                    break;
                }

                // Core.Log("Beggining run world pathing request");
                if (currentCluster.GetIdent() != nextCluster.GetIdent())
                {
                    //Core.Log("Indent Not in next Cluster");
                    if (_exitPathingRequest != null)
                    {
                        if (_exitPathingRequest.IsRunning)
                        {
                            // Core.Log("Exit Pathing Request Running");
                            _exitPathingRequest.Continue();
                        }
                        else
                        {
                            //Core.Log("Exit Pathing Request Timed Out");
                            _timeout            = DateTime.Now + TimeSpan.FromSeconds(10);
                            _exitPathingRequest = null;
                        }

                        break;
                    }


                    player = _client.GetLocalPlayerCharacterView();
                    var exits = currentCluster.GetExits();


                    var exit         = exits.FirstOrDefault(e => e.GetDestination().GetIdent() == nextCluster.GetIdent());
                    var exitLocation = exit.GetPosition();

                    var destination = new Vector3(exitLocation.GetX(), 0, exitLocation.GetY());

                    var exitCollider = Physics.OverlapCapsule(destination - HeightDifference, destination + HeightDifference, 2f).FirstOrDefault(c => c.name.ToLowerInvariant().Equals("exit") || c.name.ToLowerInvariant().Contains("entrance"));
                    _destinationPosition = exitCollider?.transform?.position;
                    _destinationExtends  = exitCollider?.GetColliderExtents();
                    if (_destinationPosition.HasValue)
                    {
                        var temp = _destinationPosition.Value;
                        temp.y = 0;
                        _destinationPosition = temp;
                    }

                    _landscape = _client.GetLandscapeManager();
                    if (player.TryFindPath(new ClusterPathfinder(), destination, IsBlockedWithExitCheck, out List <Vector3> pathing))
                    {
                        // Core.Log("Beginning new position pathing request from world pathing request");
                        _exitPathingRequest = new PositionPathingRequest(_client.GetLocalPlayerCharacterView(), destination, pathing, false);
                    }
                }
                else
                {
                    //Core.Log("Path Point Removed");
                    _path.RemoveAt(0);
                    _exitPathingRequest = null;
                }

                if (_path.Count > 0)
                {
                    break;
                }



                _state.Fire(Trigger.ReachedDestination);
                break;
            }
            }
        }
Exemplo n.º 15
0
        public void Continue()
        {
            if (_timeout > DateTime.Now)
            {
                return;
            }

            switch (_state.State)
            {
            case State.Start:
            {
                if (_path.Count > 0)
                {
                    _state.Fire(Trigger.ApproachDestination);
                }
                else
                {
                    _state.Fire(Trigger.ReachedDestination);
                }

                break;
            }

            case State.Running:
            {
                var nextCluster    = _path[0];
                var currentCluster = _world.GetCurrentCluster();

                if (currentCluster.GetIdent() != nextCluster.GetIdent())
                {
                    if (_exitPathingRequest != null)
                    {
                        if (_exitPathingRequest.IsRunning)
                        {
                            _exitPathingRequest.Continue();
                        }
                        else
                        {
                            _timeout            = DateTime.Now + TimeSpan.FromSeconds(5);
                            _exitPathingRequest = null;
                        }

                        break;
                    }

                    var player = _client.GetLocalPlayerCharacterView();
                    var exits  = currentCluster.GetExits();

                    var exit         = exits.FirstOrDefault(e => e.GetDestination().GetIdent() == nextCluster.GetIdent());
                    var exitLocation = exit.GetPosition();

                    var destination = new Vector3(exitLocation.GetX(), 0, exitLocation.GetY());

                    var exitCollider = Physics.OverlapCapsule(destination - HeightDifference, destination + HeightDifference, 2f).FirstOrDefault(c => c.name.ToLowerInvariant().Equals("exit") || c.name.ToLowerInvariant().Contains("entrance"));
                    _destinationPosition = exitCollider?.transform?.position;
                    _destinationExtends  = exitCollider?.GetColliderExtents();
                    if (_destinationPosition.HasValue)
                    {
                        var temp = _destinationPosition.Value;
                        temp.y = 0;
                        _destinationPosition = temp;
                    }

                    _landscape = _client.GetLandscapeManager();
                    if (player.TryFindPath(new ClusterPathfinder(), destination, IsBlockedWithExitCheck, out List <Vector3> pathing))
                    {
                        _exitPathingRequest = new PositionPathingRequest(_client.GetLocalPlayerCharacterView(), destination, pathing, false);
                    }
                }
                else
                {
                    _path.RemoveAt(0);
                    _exitPathingRequest = null;
                }

                if (_path.Count > 0)
                {
                    break;
                }

                _state.Fire(Trigger.ReachedDestination);
                break;
            }
            }
        }
Exemplo n.º 16
0
 void Awake()
 {
     instance = this;
 }
Exemplo n.º 17
0
        public void Continue()
        {
            switch (_state.State)
            {
            case State.Pause:
            {
                var previousNode           = _completedpath[_completedpath.Count - 1];
                var playerPosV2            = new Vector2(_player.transform.position.x, _player.transform.position.z);
                var previousNodeV2         = new Vector2(previousNode.x, previousNode.z);
                var target2D               = new Vector2(_target.x, _target.z);
                var distanceToTarget       = Vector2.Distance(playerPosV2, target2D);
                var distancePreviousToNode = (playerPosV2 - previousNodeV2).sqrMagnitude;
                var minimumDistance        = 2f;
                _landscape = _client.GetLandscapeManager();

                Core.Log("Paused");
                if (DateTime.Now < _notMovingTimer)
                {
                    Core.Log("Checking for movement restart");
                    isMovingUpdate();
                    if (IsMoving)
                    {
                        Core.Log("MOVING AGAIN");
                        _state.Fire(Trigger.ApproachTarget);
                        break;
                    }

                    break;
                }

                if (distanceToTarget < 40 && _allowMinDistCheck)
                {
                    Core.Log($"The target {target2D} is {distanceToTarget} from this position {playerPosV2}");
                    Core.Log("@ target");
                    _state.Fire(Trigger.ReachedTarget);
                    break;
                }



                if (DateTime.Now > _pauseTimer)
                {
                    _state.Fire(Trigger.ReachedTarget);
                    break;
                }



                if (_completedpath.Count < 1)
                {
                    Vector3 randomSpot = new Vector3(UnityEngine.Random.Range(-100f, 100f), 0, UnityEngine.Random.Range(-100f, 100f)) + _player.transform.position;
                    _completedpath.Add(randomSpot);
                    break;
                }

                if (_path.Count < 2)
                {
                    _player.RequestMove(_player.transform.position + new Vector3(UnityEngine.Random.Range(-100f, 100f), 0, UnityEngine.Random.Range(-100f, 100f)));
                }


                if (distancePreviousToNode < minimumDistance)
                {
                    if (_player.TryFindPath(new ClusterPathfinder(), _target, IsBlockedWithExitCheck, out List <Vector3> pathing))
                    {
                        Core.Log("Reached Previous Node and found path");

                        _path = pathing;
                        _state.Fire(Trigger.Restart);
                        break;
                    }
                    else
                    {
                        Core.Log("Reached Previous Node and didnt find path. Moving to next previous node");
                        _completedpath.RemoveAt(_completedpath.Count - 1);

                        _pauseTimer = DateTime.Now + TimeSpan.FromSeconds(15);
                    }
                }
                else
                {
                    _player.RequestMove(previousNode);
                }



                break;
            }

            case State.Start:
            {
                Core.Log($"Position pathing request path count {_path.Count}");
                if (_path.Count > 0)
                {
                    _state.Fire(Trigger.ApproachTarget);
                }
                else
                {
                    _state.Fire(Trigger.ReachedTarget);
                }

                break;
            }

            case State.Running:
            {
                //Early exit if player is null.
                if (_player == null)
                {
                    _state.Fire(Trigger.ReachedTarget);
                    break;
                }

                isMovingUpdate();
                // Core.Log($"Position pathing request is Moving {IsMoving} at { _player.transform.position}");
                if (!IsMoving)
                {
                    _notMovingTimer = DateTime.Now + TimeSpan.FromSeconds(1.5);
                    _pauseTimer     = DateTime.Now + TimeSpan.FromSeconds(15);
                    Core.Log($"Stuck Position Pathing Request During Running. State is {_state}");
                    _state.Fire(Trigger.Stuck);
                    Core.Log($"Position Pathing Request During Running 2. State is {_state}");
                }


                var currentNode     = _path[0];
                var minimumDistance = 3f;

                if (_path.Count < 2 && _useCollider)
                {
                    minimumDistance = _player.GetColliderExtents();

                    var directionToPlayer = (_player.transform.position - _target).normalized;
                    var bufferDistance    = directionToPlayer * minimumDistance;

                    currentNode = _target + bufferDistance;
                }

                var playerPosV2   = new Vector2(_player.transform.position.x, _player.transform.position.z);
                var currentNodeV2 = new Vector2(currentNode.x, currentNode.z);

                var distanceToNode = (playerPosV2 - currentNodeV2).sqrMagnitude;

                if (distanceToNode < minimumDistance)
                {
                    _completedpath.Add(_path[0]);
                    _path.RemoveAt(0);
                }
                else
                {
                    _player.RequestMove(currentNode);
                }

                if (_path.Count > 0)
                {
                    break;
                }

                _state.Fire(Trigger.ReachedTarget);
                break;
            }
            }
        }
Exemplo n.º 18
0
        public override EntityPosition GetPosition(IDynamicEntity owner)
        {
            var pos = new EntityPosition();

            if (!AllowFreeMount && !owner.EntityState.IsBlockPicked)
            {
                return(pos);
            }

            if (!MountPoint.HasFlag(BlockFace.Top) && owner.EntityState.PickPointNormal.Y == 1)
            {
                return(pos);
            }

            if (!MountPoint.HasFlag(BlockFace.Bottom) && owner.EntityState.PickPointNormal.Y == -1)
            {
                return(pos);
            }

            if (!MountPoint.HasFlag(BlockFace.Sides) && (owner.EntityState.PickPointNormal.X != 0 || owner.EntityState.PickPointNormal.Z != 0))
            {
                return(pos);
            }

            if (BlockEmptyRequired && owner.EntityState.IsBlockPicked)
            {
                //Get the chunk where the entity will be added and check if another entity is not present at the destination root block !
                var workingchunk = LandscapeManager.GetChunkFromBlock(owner.EntityState.PickedBlockPosition);

                if (workingchunk == null)
                {
                    return(pos);
                }

                foreach (var entity in workingchunk.Entities.OfType <BlockLinkedItem>().Where(x => x.Linked && x.LinkedCube == owner.EntityState.PickedBlockPosition))
                {
                    if (entity.BlockLocationRoot == owner.EntityState.NewBlockPosition && entity.LinkedCube == owner.EntityState.PickedBlockPosition)
                    {
                        //CubePlaced Entity already present at this location
                        return(pos);
                    }
                }
            }

            // locate the entity
            if (owner.EntityState.PickPointNormal.Y == 1) // = Put on TOP
            {
                if (BlockFaceCentered)
                {
                    var newBlockPos = owner.EntityState.IsBlockPicked ? owner.EntityState.NewBlockPosition : owner.EntityState.PickPoint.ToCubePosition();
                    pos.Position = new Vector3D(
                        newBlockPos + new Vector3(0.5f - (float)owner.EntityState.PickPointNormal.X / 2,
                                                  owner.EntityState.PickPoint.Y % 1,
                                                  0.5f - (float)owner.EntityState.PickPointNormal.Z / 2)
                        );
                }
                else
                {
                    pos.Position = new Vector3D(owner.EntityState.PickPoint);
                }
            }
            else if (owner.EntityState.PickPointNormal.Y == -1) //PUT on cube Bottom = (Ceiling)
            {
                pos.Position    = new Vector3D(owner.EntityState.PickPoint);
                pos.Position.Y -= DefaultSize.Y;
            }
            else //Put on a side
            {
                if (BlockFaceCentered)
                {
                    var newBlockPos = owner.EntityState.IsBlockPicked ? owner.EntityState.NewBlockPosition : owner.EntityState.PickPoint.ToCubePosition();
                    pos.Position = new Vector3D(
                        newBlockPos + new Vector3(0.5f - (float)owner.EntityState.PickPointNormal.X / 2,
                                                  0.5f,
                                                  0.5f - (float)owner.EntityState.PickPointNormal.Z / 2)
                        );
                }
                else
                {
                    pos.Position = new Vector3D(owner.EntityState.PickPoint);
                }

                pos.Position += new Vector3D(owner.EntityState.PickPointNormal.X == -1 ? -0.01 : 0,
                                             0,
                                             owner.EntityState.PickPointNormal.Z == -1 ? -0.01 : 0);


                var slope = 0d;

                if (owner.EntityState.PickPointNormal.X == -1)
                {
                    slope = -Math.PI / 2;
                }
                if (owner.EntityState.PickPointNormal.X == 1)
                {
                    slope = Math.PI / 2;                                             // ok
                }
                if (owner.EntityState.PickPointNormal.Z == -1)
                {
                    slope = Math.PI;                                             // ok
                }
                if (owner.EntityState.PickPointNormal.Z == 1)
                {
                    slope = 0;
                }

                pos.Rotation = Quaternion.RotationAxis(new Vector3(0, 1, 0), (float)slope);
            }

            pos.Valid = true;

            return(pos);
        }
Exemplo n.º 19
0
        public IToolImpact BlockImpact(IDynamicEntity owner, bool runOnServer = false)
        {
            var entity = owner;
            var impact = new BlockToolImpact {
                SrcBlueprintId = BluePrintId
            };

            if (entity.EntityState.IsBlockPicked)
            {
                //Do Dynamic entity collision testing (Cannot place a block if a dynamic entity intersect.
                var blockBB = new BoundingBox(entity.EntityState.NewBlockPosition, entity.EntityState.NewBlockPosition + Vector3.One);
                foreach (var dynEntity in EntityFactory.DynamicEntityManager.EnumerateAround(entity.EntityState.NewBlockPosition))
                {
                    var dynBB = new BoundingBox(dynEntity.Position.AsVector3(), dynEntity.Position.AsVector3() + dynEntity.DefaultSize);
                    if (blockBB.Intersects(ref dynBB))
                    {
                        impact.Message = "Cannot place a block where someone is standing";
                        return(impact);
                    }
                }

                // Get the chunk where the entity will be added and check if another block static entity is present inside this block
                var workingchunk = LandscapeManager.GetChunkFromBlock(owner.EntityState.NewBlockPosition);
                if (workingchunk == null)
                {
                    //Impossible to find chunk, chunk not existing, event dropped
                    impact.Message = "Chunk is not existing, event dropped";
                    impact.Dropped = true;
                    return(impact);
                }
                foreach (var staticEntity in workingchunk.Entities.OfType <IBlockLocationRoot>())
                {
                    if (staticEntity.BlockLocationRoot == entity.EntityState.NewBlockPosition)
                    {
                        impact.Message = "There is something there, remove it first " + staticEntity.BlockLocationRoot;
                        return(impact);
                    }
                }

                //Add new block
                var cursor = LandscapeManager.GetCursor(entity.EntityState.NewBlockPosition);
                if (cursor == null)
                {
                    //Impossible to find chunk, chunk not existing, event dropped
                    impact.Message = "Block not existing, event dropped";
                    impact.Dropped = true;
                    return(impact);
                }
                if (cursor.Read() == WorldConfiguration.CubeId.Air)
                {
                    if (!EntityFactory.Config.IsInfiniteResources)
                    {
                        var charEntity = owner as CharacterEntity;
                        if (charEntity == null)
                        {
                            impact.Message = "Character entity is expected";
                            return(impact);
                        }

                        var slot = charEntity.Inventory.FirstOrDefault(s => s.Item.StackType == StackType);

                        if (slot == null)
                        {
                            // we have no more items in the inventory, remove from the hand
                            slot           = charEntity.Equipment[EquipmentSlotType.Hand];
                            impact.Success = charEntity.Equipment.TakeItem(slot.GridPosition);
                        }
                        else
                        {
                            impact.Success = charEntity.Inventory.TakeItem(slot.GridPosition);
                        }

                        if (!impact.Success)
                        {
                            impact.Message = "Unable to take an item from the inventory";
                            return(impact);
                        }
                    }

                    cursor.Write(CubeId);
                    impact.Success = true;
                    impact.CubeId  = CubeId;

                    if (SoundEngine != null && EntityFactory.Config.ResourcePut != null)
                    {
                        SoundEngine.StartPlay3D(EntityFactory.Config.ResourcePut, entity.EntityState.NewBlockPosition + new Vector3(0.5f));
                    }

                    return(impact);
                }
            }
            impact.Message = "Pick a cube to use this tool";
            return(impact);
        }
Exemplo n.º 20
0
        public override EntityPosition GetPosition(IDynamicEntity owner)
        {
            var pos = new EntityPosition();

            Vector3I?newBlockPos = null;

            var playerRotation = owner.HeadRotation.GetLookAtVector();

            if (owner.EntityState.IsBlockPicked)
            {
                newBlockPos = owner.EntityState.NewBlockPosition;
            }
            else if (owner.EntityState.IsEntityPicked && owner.EntityState.PickedEntityLink.IsStatic)
            {
                var entity = owner.EntityState.PickedEntityLink.ResolveStatic(LandscapeManager);

                if (entity is BlockItem)
                {
                    newBlockPos = owner.EntityState.PickedEntityPosition.ToCubePosition();

                    var rotation  = entity.Rotation;
                    var normal    = Vector3.TransformNormal(owner.EntityState.PickPointNormal, Matrix.RotationQuaternion(rotation));
                    var converted = new Vector3I((int)Math.Round(normal.X, MidpointRounding.ToEven), (int)Math.Round(normal.Y, MidpointRounding.ToEven), (int)Math.Round(normal.Z, MidpointRounding.ToEven));
                    newBlockPos += converted;
                }
            }

            if (newBlockPos == null)
            {
                return(pos);
            }

            var cursor = LandscapeManager.GetCursor(newBlockPos.Value);

            if (cursor == null || cursor.Read() != WorldConfiguration.CubeId.Air || LandscapeManager.GetChunkFromBlock(newBlockPos.Value).Entities.OfType <BlockItem>().Any(i => i.BlockLocationRoot == newBlockPos))
            {
                return(pos);
            }

            // locate the entity, set translation in World space
            pos.Position = new Vector3D(newBlockPos.Value.X + 0.5f,
                                        newBlockPos.Value.Y,
                                        newBlockPos.Value.Z + 0.5f);

            //Set Orientation
            double entityRotation;

            if (Math.Abs(playerRotation.Z) >= Math.Abs(playerRotation.X))
            {
                if (playerRotation.Z < 0)
                {
                    entityRotation  = MathHelper.Pi;
                    pos.Orientation = ItemOrientation.North;
                }
                else
                {
                    entityRotation  = 0;
                    pos.Orientation = ItemOrientation.South;
                }
            }
            else
            {
                if (playerRotation.X < 0)
                {
                    entityRotation  = MathHelper.PiOver2;
                    pos.Orientation = ItemOrientation.East;
                }
                else
                {
                    entityRotation  = -MathHelper.PiOver2;
                    pos.Orientation = ItemOrientation.West;
                }
            }

            //Specific Item Rotation for this instance
            pos.Rotation = Quaternion.RotationAxis(new Vector3(0, 1, 0), (float)entityRotation);
            pos.Valid    = true;

            return(pos);
        }