示例#1
0
        public void CreateEntityFromPrefab()
        {
            ECSWorld world  = new ECSWorld();
            var      buffer = new EntityCommandBuffer(world);

            SharedComponent1 shared1 = new SharedComponent1();
            Prefab           prefab  = new Prefab();

            prefab.AddComponent(new TestComponent1 {
                i = 1, d = 2, f = 3
            });
            prefab.AddSharedComponent(shared1);


            buffer.CreateEntity(prefab);
            buffer.Playback();

            ComponentQuery query = new ComponentQuery();

            query.IncludeReadWrite <TestComponent1>();
            query.IncludeShared <SharedComponent1>();

            Assert.Collection(world.ComponentManager.GetBlocks(query), accessor => {
                Assert.Equal(1, accessor.GetEntityData().Length);
                var cData = accessor.GetComponentData <TestComponent1>();
                Assert.Equal(1, cData[0].i);
                Assert.Equal(2d, cData[0].d, 3);
                Assert.Equal(3f, cData[0].f, 3);

                var shared = accessor.GetSharedComponentData <SharedComponent1>();
                Assert.Same(shared1, shared);
            });
        }
 public override void OnCreateSystem(ECSWorld world)
 {
     cameraQuery = new ComponentQuery();
     cameraQuery.IncludeShared <Camera>();
     cameraQuery.IncludeReadonly <Position>();
     cameraQuery.IncludeReadonly <Rotation>();
 }
        public void OnCreate(ECSWorld world)
        {
            var fragShader = Asset.Load <ShaderAsset>("mesh_instanced_default.frag");
            var vertShader = Asset.Load <ShaderAsset>("mesh_instanced_default.vert");
            var shader     = new ShaderPipeline(fragShader, vertShader, ShaderType.Instanced);

            defaultShader = shader.ShaderPair;

            defaultMaterial = new Material(GraphicsContext.graphicsDevice,
                                           GraphicsContext.uniform0, defaultShader);
            defaultMaterial.wireframe = true;

            instanceMatrix = new DeviceBuffer(GraphicsContext.graphicsDevice, (ulong)Unsafe.SizeOf <ObjectToWorld>(),
                                              BufferUsageFlags.VertexBuffer, BufferMemoryUsageHint.Dynamic);


            var matrix       = mat4.Identity;
            var normalMatrix = new mat3(matrix);

            ObjectToWorld matrices = new ObjectToWorld()
            {
                model  = matrix,
                normal = normalMatrix
            };

            instanceMatrix.SetData(matrices, 0);

            MeshData initialData = new MeshData();

            initialData.subMeshes    = new SubMeshData[1];
            initialData.subMeshes[0] = new SubMeshData(vertices, indices);

            defaultMesh = new Mesh(GraphicsContext.graphicsDevice, initialData, true);
        }
示例#4
0
        public void CreateMultiple()
        {
            ECSWorld world = new ECSWorld();

            Entity[] entities = new Entity[numIterations];

            for (int i = 0; i < numIterations; i++)
            {
                entities[i] = world.Instantiate(prefab1);
            }

            for (int i = 0; i < numIterations; i++)
            {
                Assert.True(world.ComponentManager.HasComponent <TestComponent1>(entities[i]));

                var component  = world.ComponentManager.GetComponent <TestComponent1>(entities[i]);
                var component2 = world.ComponentManager.GetComponent <TestComponent2>(entities[i]);

                Assert.Same(shared, world.ComponentManager.GetSharedComponent <SharedComponent1>(entities[i]));

                Assert.Equal(1, component.i);
                Assert.Equal(2, component.d, 3);
                Assert.Equal(3, component.f, 3);

                Assert.Equal(3, component2.i);
                Assert.Equal(4, component2.d, 3);
                Assert.Equal(5, component2.f, 3);
            }
        }
示例#5
0
 internal static void FireComponentRemovedEvent(ECSWorld world, Entity entity, System.Type componentType, Span <byte> data)
 {
     if (eventCreators.TryGetValue(componentType, out var creator))
     {
         creator.FireComponentRemovedEvent(world, entity, data);
     }
 }
示例#6
0
 internal static void FireComponentAddedEvent(ECSWorld world, Entity entity, System.Type componentType)
 {
     if (eventCreators.TryGetValue(componentType, out var creator))
     {
         creator.FireComponentAddedEvent(world, entity);
     }
 }
