public void Before() {
     var pool = Helper.CreatePool();
     _e = pool.CreateEntity();
     _e.AddComponent(CP.ComponentA, new ComponentA());
     _e.AddComponent(CP.ComponentB, new ComponentB());
     _e.AddComponent(CP.ComponentC, new ComponentC());
 }
        public Entity BuildEntity(Entity e, params object[] args)
        {
            e.Tag = "Chassis";

            #region Body
            Body Chassis = e.AddComponent<Body>(new Body(_World, e));
            {
                Vertices vertices = new Vertices(8);
                vertices.Add(new Vector2(-2.5f, 0.08f));
                vertices.Add(new Vector2(-2.375f, -0.46f));
                vertices.Add(new Vector2(-0.58f, -0.92f));
                vertices.Add(new Vector2(0.46f, -0.92f));
                vertices.Add(new Vector2(2.5f, -0.17f));
                vertices.Add(new Vector2(2.5f, 0.205f));
                vertices.Add(new Vector2(2.3f, 0.33f));
                vertices.Add(new Vector2(-2.25f, 0.35f));
                PolygonShape chassisShape = new PolygonShape(vertices, 2f);

                Chassis.BodyType = BodyType.Dynamic;
                Chassis.Position = new Vector2(0.0f, -1.0f);
                Chassis.CreateFixture(chassisShape);
            }
            #endregion

            #region Sprite
            e.AddComponent<Sprite>(new Sprite(args[0] as Texture2D, (Rectangle)args[1],
               Chassis, 1, Color.White, 0f));
            #endregion
            return e;
        }
Example #3
0
        public override void Initialize()
        {
            this.RegisterSystems();

            FPSCamera camera = new FPSCamera(new Vector3(0f, 0f, 0f), Vector3.Zero,
                Blackboard.Get<GraphicsDevice>("GraphicsDevice").Viewport.AspectRatio, 0.05f, 100f);

            Entity fpscounter = new Entity();
            fpscounter.AddComponent(new Transform2DComponent() { Position = new Vector2(5, 150) });
            fpscounter.AddComponent(new FPSCounterComponent());
            fpscounter.AddComponent(new GUITextComponent());

            Entity pos = new Entity();
            pos.AddComponent(new PositionalTrackingComponent() { Target = camera.Get<Transform3DComponent>() });
            pos.AddComponent(new GUITextComponent());
            pos.AddComponent(new Transform2DComponent() { Position = new Vector2(5, 180) });

            Entity model = new Entity();
            model.AddComponent(new Transform3DComponent(new Vector3(0f, -1f, 2f)));
            model.Get<Transform3DComponent>().Rotation = new Vector3(0f, MathHelper.PiOver2, 3f*MathHelper.PiOver2);
            Model m = Blackboard.Get<ContentManager>("ContentManager").Load<Model>("dragon");
            model.AddComponent(new ModelComponent() { Model = m });

            this.AddEntity(model);
            this.AddEntity(pos);
            this.AddEntity(fpscounter);
            this.AddEntity(camera);
        }
 public void Before()
 {
     var context = Helper.CreateContext();
     _e = context.CreateEntity();
     _e.AddComponent(CP.ComponentA, new ComponentA());
     _e.AddComponent(CP.ComponentB, new ComponentB());
     _e.AddComponent(CP.ComponentC, new ComponentC());
 }
 public Entity BuildEntity(Entity entity, EntityWorld entityWorld, params object[] args)
 {
     var shipDef = Game.WorldConfiguration.Ships[args[0] as string];
     entity.AddComponent(new ModelComponent(shipDef.Model));
     entity.AddComponent(new SceneGraphNode());
     entity.AddComponent(shipDef);
     return entity;
 }
 public Entity BuildEntity(Entity e, EntityWorld world, params object[] args)
 {
     e.Group = "EFFECTS";
     e.AddComponentFromPool<Transform>();
     e.AddComponent(new SpatialForm());
     e.AddComponent(new Expires());
     e.GetComponent<SpatialForm>().SpatialFormFile = "ShipExplosion";
     e.GetComponent<Expires>().LifeTime = 1000;
     return e;
 }
 public Entity BuildEntity(Entity e)
 {
     e.Group = "EFFECTS";
     e.AddComponent(new Transform());
     e.AddComponent(new SpatialForm());
     e.AddComponent(new Expires());
     e.GetComponent<SpatialForm>().SpatialFormFile = "BulletExplosion";
     e.GetComponent<Expires>().LifeTime = 1000;
     return e;
 }
Example #8
0
        private static void InitTestEntities()
        {
            var e = new Entity("player");
            //e.Transform.Scale = new Vector2(0.5f, 0.5f);

            e.AddComponent(new SpriteComponent(e, Engine.Textures["crate"]));
            //e.AddComponent(new PlayerInput(e));
            e.AddComponent(new RectCollider(e) {Width = 96, Height = 96});
            e.AddComponent(new RectRenderer(e, Rectangle.Empty, new Texture2D(Engine.Window.GraphicsDevice, 1, 1)));

            Engine.Entities.AddEntity(e);
        }
        public Entity BuildEntity(Entity e)
        {
            e.Group = "BULLETS";

            e.AddComponent(new Transform());
            e.AddComponent(new SpatialForm());
            e.AddComponent(new Velocity());
            e.AddComponent(new Expires());
            e.GetComponent<SpatialForm>().SpatialFormFile = "Missile";
            e.GetComponent<Expires>().LifeTime = 2000;
            return e;
        }
        public Entity BuildEntity(Entity e, EntityWorld world, params object[] args)
        {
            e.Group = "BULLETS";

            e.AddComponentFromPool<Transform>();
            e.AddComponent(new SpatialForm());
            e.AddComponent(new Velocity());
            e.AddComponent(new Expires());
            e.GetComponent<SpatialForm>().SpatialFormFile = "Missile";
            e.GetComponent<Expires>().LifeTime = 2000;
            return e;
        }
 public Entity BuildEntity(Entity e, EntityWorld world, params object[] args)
 {
     e.Group = "SHIPS";
     e.AddComponentFromPool<Transform>();
     e.AddComponent(new SpatialForm());
     e.AddComponent(new Health());
     e.AddComponent(new Weapon());
     e.AddComponent(new Enemy());
     e.AddComponent(new Velocity());
     e.GetComponent<SpatialForm>().SpatialFormFile = "EnemyShip";
     e.GetComponent<Health>().HP = 10;
     return e;
 }
 public override void OnAdded(Entity entity)
 {
     if (entity.HasComponent<ShipComponent>())
     {
         entity.AddComponent(new SpatialTokenComponent { Token = Ships.AllocateToken(entity) });
     }
 }
