Esempio n. 1
0
        public void AddEnemy(EnemyEntity enemy)
        {
            enemy.IsValid = true;

            ActiveEntities.Add(enemy);
            Enemies.Add(enemy);
        }
Esempio n. 2
0
        public void Remove(Entity entity)
        {
            Debug.Assert(entity != null, "Entity must not be null.");
            //Debug.Assert(entity.entityManager == this, "");  // TODO

            ActiveEntities.Set(entity.Id, null);
            RemoveComponentsOfEntity(entity);
#if DEBUG
            --EntitiesRequestedCount;

            if (TotalRemoved < long.MaxValue)
            {
                ++TotalRemoved;
            }
#endif
            if (_removedAndAvailable.Count < RemovedEntitiesRetention)
            {
                _removedAndAvailable.Add(entity);
            }
            else
            {
                _identifierPool.Add(entity.Id);
            }

            RemovedEntityEvent?.Invoke(entity);

            _uniqueIdToEntities.Remove(entity.UniqueId);
        }
Esempio n. 3
0
        private void CleanupDeletedEntities()
        {
            if (QueuedForDisposal.Count > 0)
            {
                foreach (CharacterEntity entity in QueuedForDisposal)
                {
                    entity.DynamicBody.Enabled = false;
                    entity.DynamicBody.Dispose();
                    ActiveEntities.Remove(entity);

                    EnemyEntity enemy = entity as EnemyEntity;
                    if (enemy != null)
                    {
                        Enemies.Remove(enemy);
                    }
                    else
                    {
                        EggEntity egg = entity as EggEntity;
                        if (egg != null)
                        {
                            Eggs.Remove(egg);
                        }
                    }
                }
                QueuedForDisposal.Clear();
            }
        }
Esempio n. 4
0
        public Entity Create(long?uniqueid = null)
        {
            var id = uniqueid ?? BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0);

            var result = _removedAndAvailable.RemoveLast();

            if (result == null)
            {
                var entityId = _identifierPool.IsEmpty
                    ? _nextAvailableId++
                    : _identifierPool.RemoveLast();

                result = new Entity(_entityWorld, entityId);
            }
            else
            {
                result.Reset();
            }

            result.UniqueId = id;
            _uniqueIdToEntities[result.UniqueId] = result;
            ActiveEntities.Set(result.Id, result);
#if DEBUG
            ++EntitiesRequestedCount;

            if (TotalCreated < long.MaxValue)
            {
                ++TotalCreated;
            }
#endif
            AddedEntityEvent?.Invoke(result);

            return(result);
        }
Esempio n. 5
0
 private void CreateQueuedEntities()
 {
     if (QueuedForCreation.Count > 0)
     {
         foreach (CharacterEntity entity in QueuedForCreation)
         {
             ActiveEntities.Add(entity);
         }
     }
     QueuedForCreation.Clear();
 }
Esempio n. 6
0
        private void OnMouseClicked(object?sender, MouseEventArgs e)
        {
            if (skipNextMouseClicked)
            {
                skipNextMouseClicked = false;
                return;
            }

            sharedState.SelectedEntity = ActiveEntities.Cast <int?>()
                                         .FirstOrDefault(entity => IsEntityClicked(entity !.Value, e.Position));
        }
Esempio n. 7
0
    public override void End()
    {
        if (sharedContext.IsPaused && sharedContext.IsSyncing && ActiveEntities.All(id => {
            var entity = GetEntity(id);
            return(entity.Get <PlayerState>().IsLocal || entity.Get <PlayerInput>().IsUpToDate());
        }))
        {
            sharedContext.IsPaused  = false;
            sharedContext.IsSyncing = false;
        }

        previousMousePosition = Mouse.GetState().Position;
    }
Esempio n. 8
0
        public void InitialiseLevel()
        {
            Texture2D backgroundTexture = Content.Load <Texture2D>("background");

            _bgSprite1 = new SpriteEntity(backgroundTexture, ScreenCenter);
            base.ActiveEntities.Add(_bgSprite1);
            _bgSprite2 = new SpriteEntity(backgroundTexture, new Vector2(ScreenCenter.X + ScreenSizeDefault.X, ScreenCenter.Y));
            base.ActiveEntities.Add(_bgSprite2);


            Player = new PlayerEntity(this, Clips["player"], ScreenCenter);
            ActiveEntities.Add(Player);
        }