示例#7
0
 public void ProcessEvents(ECSWorld world, ReadOnlySpan <CollisionExitEvent> events)
 {
     foreach (var _event in events)
     {
         //Console.WriteLine($"Collision between {_event.A.ToString()} and {_event.B.ToString()} ended.");
     }
 }
        public void TryGetComponent()
        {
            ECSWorld world = new ECSWorld();

            for (int i = 0; i < loop_amount; i++)
            {
                Entity entity = world.EntityManager.CreateEntity();
                Assert.False(entity.TryGetComponent(world, out TestComponentWithInt ti));

                world.ComponentManager.AddComponent(entity, new TestComponentWithInt {
                    someInt = 10
                });

                Assert.True(entity.TryGetComponent(world, out TestComponentWithInt test));

                Assert.Equal(10, test.someInt);
                world.ComponentManager.GetComponent <TestComponentWithInt>(entity).someInt = 12;

                Assert.Equal(12, world.ComponentManager.GetComponent <TestComponentWithInt>(entity).someInt);

                entity.RemoveComponent <TestComponentWithInt>(world);

                Assert.False(entity.TryGetComponent(world, out TestComponentWithInt ti2));
            }
        }
        public override void AfterUpdate(float deltaTime, ECSWorld world)
        {
            if (count < 10000)
            {
                var position = world.ComponentManager.GetComponent <Position>(playerEntity);
                var offset   = random.RandomOnCircle(random.Range(100, 400));
                afterUpdateCommands.CreateEntity(asteroidPrefabs[random.Next(0, asteroidPrefabs.Length)]);

                afterUpdateCommands.SetComponent(new Position()
                {
                    value = offset + position.value
                });
                var maxVel = 10f;
                afterUpdateCommands.SetComponent(new Velocity()
                {
                    value = new vec3(
                        (float)random.NextDouble() * maxVel * 2 - maxVel,
                        (float)random.NextDouble() * maxVel * 2 - maxVel,
                        0
                        )
                });
                afterUpdateCommands.SetComponent(new AngularVelocity()
                {
                    value = new vec3(
                        (float)random.NextDouble() * 10 - 5,
                        (float)random.NextDouble() * 10 - 5,
                        (float)random.NextDouble() * 10 - 5
                        )
                });
                afterUpdateCommands.SetComponent(new Scale()
                {
                    value = new vec3((float)random.NextDouble() + 0.5f)
                });
            }
        }
示例#10
0
        public void SetComponentToEntity()
        {
            ECSWorld world  = new ECSWorld();
            var      buffer = new EntityCommandBuffer(world);

            SharedComponent1 shared1   = new SharedComponent1();
            EntityArchetype  archetype = EntityArchetype.Empty;

            archetype = archetype.Add <TestComponent1>();
            archetype = archetype.AddShared(shared1);

            Entity target = world.Instantiate(archetype);

            buffer.SetComponent(target, new TestComponent1 {
                i = 2, d = 3, f = 4
            });
            buffer.Playback();

            ComponentQuery query = new ComponentQuery();

            query.IncludeReadWrite <TestComponent1>();
            query.IncludeShared <SharedComponent1>();

            Assert.Collection(world.ComponentManager.GetBlocks(query), accessor => {
                Assert.Equal(1, accessor.GetEntityData().Length);

                var cData = accessor.GetComponentData <TestComponent1>();
                Assert.Equal(2, cData[0].i);
                Assert.Equal(3d, cData[0].d, 3);
                Assert.Equal(4f, cData[0].f, 3);
            });
        }
示例#11
0
 public void OnDestroySystem(ECSWorld world)
 {
     foreach (var renderSystem in systems)
     {
         renderSystem.Value.OnDestroy(world);
     }
 }
示例#12
0
        public void RemoveSharedComponentFromEntity()
        {
            ECSWorld world  = new ECSWorld();
            var      buffer = new EntityCommandBuffer(world);

            SharedComponent1 shared1   = new SharedComponent1();
            EntityArchetype  archetype = EntityArchetype.Empty;

            archetype = archetype.Add <TestComponent1>();
            archetype = archetype.AddShared(shared1);

            Entity target = world.Instantiate(archetype);

            buffer.RemoveSharedComponent <SharedComponent1>(target);
            buffer.Playback();

            ComponentQuery query = new ComponentQuery();

            query.IncludeReadWrite <TestComponent1>();
            query.ExcludeShared <SharedComponent1>();

            Assert.Collection(world.ComponentManager.GetBlocks(query), accessor => {
                Assert.Equal(1, accessor.GetEntityData().Length);
            });
        }