Example #13
0
		void Start () 
		{
			Entity e = new Entity();

			Entity player1 = new Entity();
			Entity player2 = new Entity();
			player1.AddComponent(new PlayerType(new PlayerInfo(0, true)));
			player2.AddComponent(new PlayerType(new PlayerInfo(1, false)));

			game.AddEntity(player1);
			game.AddEntity(player2);
			Entity card = EntityFactory.MakeCard(CardInfo.NewID(), "test");
			card.GetComponent<CardType>().info.state = CardInfo.State.Hand;
			game.AddEntity(card);

			card = EntityFactory.MakeCard(CardInfo.NewID(), "test");
			card.GetComponent<CardType>().info.state = CardInfo.State.Hand;
			game.AddEntity(card);

			card = EntityFactory.MakeCard(CardInfo.NewID(), "test");
			card.GetComponent<CardType>().info.state = CardInfo.State.Hand;
			game.AddEntity(card);

			game.AddEntity(EntityFactory.MakeSystem(0,0));
			game.AddEntity(EntityFactory.MakeSystem(0,1));

			game.InitateSystems();
		}
 public void Before()
 {
     _context = Helper.CreateContext();
     _context.GetGroup(Matcher.AllOf(new [] { CP.ComponentA }));
     _e = _context.CreateEntity();
     _e.AddComponent(CP.ComponentA, new ComponentA());
 }
 public void Before() {
     _pool = new Pool(CP.NumComponents);
     _pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentA }));
     _pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentB }));
     _pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentC }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentA,
         CP.ComponentB
     }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentA,
         CP.ComponentC
     }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentB,
         CP.ComponentC
     }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentA,
         CP.ComponentB,
         CP.ComponentC
     }));
     _e = new Entity(CP.NumComponents);
     _e.AddComponent(CP.ComponentA, new ComponentA());
 }
 public Entity BuildEntity(Entity et1, EntityWorld world , params object[] args)
 {
     et1.AddComponent(new Power());
     et1.GetComponent<Power>().POWER = 100;
     et1.Refresh();
     return et1;
 }
 public void Before() {
     _pool = Helper.CreatePool();
     _pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentA }));
     _pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentB }));
     _pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentC }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentA,
         CP.ComponentB
     }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentA,
         CP.ComponentC
     }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentB,
         CP.ComponentC
     }));
     _pool.GetGroup(Matcher.AllOf(new [] {
         CP.ComponentA,
         CP.ComponentB,
         CP.ComponentC
     }));
     _e = _pool.CreateEntity();
     _componentA = new ComponentA();
     _e.AddComponent(CP.ComponentA, _componentA);
 }
Example #18
0
 public void Attach(Entity newEntity)
 {
     ControlledEntity = newEntity;
     ControlledEntity.AddComponent(ComponentFamily.Input,
                                   IoCManager.Resolve<IEntityManagerContainer>().EntityManager.ComponentFactory.
                                       GetComponent("KeyBindingInputComponent"));
     ControlledEntity.AddComponent(ComponentFamily.Mover,
                                   IoCManager.Resolve<IEntityManagerContainer>().EntityManager.ComponentFactory.
                                       GetComponent("PlayerInputMoverComponent"));
     ControlledEntity.AddComponent(ComponentFamily.Collider,
                                   IoCManager.Resolve<IEntityManagerContainer>().EntityManager.ComponentFactory.
                                       GetComponent("ColliderComponent"));
     ControlledEntity.GetComponent(ComponentFamily.Collider).SetParameter(new ComponentParameter("TweakAABB",
                                                                                                 new Vector4D(
                                                                                                     39, 0, 0, 0)));
     ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove += PlayerEntityMoved;
 }
        public Entity BuildEntity(Entity e, params object[] args)
        {
            #region Body

            Body Body = e.AddComponent<Body>(new Body(_World, e));
            {
                FixtureFactory.AttachEllipse(//Add a basic bounding box (rectangle status)
                    ConvertUnits.ToSimUnits(_SpriteSheet.Animations["rotatinglightball"][0].Width * 2),
                    ConvertUnits.ToSimUnits(_SpriteSheet.Animations["rotatinglightball"][0].Height * 2),
                    5,
                    1,
                    Body);
                Body.Position = ConvertUnits.ToSimUnits((Vector2)args[0]);
                Body.BodyType = GameLibrary.Dependencies.Physics.Dynamics.BodyType.Dynamic;
                Body.CollisionCategories = GameLibrary.Dependencies.Physics.Dynamics.Category.Cat3 | GameLibrary.Dependencies.Physics.Dynamics.Category.Cat16;
                Body.CollidesWith = GameLibrary.Dependencies.Physics.Dynamics.Category.Cat2 | GameLibrary.Dependencies.Physics.Dynamics.Category.Cat4 | GameLibrary.Dependencies.Physics.Dynamics.Category.Cat5;
                Body.FixedRotation = false;

                Body.SleepingAllowed = false;
            }

            #endregion Body

            #region Sprite

            Sprite s = new Sprite(_SpriteSheet, "rotatinglightball", 0.4f);
            e.AddComponent<Sprite>(s);

            #endregion Sprite

            #region Animation

            e.AddComponent<Animation>(new Animation(AnimationType.Loop, 10));

            #endregion Animation

            #region Health

            e.AddComponent<Health>(new Health(1)).OnDeath += LambdaComplex.BigEnemyDeath(e, _World as SpaceWorld, 0);

            #endregion Health

            e.Group = "Structures";
            return e;
        }