Esempio n. 9
0
		void OnDrawGizmos()
		{
			var sceneCameraTransform = SceneView.GetAllSceneCameras()[0].transform;

			EnsurePreviewObjectExists(PrimitiveType.Quad, ref previewRect);

			foreach (EntityData e in ActiveEntities
				.Where(x => x.Material)
				.OrderBy(x => Vector3.Dot(sceneCameraTransform.position - x.Position, sceneCameraTransform.forward)))
			{
				Color color = e.Material.Albedo ? e.Material.Albedo.MainColor : Color.white;
				if (e.Material.Emission)
					color += e.Material.Emission.MainColor;

				switch (e.Material.Type)
				{
					case MaterialType.Dielectric: color = color.GetAlphaReplaced(0.5f); break;
					case MaterialType.ProbabilisticVolume: color = color.GetAlphaReplaced(max(e.Material.Density, 0.5f)); break;
					default: color = color.GetAlphaReplaced(1); break;
				}

				Gizmos.color = color;

				if (e.Selected)
					Gizmos.color = Color.yellow;

				switch (e.Type)
				{
					case EntityType.Rect:
						Gizmos.matrix = Matrix4x4.TRS(e.Position, e.Rotation, float3(e.RectData.Size, 1));
						Gizmos.DrawMesh(previewRect.sharedMesh, 0);
						Gizmos.matrix = Matrix4x4.identity;
						break;

					case EntityType.Sphere:
						Gizmos.DrawSphere(e.Position, e.SphereData.Radius);
						break;

					case EntityType.Box:
						Gizmos.matrix = Matrix4x4.TRS(e.Position, e.Rotation, Vector3.one);
						Gizmos.DrawCube(Vector3.zero, e.BoxData.Size);
						Gizmos.matrix = Matrix4x4.identity;
						break;
				}
			}

#if BVH
			if (previewBvh && bvhNodeBuffer.IsCreated)
			{
				float silverRatio = (sqrt(5.0f) - 1.0f) / 2.0f;
				(AxisAlignedBoundingBox _, int Depth)[] subBounds = BvhRoot->GetAllSubBounds().ToArray();
Esempio n. 10
0
        public Bag <Entity> GetEntities(Aspect aspect)
        {
            var entitiesBag = new Bag <Entity>();

            for (int index = 0; index < ActiveEntities.Count; ++index)
            {
                var entity = ActiveEntities.Get(index);
                if (entity != null && aspect.Interests(entity))
                {
                    entitiesBag.Add(entity);
                }
            }

            return(entitiesBag);
        }
        public override void Update(GameTime gameTime)
        {
            _bullets.AddRange(ActiveEntities.Where(e => _bulletMapper.Has(e)));
            _aliens.AddRange(ActiveEntities.Where(e => _alienMapper.Has(e)));

            foreach (var alien in _aliens)
            {
                var alienSprite    = _animatedSpriteMapper.Get(alien);
                var alienTransform = _transformMapper.Get(alien);
                var alienRect      = alienSprite.GetBoundingRectangle(alienTransform);
                var destroyAlien   = false;
                foreach (var bullet in _bullets)
                {
                    if (_bulletsToDestroy.Contains(bullet))
                    {
                        continue;
                    }
                    var bulletSprite    = _spriteMapper.Get(bullet);
                    var bulletTransform = _transformMapper.Get(bullet);
                    var bulletRect      = bulletSprite.GetBoundingRectangle(bulletTransform);

                    if (bulletRect.Intersects(alienRect))
                    {
                        destroyAlien = true;
                        _bulletsToDestroy.Add(bullet);
                        break;
                    }
                }

                if (destroyAlien)
                {
                    DestroyEntity(alien);
                }
            }

            foreach (var destroy in _bulletsToDestroy)
            {
                DestroyEntity(destroy);
            }

            _bulletsToDestroy.Clear();
            _bullets.Clear();
            _aliens.Clear();
        }
Esempio n. 12
0
        /// <summary>
        /// Helper for tests to create snapshots with entities within more collections than just
        /// AddedEntities.
        /// </summary>
        internal IEntity CreateEntity(EntityAddTarget target, string prettyName = "")
        {
            ContentEntity added = new ContentEntity(EntityIdGenerator.Next(), prettyName);

            if (target == EntityAddTarget.Added)
            {
                AddedEntities.Add(added);
            }
            else if (target == EntityAddTarget.Active)
            {
                ActiveEntities.Add(added);
            }
            else
            {
                RemovedEntities.Add(added);
            }

            return(added);
        }
Esempio n. 13
0
        // removes all entities from the game
        private void FlushEntities()
        {
            Enemies.Clear();
            Eggs.Clear();

            Player.Sensor.Dispose();

            foreach (GameEntity entity in ActiveEntities)
            {
                CharacterEntity character = entity as CharacterEntity;
                if (character != null)
                {
                    character.DynamicBody.Enabled = false;
                    character.DynamicBody.Dispose();
                }
            }

            ActiveEntities.Clear();
        }
Esempio n. 14
0
        public void Update(GameTime gameTime)
        {
            float deltaTime = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            _chickenSpawnTimer += deltaTime;

            int chickenCnt = ActiveEntities.Count();

            // Spawn Large Chicken
            if (_chickenSpawnTimer >= ChickenSpawnDuration)
            {
                _chickenSpawnTimer = 0f;

                if (chickenCnt < maxChickenCnt)
                {
                    SpawnChicken(GetRandomChickenType());
                }
            }
        }
Esempio n. 15
0
        public GameSnapshotEntityRemoveResult RemoveEntity(IEntity entity)
        {
            if (GlobalEntity == entity)
            {
                return(GameSnapshotEntityRemoveResult.Failed);
            }

            for (int i = 0; i < AddedEntities.Count; ++i)
            {
                if (entity.UniqueId == AddedEntities[i].UniqueId)
                {
                    AddedEntities.RemoveAt(i);
                    return(GameSnapshotEntityRemoveResult.Destroyed);
                }
            }

            for (int i = 0; i < ActiveEntities.Count; ++i)
            {
                if (entity.UniqueId == ActiveEntities[i].UniqueId)
                {
                    IEntity removed = ActiveEntities[i];
                    ActiveEntities.RemoveAt(i);
                    RemovedEntities.Add(removed);
                    return(GameSnapshotEntityRemoveResult.IntoRemoved);
                }
            }

            foreach (IEntity removed in RemovedEntities)
            {
                if (entity.UniqueId == removed.UniqueId)
                {
                    return(GameSnapshotEntityRemoveResult.Failed);
                }
            }

            throw new InvalidOperationException("Unable to find entity with UniqueId = " + entity.UniqueId);
        }
 private IEnumerable <int> GetSortedChickens()
 {
     return(ActiveEntities
            .OrderBy(id => _chickenInfoMapper.Get(id).ChickenType));
 }
Esempio n. 17
0
		void UpdatePreview()
		{
			if (!this) return;
#if BVH
			if (previewBvh)
			{
				if (!entityBuffer.IsCreated) RebuildEntityBuffers();
				if (!bvhNodeBuffer.IsCreated) RebuildBvh();
			}
			else
			{
				sphereBuffer.SafeDispose();
				bvhNodeBuffer.SafeDispose();
				entityBuffer.SafeDispose();

				ActiveEntities.Clear();
			}
#endif // BVH

			if (scene)
			{
				Transform cameraTransform = targetCamera.transform;
				cameraTransform.position = scene.CameraPosition;
				cameraTransform.rotation = Quaternion.LookRotation(scene.CameraTarget - scene.CameraPosition);
				targetCamera.fieldOfView = scene.CameraFieldOfView;
			}

			Action updateDelegate = OnEditorUpdate;
			if (EditorApplication.update.GetInvocationList().All(x => x != (Delegate) updateDelegate))
				EditorApplication.update += OnEditorUpdate;

			if (opaquePreviewCommandBuffer == null)
				opaquePreviewCommandBuffer = new CommandBuffer { name = "World Preview (Opaque)" };
			if (transparentPreviewCommandBuffer == null)
				transparentPreviewCommandBuffer = new CommandBuffer { name = "World Preview (Transparent)" };

			targetCamera.RemoveAllCommandBuffers();

			targetCamera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, opaquePreviewCommandBuffer);
			targetCamera.AddCommandBuffer(CameraEvent.AfterForwardAlpha, transparentPreviewCommandBuffer);

			opaquePreviewCommandBuffer.Clear();
			transparentPreviewCommandBuffer.Clear();

			foreach (UnityEngine.Material material in previewMaterials)
				DestroyImmediate(material);
			previewMaterials.Clear();

			var skybox = targetCamera.GetComponent<Skybox>();
			if (AssetDatabase.IsMainAsset(skybox.material))
				RenderSettings.skybox = skybox.material = new UnityEngine.Material(skybox.material);

			skybox.material.SetColor("_Color1", scene.SkyBottomColor);
			skybox.material.SetColor("_Color2", scene.SkyTopColor);

			EnsurePreviewObjectExists(PrimitiveType.Sphere, ref previewSphere);
			EnsurePreviewObjectExists(PrimitiveType.Quad, ref previewRect);
			EnsurePreviewObjectExists(PrimitiveType.Cube, ref previewBox);

			var previewMeshRenderer = previewSphere.GetComponent<MeshRenderer>();

			CollectActiveEntities();

			opaquePreviewCommandBuffer.EnableShaderKeyword("LIGHTPROBE_SH");
			transparentPreviewCommandBuffer.EnableShaderKeyword("LIGHTPROBE_SH");

			foreach (EntityData entity in ActiveEntities)
			{
				if (!entity.Material) continue;

				bool transparent = entity.Material.Type == MaterialType.Dielectric;
				bool emissive = entity.Material.Type == MaterialType.DiffuseLight;

				Color albedoMainColor = entity.Material.Albedo ? entity.Material.Albedo.MainColor : Color.white;
				Color color = transparent ? albedoMainColor.GetAlphaReplaced(0.5f) : albedoMainColor;
				var material = new UnityEngine.Material(previewMeshRenderer.sharedMaterial) { color = color };
				previewMaterials.Add(material);

				material.SetFloat("_Metallic", entity.Material.Type == MaterialType.Metal ? 1 : 0);
				material.SetFloat("_Glossiness",
					entity.Material.Type == MaterialType.Metal ? 1 - entity.Material.Roughness : transparent ? 1 : 0);
				material.SetTexture("_MainTex", entity.Material.Albedo ? entity.Material.Albedo.Image : null);

				if (transparent)
				{
					material.SetInt("_SrcBlend", (int) BlendMode.One);
					material.SetInt("_DstBlend", (int) BlendMode.OneMinusSrcAlpha);
					material.SetInt("_ZWrite", 0);
					material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
					material.renderQueue = 3000;
				}

				if (emissive)
				{
					material.EnableKeyword("_EMISSION");
					material.SetColor("_EmissionColor",
						entity.Material.Emission ? entity.Material.Emission.MainColor : Color.black);
				}

				CommandBuffer previewCommandBuffer =
					transparent ? transparentPreviewCommandBuffer : opaquePreviewCommandBuffer;

				switch (entity.Type)
				{
					case EntityType.Sphere:
						SphereData s = entity.SphereData;
						previewCommandBuffer.DrawMesh(previewSphere.sharedMesh,
							Matrix4x4.TRS(entity.Position, entity.Rotation, s.Radius * 2 * Vector3.one),
							material, 0,
							material.FindPass("FORWARD"));
						break;

					case EntityType.Rect:
						RectData r = entity.RectData;
						previewCommandBuffer.DrawMesh(previewRect.sharedMesh,
							Matrix4x4.TRS(entity.Position, Quaternion.LookRotation(Vector3.forward) * entity.Rotation,float3(r.Size, 1)),
							material, 0,
							material.FindPass("FORWARD"));
						break;

					case EntityType.Box:
						BoxData b = entity.BoxData;
						previewCommandBuffer.DrawMesh(previewBox.sharedMesh,
							Matrix4x4.TRS(entity.Position, entity.Rotation, b.Size), material, 0,
							material.FindPass("FORWARD"));
						break;
				}
			}
		}
Esempio n. 18
0
 public int GetChickenTypeCnt(ChickenType chickenType)
 {
     return(ActiveEntities
            .Where(id => _chickenInfoMapper.Get(id).ChickenType.Equals(chickenType))
            .Count());
 }
Esempio n. 19
0
 public bool IsActive(int entityId)
 {
     return(ActiveEntities.Get(entityId) != null);
 }
Esempio n. 20
0
        public Entity GetEntity(int entityId)
        {
            Debug.Assert(entityId >= 0, "Id must be at least 0.");

            return(ActiveEntities.Get(entityId));
        }