示例#13
0
        public override void ProcessBlock(float deltaTime, BlockAccessor block, ECSWorld world)
        {
            var positions = block.GetComponentData <Position>();
            var follows   = block.GetReadOnlyComponentData <FollowTarget>();
            var rotations = block.GetComponentData <Rotation>();

            for (int i = 0; i < block.length; i++)
            {
                if (!world.ComponentManager.TryGetComponent(follows[i].target, out Position targetPos))
                {
                    continue;
                }
                if (!world.ComponentManager.TryGetComponent(follows[i].target, out Rotation targetRot))
                {
                    targetRot = new Rotation();
                }

                var p    = targetPos.value + follows[i].offset;
                var rOff = new quat(follows[i].angleOffset);
                var r    = targetRot.value * rOff;

                positions[i].value = p;
                rotations[i].value = r;
            }
        }
示例#14
0
        public void DestroyEntity()
        {
            ECSWorld world  = new ECSWorld();
            var      buffer = new EntityCommandBuffer(world);

            SharedComponent1 shared1   = new SharedComponent1();
            EntityArchetype  archetype = EntityArchetype.Empty;

            archetype = archetype.Add <TestComponent1>();
            archetype = archetype.AddShared(shared1);


            buffer.CreateEntity(archetype);
            buffer.Playback();

            ComponentQuery query = new ComponentQuery();

            query.IncludeReadWrite <TestComponent1>();
            query.IncludeShared <SharedComponent1>();

            Entity e = default;

            Assert.Collection(world.ComponentManager.GetBlocks(query), accessor => {
                Assert.Equal(1, accessor.GetEntityData().Length);
                e = accessor.GetEntityData()[0];
            });

            buffer.DestroyEntity(e);
            buffer.Playback();

            Assert.Empty(world.ComponentManager.GetBlocks(query));
        }
        public void RemoveComponent()
        {
            ECSWorld world = new ECSWorld();

            Entity[] entities = new Entity[loop_amount];

            for (int i = 0; i < loop_amount; i++)
            {
                Entity entity = world.EntityManager.CreateEntity();
                world.ComponentManager.AddComponent(entity, new TestComponentWithInt {
                    someInt = 10
                });
                Assert.True(world.ComponentManager.HasComponent <TestComponentWithInt>(entity));
                entities[i] = entity;
            }

            for (int i = 0; i < loop_amount; i++)
            {
                Assert.True(world.ComponentManager.HasComponent <TestComponentWithInt>(entities[i]));
                world.ComponentManager.RemoveComponent <TestComponentWithInt>(entities[i]);
                Assert.False(world.ComponentManager.HasComponent <TestComponentWithInt>(entities[i]));
#if DEBUG
                Assert.Throws <ComponentNotFoundException>(() => { world.ComponentManager.GetComponent <TestComponentWithInt>(entities[i]); });
#endif
            }
        }
示例#16
0
        public static void Initialize(ECSWorld world)
        {
            if (initialized)
            {
                return;
            }
            if (world == null)
            {
                throw  new ArgumentNullException(nameof(world), "The ECSWorld provided can not be null.");
            }
            if (!world.IsMainWorld)
            {
                throw new ArgumentException("The ECSWorld of the window needs to be the mainWorld", nameof(world));
            }

            WindowInstance     = Process.GetCurrentProcess().SafeHandle.DangerousGetHandle();
            window             = new Sdl2Window("ECS", 50, 50, 1280, 720, SDL_WindowFlags.Resizable, threadedProcessing: false);
            window.X           = 50;
            window.Y           = 50;
            window.Visible     = true;
            window.MouseWheel += (x) => OnMouseWheel?.Invoke(x);
            window.MouseMove  += (x) => OnMouseMove?.Invoke(x);
            window.MouseDown  += (x) => OnMouseDown?.Invoke(x);
            window.KeyDown    += (x) => OnKeyDown?.Invoke(x);
            window.Closed     += () => OnWindowClose?.Invoke();
            window.Resized    += () => OnWindowResize?.Invoke(window.Width, window.Height);

            world.EarlyUpdate += PumpEvents;

            initialized = true;
            GraphicsContext.Initialize(world);
        }
示例#17
0
 private void InitMainSystems()
 {
     transformsSystem = ECSWorld.AddSystem <TransformsSystem>();
     camerasSystem    = ECSWorld.AddSystem <CamerasSystem>();
     lightSystem      = ECSWorld.AddSystem <LightSystem>();
     renderSystem     = ECSWorld.AddSystem <RenderSystem>();
     ECSWorld.Refresh();
 }
 public void OnDestroy(ECSWorld world)
 {
     foreach (DeviceBuffer buffer in instanceMatricesBuffers)
     {
         buffer.Dispose();
     }
     instanceMatricesBuffers.Clear();
 }