Example #20
0
 void addDebugComponent(Entity entity)
 {
     var debugBehaviour = new GameObject().AddComponent<EntityDebugBehaviour>();
     debugBehaviour.Init(this, entity, _debugIndex);
     debugBehaviour.transform.SetParent(_entitiesContainer, false);
     var debugComponent = new DebugComponent();
     debugComponent.debugBehaviour = debugBehaviour;
     entity.AddComponent(_debugIndex, debugComponent);
 }
Example #21
0
 public void CreateChildEntities(EntityWorld world, Entity parentEntity)
 {
     var modelComponent = new ShipModelComponent { Model = this };
     parentEntity.AddComponent(modelComponent);
     foreach (var part in Parts)
     {
         part.CreateEntity(world, parentEntity);
     }
     modelComponent.BoundingBox = CalculateBoundingBox(0);
 }
        public Entity BuildEntity(Entity entity, EntityWorld entityWorld, params object[] args)
        {
            TextureManager textureManager = EntitySystem.BlackBoard.GetEntry<TextureManager>("TextureManager");
            FarseerPhysics.Dynamics.World world = EntitySystem.BlackBoard.GetEntry<FarseerPhysics.Dynamics.World>("PhysicsWorld");

            int2 pos = new int2(0, 0);
            float rotation = 0.0f;
            int resourceAmount = 500;
            String resourceType = "No type";
            int textureId = 0;

            Random r = new Random();

            if (args.Length >= 1)
                pos = (int2)args[0];

            if (args.Length >= 2)
                rotation = (float)args[1];

            if (args.Length >= 3)
                resourceType = (String)args[2];

            if (args.Length >= 4)
                resourceAmount = (int)args[3];

            if (args.Length >= 5)
                textureId = (int)args[4];

            Texture2D texture = textureManager.getTexture(textureId);

            Rectangle col;
            if (resourceType.Equals("wood"))
                col = new Rectangle(pos.x + 1, pos.y + 1, 2, 2);
            else
                col = new Rectangle(pos.x, pos.y, texture.Width / Global.tileSize, texture.Height / Global.tileSize);

            entity.AddComponent(new component.TileEntity(entity, new Rectangle(pos.x, pos.y, texture.Width / Global.tileSize, texture.Height / Global.tileSize), col, rotation));
            entity.AddComponent(new component.Size(texture.Width, texture.Height));
            entity.AddComponent(new component.Drawable(texture));
            entity.AddComponent(new component.DepletableResource(resourceAmount, resourceType));
            return entity;
        }
        public Entity BuildEntity(Entity e, params object[] args)
        {
            string text = (string)args[0];
            Vector2 position = (Vector2)args[1];
            float time = 0.9f;

            e.AddComponent<FadingText>(new FadingText(text, time, position));

            e.Refresh();
            return e;
        }
Example #24
0
        public Entity BuildEntity(Entity e, params object[] args)
        {
            e.Tag = "Wheel" + e.Id;

            #region Body
            Body Wheel = e.AddComponent<Body>(new Body(_World, e));
            {
                Wheel.BodyType = BodyType.Dynamic;
                Wheel.Position = (Vector2)args[2];
                Fixture fix = Wheel.CreateFixture(args[3] as CircleShape);
                if (args.Length > 4 && args[4] != null)
                    fix.Friction = (float)args[4];
            }

            #endregion

            #region Sprite
            e.AddComponent<Sprite>(new Sprite(args[0] as Texture2D, (Rectangle)args[1]));
            #endregion
            return e;
        }
Example #25
0
 /// <summary>
 /// Add a Modifier script to an Entity, based on a code block (delegate) and a VectorFunction
 /// </summary>
 /// <param name="e">Entity to add modifier script to</param>
 /// <param name="scriptCode">Code block (delegate) that is the script</param>
 /// <param name="func">Function whose value will be passed in ScriptContext.FunctionValue to script</param>
 /// <returns></returns>
 public static VectorModifierScript AddModifier(Entity e, VectorModifierDelegate scriptCode, IVectorFunction func)
 {
     if (!e.HasComponent<ScriptComp>())
     {
         e.AddComponent(new ScriptComp());
         e.Refresh();
     }
     var sc = e.GetComponent<ScriptComp>();
     var script = new VectorModifierScript(scriptCode, func);
     sc.Add(script);
     return script;
 }
Example #26
0
        public IEntity CreateEntity(IEnumerable<Component> componentCollection)
        {
            IEntity entity = new Entity();

            foreach (Component component in componentCollection)
            {
                component.Entity = entity;
                entity.AddComponent(component);
            }

            return entity;
        }
        public override void Process(Entity e)
        {
            Sprite sprite = e.GetComponent<Sprite>();
            Animation anim = e.GetComponent<Animation>();

            if (anim.Type != AnimationType.None)
            {
                anim._Tick++;
                anim._Tick %= anim.FrameRate;
                if (anim._Tick == 0) //If time to animate.
                {
                    switch (anim.Type)
                    {
                        case AnimationType.Loop:
                            sprite.FrameIndex++;
                            break;

                        case AnimationType.ReverseLoop:
                            sprite.FrameIndex--;
                            break;

                        case AnimationType.Increment:
                            sprite.FrameIndex++;
                            anim.Type = AnimationType.None;
                            break;

                        case AnimationType.Decrement:
                            sprite.FrameIndex--;
                            anim.Type = AnimationType.None;
                            break;

                        case AnimationType.Bounce:
                            sprite.FrameIndex += anim.FrameInc;
                            if (sprite.FrameIndex == sprite.Source.Count() - 1)
                                anim.FrameInc = -1;

                            if (sprite.FrameIndex == 0)
                                anim.FrameInc = 1;
                            break;

                        case AnimationType.Once:
                            if (sprite.FrameIndex < sprite.Source.Count() - 1)
                                sprite.FrameIndex++;
                            else
                                anim.Type = AnimationType.None;
                            break;
                    }
                    e.RemoveComponent<Sprite>(e.GetComponent<Sprite>());
                    e.AddComponent<Sprite>(sprite);
                }
            }
        }
Example #28
0
        public Entity BuildEntity(Entity e, params object[] args)
        {
            e.Group = "Props";
            e.Tag = "Ground";
            Body ground = e.AddComponent<Body>(new Body(world, e));

            //Verts
            Vertices terrain = new Vertices();
                terrain.Add(new Vector2(-20f, -5f));
                terrain.Add(new Vector2(-20f, 0f));
                terrain.Add(new Vector2(20f, 0f));
                terrain.Add(new Vector2(25f, -0.25f));
                terrain.Add(new Vector2(30f, -1f));
                terrain.Add(new Vector2(35f, -4f));
                terrain.Add(new Vector2(40f, 0f));
                terrain.Add(new Vector2(45f, 0f));
                terrain.Add(new Vector2(50f, 1f));
                terrain.Add(new Vector2(55f, 2f));
                terrain.Add(new Vector2(60f, 2f));
                terrain.Add(new Vector2(65f, 1.25f));
                terrain.Add(new Vector2(70f, 0f));
                terrain.Add(new Vector2(75f, -0.3f));
                terrain.Add(new Vector2(80f, -1.5f));
                terrain.Add(new Vector2(85f, -3.5f));
                terrain.Add(new Vector2(90f, 0f));
                terrain.Add(new Vector2(95f, 0.5f));
                terrain.Add(new Vector2(100f, 1f));
                terrain.Add(new Vector2(105f, 2f));
                terrain.Add(new Vector2(110f, 2.5f));
                terrain.Add(new Vector2(115f, 1.3f));
                terrain.Add(new Vector2(120f, 0f));
                terrain.Add(new Vector2(160f, 0f));
                terrain.Add(new Vector2(159f, 10f));
                terrain.Add(new Vector2(201f, 10f));
                terrain.Add(new Vector2(200f, 0f));
                terrain.Add(new Vector2(240f, 0f));
                terrain.Add(new Vector2(250f, -5f));
                terrain.Add(new Vector2(250f, 10f));
                terrain.Add(new Vector2(270f, 10f));
                terrain.Add(new Vector2(270f, 0));
                terrain.Add(new Vector2(310f, 0));
                terrain.Add(new Vector2(310f, -5));

            for (int i = 0; i < terrain.Count - 1; ++i)
            {
                FixtureFactory.AttachEdge(terrain[i], terrain[i + 1], ground);
            }
            ground.Friction = 0.6f;

            return e;
        }
Example #29
0
        protected override void Initialize()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            _netAgent = new NetworkAgent(AgentRole.Client, "Umbra");

            EntitySystem.BlackBoard.SetEntry("Game", this);
            EntitySystem.BlackBoard.SetEntry("ContentManager", Content);
            EntitySystem.BlackBoard.SetEntry("SpriteBatch", spriteBatch);
            EntitySystem.BlackBoard.SetEntry("GraphicsDevice", GraphicsDevice);
            EntitySystem.BlackBoard.SetEntry("ContentManager", Content);
            EntitySystem.BlackBoard.SetEntry("NetworkAgent", _netAgent);

            _entityWorld = new EntityWorld();

            // create camera
            Vector3 camPosition = new Vector3(0, 10, 5);
            Matrix  camRotation = Matrix.CreateFromAxisAngle(new Vector3(1, 0, 0), MathHelper.ToRadians(-65.0f));
            float   aspectRatio = (float)GraphicsDevice.Viewport.Width / GraphicsDevice.Viewport.Height;

            CameraComponent cameraComponent = new CameraComponent(camPosition, camRotation, aspectRatio);

            Entity cameraEntity = _entityWorld.CreateEntity();

            cameraEntity.AddComponent(cameraComponent);

            EntitySystem.BlackBoard.SetEntry("Camera", cameraComponent);

            //// TEMP ////
            Map    map       = new Map(100, 100);
            Entity mapEntity = _entityWorld.CreateEntity();

            mapEntity.AddComponent(new TileMapComponent(map));

            EntitySystem.BlackBoard.SetEntry("Map", map);
            //// TEMP ////

            _entityWorld.InitializeAll(new[] { GetType().Assembly });

            CrawEntityManager.Instance.Initialize(_entityWorld, new ClientEntityFactory(_entityWorld));

            _netAgent.Connect("127.0.0.1");

            base.Initialize();
        }
Example #30
0
        private void NewPlayerInfo(object sender, IncomingMessage receivedMessage)
        {
            if (playerInfo.Count == 0)
            {
                AddHeader();
            }
            string playerIdentifier    = receivedMessage.ReadString();
            string playerName          = receivedMessage.ReadString();
            bool   playerAlreadyExists = false;

            for (int i = 0; i < playerInfo.Count; i++)
            {
                if (playerInfo[i].playerIdentifier == playerIdentifier)
                {
                    playerAlreadyExists = true;
                    //break;
                }
                else if (networkedScene.isHost)
                {
                    //We must resend the all the info as the new player does not have any of that
                    PlayerInfoSync  infoSync = playerInfo[i].Owner.FindComponent <PlayerInfoSync>();
                    OutgoingMessage mes      = networkedScene.networkService.CreateServerMessage();
                    mes.Write(NetworkedScene.SYNC);
                    mes.Write(infoSync.Owner.Name);
                    mes.Write(infoSync.GetType().ToString());
                    infoSync.WriteSyncData(mes);
                    networkedScene.networkService.SendToClients(mes, DeliveryMethod.ReliableOrdered);
                }
            }
            if (!playerAlreadyExists)
            {
                Entity     p    = new Entity("playerInfo" + playerIdentifier);
                PlayerInfo info = new PlayerInfo();
                info.Set(playerIdentifier, playerName,
                         networkedScene.networkService.ClientIdentifier == playerIdentifier,
                         playerInfo.Count,
                         networkedScene);

                p.AddComponent(info)
                .AddComponent(new PlayerInfoSync())
                .AddComponent(new SyncBehavior());
                playerInfo.Add(info);
                networkedScene.EntityManager.Add(p);
            }
        }
        public void TestDestroy_AllEventsThrown()
        {
            Entity            entity    = new Entity();
            UnitTestComponent component = new UnitTestComponent();

            void handler(object sender, ComponentRequestEventArgs args) => args.SetComponent(component);

            entity.ComponentRequested += handler;
            entity.AddComponent <UnitTestComponent>();
            var e = Assert.Raises <ComponentEventArgs>(handler => entity.ComponentRemoved += handler,
                                                       handler => entity.ComponentRemoved -= handler,
                                                       () => entity.Destroy());

            entity.ComponentRequested -= handler;

            Assert.Empty(entity.Components);
            Assert.Equal(component, e.Arguments.Component);
        }