示例#19
0
 private void MouseInputEvent(InputDevice.MouseMoveEventArgs e)
 {
     if (GetEngineConsole.IsShownConsole)
     {
         return;
     }
     ECSWorld?.GetSingletonComponent <SingletonInput>().UpdateMousePosition(e.Offset);
 }
示例#20
0
 public void ProcessEvents(ECSWorld world, ReadOnlySpan <CollisionEnterEvent> events)
 {
     foreach (var _event in events)
     {
         //Console.WriteLine($"Collision between {_event.A.ToString()} and {_event.B.ToString()} started.");
         //_event.A.Destroy(world);
     }
 }
示例#21
0
        public EntityEventTests()
        {
            world = new ECSWorld(false);
            world.Initialize(false);
            eventSystem = new EventHandlerSystem();

            world.SystemManager.RegisterSystem(eventSystem);
        }
示例#22
0
 private void m_OnQuit()
 {
     Profiler.Shutdown();
     AssetsLoader.CleanupAssets();
     OnQuit();
     DestroyMainSystems();
     ECSWorld?.Destroy();
     //RenderBackend.Deinitialize();
 }
示例#23
0
 private static void PumpEvents(float deltatime, ECSWorld ecsWorld)
 {
     Profiler.StartMethod("PumpEvents");
     if (window.Exists)
     {
         InputSnapshot snapshot = window.PumpEvents();
         Input.UpdateInput(snapshot);
     }
     Profiler.EndMethod();
 }
示例#24
0
 private void CreateCubes(int aCount)
 {
     ECSWorld.WatchStart();
     for (int i = 0; i < aCount; i++)
     {
         var pos = ECSWorld.RandomPos();
         CreateCube(pos);
     }
     UnityEngine.Debug.Log("Cost " + ECSWorld.WatchStop() + " Milliseconds Creating " + aCount + " ECSCubes.");
 }
示例#25
0
        public void OnCreateSystem(ECSWorld world)
        {
            BufferPool = new BufferPool();

            Simulation = Simulation.Create(BufferPool, new NarrowPhaseCallbacks(), new PoseIntergratorCallbacks());
            Simulation.Solver.IterationCount = Physics.Settings.solverIterationCount;
            Console.WriteLine("SolverItCount= " + Simulation.Solver.IterationCount);

            threadDispatcher = new SimpleThreadDispatcher(Environment.ProcessorCount);
        }
示例#26
0
 public override void BeforeUpdate(float deltaTime, ECSWorld world)
 {
     foreach (BlockAccessor block in world.ComponentManager.GetBlocks(cameraQuery))
     {
         var poses = block.GetReadOnlyComponentData <Position>();
         for (int i = 0; i < block.length; i++)
         {
             cameraPosition = poses[i].value;
         }
     }
 }
示例#27
0
        private void UpdateMainSystems(Timer timer)
        {
            configSC                   = ECSWorld.GetSingletonComponent <SingletonConfigVar>();
            configSC.ScreenWidth       = RenderBackend.ScreenProps.Width;
            configSC.ScreenHeight      = RenderBackend.ScreenProps.Height;
            configSC.ScreenAspectRatio = RenderBackend.ScreenProps.AspectRatio;

            transformsSystem.Update(timer);
            camerasSystem.Update(timer);
            lightSystem.Update(timer);
            renderSystem.Update(timer);
        }
示例#28
0
        private IFrameData m_Update()
        {
            Profiler.Frame();
            Time.Update();
            Update(Time);
            UpdateMainSystems(Time);
            Profiler.ECS();

            //TODO: Update RenderBackend
            //RenderBackend.RenderFrame(frameData);
            return(ECSWorld.GetSingletonComponent <SingletonFrameScene>().FrameData);
        }
示例#29
0
        public void CreateWithComponent()
        {
            ECSWorld world = new ECSWorld();

            Entity instantiated = world.Instantiate(prefab2);

            Assert.True(world.ComponentManager.HasComponent <TestComponentVector3>(instantiated));

            TestComponentVector3 component = world.ComponentManager.GetComponent <TestComponentVector3>(instantiated);

            Assert.Equal(component.value, Vector3.One);
        }
示例#30
0
        public void Update(float deltaTime, ECSWorld world)
        {
            if (Math.Abs(Window.Aspect - previousAspect) < 0.01)
            {
                return;
            }

            foreach (BlockAccessor block in world.ComponentManager.GetBlocks(query))
            {
                var camera = block.GetSharedComponentData <Camera>();
                camera.aspect = Window.Aspect;
            }
        }