Example #32
0
        public void FirstCommit_EntityAddedAndHandled()
        {
            var entity        = new Entity();
            var component     = new Component();
            var system        = new EntitySystems();
            var entities      = new EntityList();
            var entitySystems = new EntitySystemList(entities);

            entities.Add(entity);
            entitySystems.Add(system);
            entity.AddComponent(component);

            entities.CommitChanges();

            entitySystems.NotifyDoAction(TimeSpan.Zero);

            Assert.AreEqual(11, system.Counter);
        }
Example #33
0
        public static void TestGenerationIndexes()
        {
            Entity e1 = EnvironmentManager.AddEntity();

            Assert.True(e1.EntityExists());
            TestComponent t = e1.AddComponent <TestComponent>();

            Assert.AreEqual(e1.GetComponent <TestComponent>(), t);
            Assert.True(e1.RemoveEntity());
            Assert.False(e1.RemoveEntity());
            Assert.False(e1.EntityExists());
            Entity e2 = EnvironmentManager.AddEntity();

            Assert.True(e2.EntityExists());
            Assert.AreEqual(e1 >> 16, e2 >> 16);
            Assert.AreNotEqual(e1 & 65535, e2 & 65535);
            Assert.Null(e2.GetComponent <TestComponent>());
        }
Example #34
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Context context = new Context();
            Entity  player  = context.CreateEntity();

            player.AddComponent(new PositionComponent {
                x = 0, y = 0
            });
            System.Console.WriteLine(player.GetComponent <PositionComponent>().x);

            //player.SetComponent<PositionComponent>(new PositionComponent { x = 5, y = 5 });
            //System.Console.WriteLine(player.HasComponent<PositionComponent>());

            //player.RemoveComponent<PositionComponent>();
            //System.Console.WriteLine(player.HasComponent<PositionComponent>());
        }
        public void TestAddComponent_ValidNonExistingComponent_ComponentSuccessfullyAdded()
        {
            Entity            entity    = new Entity();
            UnitTestComponent component = new UnitTestComponent();

            void handler(object sender, ComponentRequestEventArgs args) => args.SetComponent(component);

            entity.ComponentRequested += handler;

            var added = Assert.RaisesAny <ComponentEventArgs>(handler => entity.ComponentAdded += handler,
                                                              handler => entity.ComponentAdded -= handler,
                                                              () => entity.AddComponent <UnitTestComponent>());

            entity.ComponentRequested -= handler;
            Assert.Single(entity.Components);
            Assert.Contains(component, entity.Components);
            Assert.Equal(component, added.Arguments.Component);
        }
Example #36
0
        public void Show(Entity screen, Entity module, Entity marketModule, Entity user)
        {
            MainScreenComponent.Instance.OverrideOnBack(new Action(this.Hide));
            Animator component = base.GetComponent <Animator>();

            this.screen = screen;
            if (!base.gameObject.activeSelf)
            {
                base.gameObject.SetActive(true);
                base.GetComponent <CanvasGroup>().alpha = 0f;
                component.SetTrigger("craft");
            }
            component.SetInteger("type", 0);
            if (!screen.HasComponent <LockedScreenComponent>())
            {
                screen.AddComponent <LockedScreenComponent>();
            }
        }
Example #37
0
        public void CanRemoveComponentFromEntityInEcosystemWithHandlers()
        {
            var ecosystem = TestEco();
            var handler   = new MockHandler1();
            var entity    = new Entity();

            ecosystem
            .AddHandler(handler)
            .AddEntity(NAME, entity);
            entity.AddComponent <MockComponent1>();
            ecosystem.Update();

            entity.RemoveComponent <MockComponent1>();
            ecosystem.Update();

            Assert.Equal(2, handler.Called);
            Assert.Empty(handler.EntitiesHandled); // No entities handled on most recent update
        }
        protected virtual void OnEnable()
        {
            entity = GetComponent <EntityMB>().entity;

            if (entity.HasComponent <T>())
            {
                component = entity.GetComponent <T>();
            }
            else if (component == null)
            {
                component = Activator.CreateInstance <T>();
            }

            if (!entity.HasComponent <T>())
            {
                entity.AddComponent(component);
            }
        }
Example #39
0
        public bool PlaceEntityNear(Entity en, int x, int y)
        {
            var emptyCell = this.EmptyCellNear(x, y);

            if (emptyCell == null)
            {
                return(false);
            }
            else
            {
                if (!this.mapEntities.Contains(en))
                {
                    this.mapEntities.Add(en);
                }
                en.AddComponent(new Component_Position(emptyCell.Item1, emptyCell.Item2, this.Level, true));
                return(true);
            }
        }
Example #40
0
        public void Test_EntityWithOneMatchingComponentAndNonMatchingComponent_MatchFalse()
        {
            // Arrange
            var entity = new Entity(new World());

            var transform = new Transform(10f, 10f, 32f, 32f);
            var color     = new Color(1f, 0f, 0f);

            entity.AddComponent(transform);

            var filter = new Filter(new[] { transform.GetType(), color.GetType() });

            // Act
            var match = filter.Match(entity);

            // Assert
            Assert.False(match);
        }
        void UpdateComponents(IEnumerable <Component> oldComponents, IEnumerable <Component> newComponents)
        {
            foreach (var component in oldComponents)
            {
                if (!newComponents.Contains(component))
                {
                    Entity.RemoveComponent(component);
                }
            }

            foreach (var component in newComponents)
            {
                if (!oldComponents.Contains(component))
                {
                    Entity.AddComponent(component);
                }
            }
        }
Example #42
0
        public void CreateEntity_HandlesInitializationFailure()
        {
            var entity = new Entity(1);

            entity.AddComponent(new ComponentStub(entity, false));
            var factoryMock = new Mock <IEntityFactory>();

            factoryMock.Setup(m => m.Create(It.IsNotNull <string>()))
            .Returns(entity);
            entityManager.EntityFactory = factoryMock.Object;
            entityManager.Initialize();
            entityManager.PostInitialize();

            var result = entityManager.CreateEntity("test");

            Assert.IsNull(result);
            Assert.IsEmpty(entityManager.Entities);
        }
Example #43
0
        private void CreateSecurityCamera(Entity entity, Vector3 position, Vector3 startLookAt, Vector3 endLookAt, TimeSpan timeOffset)
        {
            var camera = entity.FindComponent <Camera3D>();

            // Create RenderTarget to the camera
            camera.RenderTarget       = WaveServices.GraphicsDevice.RenderTargets.CreateRenderTarget(350, 256);
            camera.Transform.Position = position;
            camera.Transform.LookAt(startLookAt);

            entity.AddComponent(new SecurityCameraBehavior(startLookAt, endLookAt, timeOffset));

            // This camera will not render the GUI layer
            camera.LayerMask[DefaultLayers.GUI] = false;

            // Register as secondary camera
            this.cameras.Add(camera);
            this.cameraRenderTargets[camera] = camera.RenderTarget;
        }
Example #44
0
        protected override void DoAction(Entity entity, TimeSpan gameTime)
        {
            base.DoAction(entity, gameTime);
            var map   = entity.GetComponent <TiledMapComponent>();
            var depth = entity.GetComponent <DepthLayerComponent>()?.Depth ?? 0;

            var finalRender = entity.GetComponent <FinalRenderComponent>();

            if (finalRender == null)
            {
                finalRender = entity.AddComponent <FinalRenderComponent>();
            }
            finalRender.Batch.Clear();

            var transformMatrix = TransformationUtils.GetTransformation(entity).LocalTransformMatrix;

            this.Draw(map, depth, finalRender.Batch, transformMatrix);
        }
        public void InitShaftShotAnimation(NodeAddedEvent evt, InitialShaftShotAnimationNode weapon)
        {
            Animator             animator    = weapon.animation.Animator;
            ShaftEnergyComponent shaftEnergy = weapon.shaftEnergy;
            Entity entity = weapon.Entity;

            weapon.shaftShotAnimation.Init(animator, weapon.weaponCooldown.CooldownIntervalSec, shaftEnergy.UnloadEnergyPerQuickShot, shaftEnergy.ReloadEnergyPerSec, shaftEnergy.PossibleUnloadEnergyPerAimingShot);
            weapon.shaftShotAnimationTrigger.Entity = entity;
            ShaftShotAnimationESMComponent component = new ShaftShotAnimationESMComponent();

            entity.AddComponent(component);
            EntityStateMachine esm = component.Esm;

            esm.AddState <ShaftShotAnimationStates.ShaftShotAnimationIdleState>();
            esm.AddState <ShaftShotAnimationStates.ShaftShotAnimationBounceState>();
            esm.AddState <ShaftShotAnimationStates.ShaftShotAnimationCooldownState>();
            esm.ChangeState <ShaftShotAnimationStates.ShaftShotAnimationIdleState>();
        }
Example #46
0
        public static void AddFireEmitter(Entity e)
        {
            e.AddComponent <Emiter>();

            Emiter emiter = e.GetComponent <Emiter>();

            emiter.particleLifeTime   = 400;
            emiter.particlesPerSecond = 500;
            emiter.particleSpeed      = 2;
            emiter.spray           = 90;
            emiter.direction       = -135;
            emiter.startColor      = Color.Red;
            emiter.lastEmit        = DateTime.Now;
            emiter.type            = EmiterType.Sphere;
            emiter.radius          = 50;
            emiter.particleTexture = new Texture2D(World.GraphicsDevice, 1, 1);
            emiter.particleTexture.SetData(new Color[] { emiter.startColor });
        }
 public Entity BuildEntity(Entity e)
 {
     e.Group = "SHIPS";
     e.AddComponent(new Transform());
     e.AddComponent(new SpatialForm());
     e.AddComponent(new Health());
     e.AddComponent(new Weapon());
     e.AddComponent(new Enemy());
     e.AddComponent(new Velocity());
     e.GetComponent<SpatialForm>().SpatialFormFile = "EnemyShip";
     e.GetComponent<Health>().HP = 10;
     return e;
 }
Example #48
0
        public void Show(Entity screen, Entity battleUser, bool customBattle, bool isDeserter, bool isNewbieBattle)
        {
            this.screen     = screen;
            this.battleUser = battleUser;
            InputManager.DeactivateContext(BasicContexts.MOUSE_CONTEXT);
            this.SaveCursorStateAndShow();
            InputManager.Suspend();
            if (InputMapping.Cancel)
            {
                this.igoreFirstEscape = true;
            }
            base.gameObject.SetActive(true);
            this.no.GetComponent <Animator>().ResetTrigger("Normal");
            this.no.GetComponent <Animator>().SetTrigger("Highlighted");
            this.no.Select();
            if (!screen.HasComponent <LockedScreenComponent>())
            {
                screen.AddComponent <LockedScreenComponent>();
            }
            bool flag = !battleUser.HasComponent <UserInBattleAsTankComponent>();

            this.firstLineText.gameObject.SetActive(false);
            if (isNewbieBattle)
            {
                this.warningSign.gameObject.SetActive(false);
                this.headerText.color    = this.newbieHeaderColor;
                this.headerText.text     = this.NewbieExitText;
                this.secondLineText.text = this.NewbieSecondLineText;
                this.thirdLineText.text  = this.NewbieThirdLineText;
                this.warningText.gameObject.SetActive(false);
                this.yesText.text = this.CustomYesText;
            }
            else
            {
                this.warningSign.gameObject.SetActive(true);
                this.headerText.color = this.regularHeaderColor;
                this.headerText.text  = this.RegularHeaderText;
                this.secondLineText.gameObject.SetActive(!flag);
                this.secondLineText.text = !customBattle ? this.SecondLineText : this.CustomBattleSecondLineText;
                this.thirdLineText.text  = (customBattle || flag) ? this.CustomThirdLineText : this.ThirdLineText;
                this.yesText.text        = (customBattle || (flag || !isDeserter)) ? this.CustomYesText : this.YesText;
                this.warningText.gameObject.SetActive((isDeserter && !customBattle) && !flag);
            }
        }
Example #49
0
        private void loadMap()
        {
            // TODO: figure out whether we're creating a new map or restoring (does it matter if we seed the rng)
            var mapAsset = default(TmxMap);

            if (NGame.context.config.generateMap)
            {
                mapAsset = Core.Content.LoadTiledMap("Data/maps/base.tmx");
                var mapSize = NGame.context.config.generatedMapSize;

                if (state.mapgenSeed == 0)
                {
                    // choose a new mapgen seed
                    state.mapgenSeed = Random.RNG.Next(int.MinValue, int.MaxValue);
                }

                var gen = new MapGenerator(mapSize, mapSize, state.mapgenSeed);
                gen.generate();
                gen.analyze();
                gen.copyToTilemap(mapAsset, createObjects: !rehydrated);
                // log generated map
                Global.log.trace(
                    $"generated map of size {mapSize}, with {gen.roomRects.Count} rects:\n{gen.dumpGrid()}");
            }
            else
            {
                mapAsset = Core.Content.LoadTiledMap("Data/maps/test4.tmx");
            }

            // TODO: ensure that the loaded map matches the saved map
            mapNt = new Entity("map");
            var mapRenderer = mapNt.AddComponent(new TiledMapRenderer(mapAsset, null, false));

            mapRenderer.SetLayersToRender(MapLoader.LAYER_STRUCTURE, MapLoader.LAYER_FEATURES,
                                          MapLoader.LAYER_BACKDROP);
            var mapLoader = new MapLoader(this, mapNt);

            // load map
            mapLoader.load(mapAsset, createObjects: !rehydrated);

            // save map
            state.map = mapLoader.mapRepr;
        }
Example #50
0
        public override void Initialize()
        {
            base.Initialize();

            animator.AddAnimation("fire", new[] {
                sprites[0],
                sprites[1],
                sprites[2],
                sprites[3],
                sprites[4],
                sprites[5],
                sprites[6]
            });
            animator.AddAnimation("fire", new[] {
                sprites[0],
                sprites[1],
                sprites[2],
                sprites[3],
                sprites[4],
                sprites[5],
                sprites[6]
            });
            animator.AddAnimation("idle", new[] {
                sprites[7],
                sprites[8],
                sprites[9],
                sprites[10],
            });

            animator.OnAnimationCompletedEvent += onAnimCompleted;
            // set up hitbox
            hitbox = new BoxCollider(-2 * 2, -28 * 2, 4 * 2, 20 * 2)
            {
                Tag = Constants.Colliders.SHOOT
            };
            hitboxOffset = new Vector2(0, -28);

            hitbox.IsTrigger = true;
            Flags.SetFlagExclusive(ref hitbox.PhysicsLayer, Constants.Physics.LAYER_FIRE);
            Entity.AddComponent(hitbox);

            onAnimCompleted(null); // reset animation
        }
Example #51
0
        public void AddOrbiter(Entity e)
        {
            if (!e.HasComponent <OrbitalComponent>())
            {
                e.AddComponent(new OrbitalComponent());
            }

            /*if (Entity is Player && Orbiting.Count == 0) {
             *      Entity.GetComponent<AudioEmitterComponent>().Emit("item_orbitals", 0.5f, looped: true, tween: true);
             * }	*/

            e.GetComponent <OrbitalComponent>().Orbiting = Entity;
            Orbiting.Add(e);

            if (Entity is Player && Orbiting.Count >= 3)
            {
                Achievements.Unlock("bk:star");
            }
        }
Example #52
0
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (preppingLevel)
            {
                return;
            }
            //we know it's time to seed a new level when no meteors or enemies are left
            List <Entity> enemies = world.GetEntities(new[] { typeof(EnemyComponent) });
            List <Entity> meteors = world.GetEntities(new[] { typeof(MeteorComponent) });

            if (enemies.Count == 0 && meteors.Count == 0)
            {
                levelNumber++;
                if (levelNumber > 1)
                {
                    Entity e = new Entity();
                    e.AddComponent(new NotificationComponent("Level Complete!", 3000, true));
                    world.AddEntity(e);
                    preppingLevel = true;
                    Task.Delay(5000).ContinueWith(delegate
                    {
                        Entity e = new Entity();
                        e.AddComponent(new NotificationComponent("Begin Level " + levelNumber, 3000, true));
                        world.AddEntity(e);

                        Task.Delay(3000).ContinueWith(delegate
                        {
                            BuildLevel();
                        });
                    });
                }
                else
                {
                    Entity e = new Entity();
                    e.AddComponent(new NotificationComponent("Good Luck!", 3000, true));
                    world.AddEntity(e);
                    //Load first level
                    BuildLevel();
                }
            }
        }
Example #53
0
        public void CreateEntity_AddsEntity()
        {
            var entity = new Entity(1);

            entity.AddComponent(new ComponentStub(entity));
            var factoryMock = new Mock <IEntityFactory>();

            factoryMock.Setup(m => m.Create(It.IsNotNull <string>()))
            .Returns(entity);
            entityManager.EntityFactory = factoryMock.Object;
            entityManager.Initialize();
            entityManager.PostInitialize();

            var result = entityManager.CreateEntity("test");

            Assert.IsNotNull(result);
            Assert.IsTrue(result.IsInitialized);
            Assert.AreEqual(1, entityManager.Entities.Count);
        }
Example #54
0
        internal override void OnComponentAddedToLayer(Component component)
        {
            base.OnComponentAddedToLayer(component);
            Entity e = component as Entity;

            if (e != null)
            {
                TilePosition tp = e.GetComponentByType <TilePosition>();
                if (tp == null)
                {
                    e.AddComponent(tp = new TilePosition(this));
                }
                else
                {
                    tp.SetIntegrater(this);
                }
                this.positions[e] = tp;
            }
        }
Example #55
0
        public override void OnAddedToEntity()
        {
            base.OnAddedToEntity();

            mover                            = Entity.AddComponent(new Mover());
            animator                         = Entity.AddComponent(new SpriteAnimator());
            movementCollider                 = Entity.AddComponent(new BoxCollider(-7, 48, 12, 8));
            interactableCollider             = Entity.AddComponent(new CircleCollider(34));
            interactableCollider.IsTrigger   = true;
            interactableCollider.LocalOffset = new Vector2(0, 48);
            health                           = Entity.AddComponent(new Health(44));

            health.OnDeath      += OnDeath;
            animator.RenderLayer = 0;
            Core.StartCoroutine(TimeDamage());

            SetupInput();
            SetupAnimations();
        }
Example #56
0
        void LoadMarineSnow(List <Entity> entities)
        {
            Texture2D texture = ContentLoader.Load <Texture2D>("Levels/Jellyfish/marine-snow");

            Entity front = new Entity("marine-snow-front");

            front.AddComponent(new MarineSnow(texture, new RectangleF(0, 0, Screen.Width, Screen.Height), new Vector2(0, 50)));
            entities.Add(front);

            Entity middle = new Entity("marine-snow-middle");

            middle.AddComponent(new MarineSnow(texture, new RectangleF(texture.Width * 1 / 3f, texture.Height * 1 / 3f, Screen.Width, Screen.Height), new Vector2(0, 25)));
            entities.Add(middle);

            Entity back = new Entity("marine-snow-back");

            back.AddComponent(new MarineSnow(texture, new RectangleF(texture.Width * 2 / 3f, texture.Height * 2 / 3f, Screen.Width, Screen.Height), new Vector2(0, 12.5f)));
            entities.Add(back);
        }
Example #57
0
        /// add a new Component, return the old one if exists
        public static T AddComponent <T>(this Entity entity, bool keepOldIfExists = false) where T : IComponent, new()
        {
            int index = ComponentIndex <T> .FindIn(entity.contextInfo);

            T component;

            if (keepOldIfExists && entity.HasComponent(index))
            {
                component = (T)entity.GetComponent(index);
                entity.MarkUpdated(index);
            }
            else
            {
                component = entity.CreateComponent <T>(index);
                entity.AddComponent(index, component);
            }

            return(component);
        }
Example #58
0
        public void SetUp()
        {
            _world = TestHelpers.CreateEntityWorld();
            _mockEnemyWithPosition = _world.CreateEntity();
            _mockEnemyWithPosition.AddComponent(new Position());
            _mockEnemyWithoutPosition = _world.CreateEntity();
            _mockItem = _world.CreateEntity();

            Mock <IEntityFactory> mockFactory = new Mock <IEntityFactory>();

            mockFactory.Setup(x => x.Create <Enemy>("testName", It.IsAny <int>(), It.IsAny <int>()))
            .Returns(_mockEnemyWithPosition);
            mockFactory.Setup(x => x.Create <Enemy>("testWithoutPosition", It.IsAny <int>(), It.IsAny <int>()))
            .Returns(_mockEnemyWithoutPosition);
            mockFactory.Setup(x => x.Create <Item>("testName", It.IsAny <int>(), It.IsAny <int>()))
            .Returns(_mockItem);

            _methods = new EntityMethods(mockFactory.Object);
        }
Example #59
0
        public void AddPlayers(List <Player> players)
        {
            foreach (var p in players)
            {
                var e     = new Entity();
                var lives = new Text(StartingLives.ToString());
                lives.Italicized = true;
                lives.Size       = 18;
                lives.X          = 10;
                lives.Y          = 15;
                lives.ScrollX    = lives.ScrollY = 0;

                var head = new Image(Library.GetTexture("players/" + p.ImageName + "_head.png"));
                head.CenterOO();
                head.X       = -10;
                head.Y       = 25;
                head.ScrollX = head.ScrollY = 0;

                var graphics = new Graphiclist(lives, head);
                graphics.ScrollX = graphics.ScrollY = 0;
                e.AddComponent(graphics);

                if (StartingHealth != 0 && PunchDamage != 0)
                {
                    var health = new Text(string.Format("{0}/{0}", StartingHealth));
                    health.Bold    = true;
                    health.Size    = 18;
                    health.X       = head.X - head.Width / 2;
                    health.Y       = lives.Y + 30;
                    health.ScrollX = health.ScrollY = 0;
                    graphics.Add(health);

                    e.AddResponse(HUD.Message.UpdateDamage, OnDamage(p, health));
                }

                e.AddResponse(Player.Message.Die, OnDeath(p, lives, head));
                e.AddResponse(Player.Message.UpgradeAcquired, OnUpgradeAcquired(p, lives, head));
                e.AddResponse(Upgrade.Message.Used, OnUpgradeUsed());

                Players.Add(e);
                upgradeIcons.Add(new Stack <Image>());
            }
        }
Example #60
0
        protected override void Initialize()
        {
            base.Initialize();

            Engine.Initialize((IGraphicsDeviceService)Services.GetService(typeof(IGraphicsDeviceService)), TopLevelControl.Handle);

            Entity mainCamera = new Entity("_MainCamera", true);

            mainCamera.AddComponent(new CameraComponent(mainCamera));
            //mainCamera.AddComponent(new CameraInput(mainCamera));
            Engine.Cameras.SetCurrent(mainCamera.GetComponent<CameraComponent>());

            Engine.Textures.Add("crate", "Sprites/crate", true);
            Engine.Textures.Add("grass", "Tiles/grass", true);
            Engine.Textures.Add("background", "Tiles/background", true);

            Engine.SoundFX.Add("ammo_pickup", "Sounds/ammo_pickup", true);

            InitTestEntities();
        }