private void KillUnit(Entity unit)
    {
        EntityQuery thanatosQ = GetEntityQuery(typeof(SoulEater), typeof(HP), typeof(Attack));

        if (thanatosQ.CalculateLength() > 0)
        {
            var thanatosA = thanatosQ.ToEntityArray(Allocator.TempJob);
            foreach (var thanatos in thanatosA)
            {
                var thanatosAttack = EntityManager.GetComponentData <Attack>(thanatos);
                var thanatosHP     = EntityManager.GetComponentData <HP>(thanatos);
                PostUpdateCommands.SetComponent <Attack>(thanatos, new Attack()
                {
                    amountOfCubes = thanatosAttack.amountOfCubes + 1, index = thanatosAttack.index, typeOfCubes = thanatosAttack.typeOfCubes
                });
                PostUpdateCommands.SetComponent <HP>(thanatos, new HP()
                {
                    startValue = thanatosHP.startValue, currentValue = thanatosHP.currentValue + 8
                });
            }
            thanatosA.Dispose();
            thanatosQ.Dispose();
        }
        int targetId = EntityManager.GetComponentData <Id>(unit).value;

        if (SquadsManagement.instance.userSquad.ContainsKey(targetId))
        {
            SquadsManagement.instance.userSquad.Remove(targetId);
            SquadsManagement.instance.userScrollListContent.GetComponent <RectTransform>().sizeDelta = new Vector2(0, SquadsManagement.instance.userSquad.Count * 280);
            foreach (var card in SquadsManagement.instance.allCards)
            {
                if (SquadsManagement.instance.userSquad.ContainsKey(card.Key) && card.Value.transform.localPosition.y < SquadsManagement.instance.allCards[targetId].transform.localPosition.y)
                {
                    card.Value.transform.localPosition += new Vector3(0, 280, 0);
                }
            }
            GameObject.Destroy(SquadsManagement.instance.allCards[targetId]);
        }
        PostUpdateCommands.RemoveComponent <Unit>(unit);
        PostUpdateCommands.RemoveComponent <Action>(unit);
        PostUpdateCommands.AddComponent(unit, new View()
        {
            frame = 0, state = 0
        });
        PostUpdateCommands.AddComponent(unit, new Dead()
        {
        });
        PostUpdateCommands.AddComponent(unit, new UnitAnimation()
        {
        });
    }
    protected override void OnUpdate()
    {
        EntityQuery entityQuery = GetEntityQuery(typeof(Translation), typeof(Rotation), typeof(NonUniformScale), typeof(Planetoid));

        quadrantMultiHashMap.Clear();

        if (quadrantMultiHashMap.Capacity < entityQuery.CalculateLength())
        {
            quadrantMultiHashMap.Capacity = entityQuery.CalculateLength();
        }

        SetQuadrantDataJob setQuadrantDataJob = new SetQuadrantDataJob
        {
            quadrantMultiHashMap = quadrantMultiHashMap.ToConcurrent()
        };

        //JobHandle jobHandle = setQuadrantDataJob.Schedule(this);
        JobHandle jobHandle = JobForEachExtensions.Schedule(setQuadrantDataJob, entityQuery); //extension for jobs using parallel for

        jobHandle.Complete();

        DebugDrawQuadrant(CodeMonkey.Utils.UtilsClass.GetMouseWorldPosition());
    }
Beispiel #3
0
    protected override void OnUpdate()
    {
        EntityQuery eq = GetEntityQuery(typeof(Id));

        if (eq.CalculateLength() > 0)
        {
            var allE = eq.ToEntityArray(Allocator.TempJob);
            foreach (var E in allE)
            {
                PostUpdateCommands.DestroyEntity(E);
            }
            allE.Dispose();
        }
    }
Beispiel #4
0
        protected override JobHandle OnUpdate(JobHandle inputDependencies)
        {
            m_BuildPhysicsWorldSystem.FinalJobHandle.Complete();
            var collisionWorld = m_BuildPhysicsWorldSystem.PhysicsWorld.CollisionWorld;

            var chickenCount  = m_ChickenGroup.CalculateLength();
            var raycastsHit   = new NativeArray <int>(chickenCount, Allocator.TempJob);
            var localToWorlds = m_ChickenGroup.ToComponentDataArray <LocalToWorld>(Allocator.TempJob);

            for (var i = 0; i < chickenCount; i++)
            {
                var localToWorld = localToWorlds[i];

                var input = new RaycastInput
                {
                    Start  = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 0.5f,
                    End    = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 1.0f,
                    Filter = CollisionFilter.Default
                };
                raycastsHit[i] = collisionWorld.CastRay(input, out var hit) ? 1 : 0;
                Debug.DrawLine(input.Start, input.End, (raycastsHit[i] & 1) > 0 ? Color.red : Color.green);
                input = new RaycastInput
                {
                    Start  = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 0.5f,
                    End    = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 1.5f + localToWorld.Right * 0.5f,
                    Filter = CollisionFilter.Default
                };
                raycastsHit[i] += collisionWorld.CastRay(input, out hit) ? 1 << 1 : 0;
                Debug.DrawLine(input.Start, input.End, (raycastsHit[i] & 1 << 1) > 0 ? Color.red : Color.green);
                input = new RaycastInput
                {
                    Start  = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 0.5f,
                    End    = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 1.5f - localToWorld.Right * 0.5f,
                    Filter = CollisionFilter.Default
                };
                raycastsHit[i] += collisionWorld.CastRay(input, out hit) ? 1 << 2 : 0;
                Debug.DrawLine(input.Start, input.End, (raycastsHit[i] & 1 << 2) > 0 ? Color.red : Color.green);
            }
            localToWorlds.Dispose();

            var job = new ChickensystemJob
            {
                DeltaTime = Time.deltaTime,
                Hits      = raycastsHit
            };

            return(job.Schedule(m_ChickenGroup, inputDependencies));
        }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (m_MouseGroup.CalculateLength() == 0)
            {
                return(inputDeps);
            }

            var handle = JobHandle.CombineDependencies(inputDeps, m_BuildPhysicsWorldSystem.FinalJobHandle);

            if (Input.GetMouseButtonDown(0) && (Camera.main != null))
            {
                Vector2         mousePosition = Input.mousePosition;
                UnityEngine.Ray unityRay      = Camera.main.ScreenPointToRay(mousePosition);

                var mice           = m_MouseGroup.ToComponentDataArray <MousePick>(Allocator.TempJob);
                var IgnoreTriggers = mice[0].IgnoreTriggers != 0;
                mice.Dispose();

                // Schedule picking job, after the collision world has been built
                handle = new Pick
                {
                    CollisionWorld   = m_BuildPhysicsWorldSystem.PhysicsWorld.CollisionWorld,
                    NumDynamicBodies = m_BuildPhysicsWorldSystem.PhysicsWorld.NumDynamicBodies,
                    SpringData       = SpringDatas,
                    RayInput         = new RaycastInput
                    {
                        Start  = unityRay.origin,
                        End    = unityRay.origin + unityRay.direction * k_MaxDistance,
                        Filter = CollisionFilter.Default,
                    },
                    Near           = Camera.main.nearClipPlane,
                    Forward        = Camera.main.transform.forward,
                    IgnoreTriggers = IgnoreTriggers,
                }.Schedule(JobHandle.CombineDependencies(handle, m_BuildPhysicsWorldSystem.FinalJobHandle));

                PickJobHandle = handle;

                handle.Complete(); // TODO.ma figure out how to do this properly...we need a way to make physics sync wait for
                // any user jobs that touch the component data, maybe a JobHandle LastUserJob or something that the user has to set
            }

            if (Input.GetMouseButtonUp(0))
            {
                SpringDatas[0] = new SpringData();
            }

            return(handle);
        }
Beispiel #6
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        DestroyPositions();

        particlePositions = new NativeArray <float4>(
            positionQuery.CalculateLength(),
            Allocator.TempJob,
            NativeArrayOptions.UninitializedMemory);

        particleJobHandle = new GatherPosJob
        {
            positions = particlePositions,
        }.Schedule(this, inputDeps);

        return(particleJobHandle);
    }
Beispiel #7
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            int projectilesCount = MainGroup.CalculateLength();

            EntityCommandBuffer.Concurrent commandBuffer = barrier.CreateCommandBuffer().ToConcurrent();

            var moveProjectilesJob = new MoveProjectilesJob {
                dt            = Time.deltaTime,
                commandBuffer = commandBuffer,
                terrainY      = ECSController.TerrainY
            };
            var moveProjectilesJobHandle = moveProjectilesJob.Schedule(MainGroup, inputDeps);

            barrier.AddJobHandleForProducer(moveProjectilesJobHandle);
            return(moveProjectilesJobHandle);
        }
        protected override void OnUpdate()
        {
            int total = m_QueryCompleted.CalculateLength();

            if (total == 0)
            {
                return;
            }
            var entities = m_QueryCompleted.ToEntityArray(Allocator.TempJob);

            for (int i = 0; i < total; ++i)
            {
                PostUpdateCommands.DestroyEntity(entities[i]);
            }

            entities.Dispose();
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var df = GetSingleton <DistanceField>();

        EntityManager.GetAllUniqueSharedComponentData(m_UniqueParticlePropertiesEntries);

        // Ignore typeIndex 0, can't use the default for anything meaningful.
        for (int entryIndex = 1; entryIndex < m_UniqueParticlePropertiesEntries.Count; entryIndex++)
        {
            var settings = m_UniqueParticlePropertiesEntries[entryIndex];
            m_Particles.SetFilter(settings);
            if (!m_ParticleDistancesFromIsosurface.IsCreated)
            {
                m_ParticleDistancesFromIsosurface = new NativeArray <float>(m_Particles.CalculateLength(), Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
                m_PropertyColorsAsFloat4s         = new PropertyColorsAsFloat4s(settings.surfaceColor, settings.interiorColor, settings.exteriorColor);
            }

            var simulateParticlesJob = new SimulateParticlesJob()
            {
                deltaTime                  = Time.deltaTime,
                jobSettings                = settings,
                jobRNG                     = m_RandomNumberGenerator,
                jobDistanceFieldModel      = df.model,
                jobDistancesFromIsoSurface = m_ParticleDistancesFromIsosurface
            };
            var simulateParticlesJobHandle = simulateParticlesJob.Schedule(m_Particles, inputDeps);

            var simulateColorsJob = new SimulateParticleColorsJob()
            {
                deltaTime                  = Time.deltaTime,
                jobSettings                = settings,
                jobPropertyColorFloat4s    = m_PropertyColorsAsFloat4s,
                jobDistancesFromIsoSurface = m_ParticleDistancesFromIsosurface
            };
            // Simulating the colors depends on the jobDistancesFromIsoSurface output from simulateParticlesJob.
            var simulateColorsJobHandle = simulateColorsJob.Schedule(m_Particles, simulateParticlesJobHandle);

            // Combine all the job handles from this system so other systems can wait on this one if needed.
            var jobHandles = new NativeArray <JobHandle>(2, Allocator.Temp);
            jobHandles[0] = simulateParticlesJobHandle;
            jobHandles[1] = simulateColorsJobHandle;
            inputDeps     = JobHandle.CombineDependencies(jobHandles);
        }
        m_UniqueParticlePropertiesEntries.Clear();
        return(inputDeps);
    }
Beispiel #10
0
        protected override JobHandle OnUpdate(JobHandle inputDependencies)
        {
            m_BuildPhysicsWorldSystem.FinalJobHandle.Complete();
            var collisionWorld = m_BuildPhysicsWorldSystem.PhysicsWorld.CollisionWorld;

            var playerCount = m_PlayerGroup.CalculateLength();

            var raycastsHit   = new NativeArray <int>(playerCount, Allocator.TempJob);
            var localToWorlds = m_PlayerGroup.ToComponentDataArray <LocalToWorld>(Allocator.TempJob);

            for (var i = 0; i < playerCount; i++)
            {
                var localToWorld = localToWorlds[i];

                var input = new RaycastInput
                {
                    Start  = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 0.65f,
                    End    = localToWorld.Position + math.up() * 0.25f + localToWorld.Forward * 1.5f,
                    Filter = CollisionFilter.Default
                };
                raycastsHit[i] = collisionWorld.CastRay(input, out var hit) ? 1 : 0;
                Debug.DrawLine(input.Start, input.End, (raycastsHit[i] & 1) > 0 ? Color.red : Color.green);

                if ((raycastsHit[i] & 1) > 0)
                {
                    var entity = collisionWorld.Bodies[hit.RigidBodyIndex].Entity;
                    if (World.Active.EntityManager.HasComponent <TreeComponentData>(entity) &&
                        !World.Active.EntityManager.HasComponent <CutTreeTag>(entity))
                    {
                        World.Active.EntityManager.AddComponentData(entity, new CutTreeTag());
                    }
                }
            }
            localToWorlds.Dispose();

            var job = new PlayerSystemJob
            {
                HorizontalInput = Input.GetAxis("Horizontal"),
                VerticalInput   = Input.GetAxis("Vertical"),
                DeltaTime       = Time.deltaTime,
                Hits            = raycastsHit
            };

            return(job.Schedule(m_PlayerGroup, inputDependencies));
        }
        public void ProjectileSpawned_When_WeaponFired()
        {
            BeginInitializationEntityCommandBufferSystem projectileEntityCommandBuffer = _world.GetOrCreateSystem <BeginInitializationEntityCommandBufferSystem>();

            SpawnProjectileSystem spawnSystem = _world.CreateSystem <SpawnProjectileSystem>();
            JobHandle             handle      = spawnSystem.ProcessSpawnProjectileJob(m_weaponFiredQuery, projectileEntityCommandBuffer);

            projectileEntityCommandBuffer.Update();

            _manager.DestroyEntity(m_projectileEntity);   // Destroy prefab entity so that it doesn't count towards the final result

            EntityQuery projectileQuery = _manager.CreateEntityQuery(typeof(Projectile));

            int expectation = 1;
            int result      = projectileQuery.CalculateLength();

            Assert.AreEqual(expectation, result);
        }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            int total = m_TransformGroup.CalculateLength();

            if (total == 0)
            {
                return(inputDeps);
            }

            var transforms   = m_TransformGroup.GetTransformAccessArray();
            var positions    = m_TransformGroup.ToComponentDataArray <Translation>(Allocator.TempJob);
            var applyMoveJob = new ApplyMoveJob
            {
                positions = positions,
            };

            return(applyMoveJob.Schedule(transforms, inputDeps));
        }
Beispiel #13
0
    protected override void OnUpdate()
    {
        int clickCount = m_InstantiateButtonQuery.CalculateLength();

        for (int i = 0; i < clickCount; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                Entity entity = m_WindowPrefab.Instantiate();
                DotsUI.Core.RectTransform rectTransform = EntityManager.GetComponentData <DotsUI.Core.RectTransform>(entity);
                rectTransform.Position = new float2(10.0f + j * 10.0f, -10.0f - j * 10.0f);
                EntityManager.SetComponentData(entity, rectTransform);
                EntityManager.SetComponentData(entity, new UIParent {
                    Value = GetSingletonEntity <WindowCanvasComponent>()
                });
            }
        }
    }
Beispiel #14
0
        private void UpdateDeletedParents()
        {
            using (new ProfilerSample("UpdateDeletedParents"))
            {
                if (m_DeletedParentsGroup.CalculateLength() < 1)
                {
                    return;
                }
                var previousParents = m_DeletedParentsGroup.ToEntityArray(Allocator.TempJob);
                for (int i = 0; i < previousParents.Length; i++)
                {
                    var parentEntity        = previousParents[i];
                    var childEntitiesSource = EntityManager.GetBuffer <UIChild>(parentEntity).AsNativeArray();
                    var childEntities       = new NativeArray <Entity>(childEntitiesSource.Length, Allocator.Temp);
                    for (int j = 0; j < childEntitiesSource.Length; j++)
                    {
                        childEntities[j] = childEntitiesSource[j].Value;
                    }

                    for (int j = 0; j < childEntities.Length; j++)
                    {
                        var childEntity = childEntities[j];

                        if (!EntityManager.Exists(childEntity))
                        {
                            continue;
                        }

                        if (EntityManager.HasComponent(childEntity, typeof(UIParent)))
                        {
                            EntityManager.RemoveComponent(childEntity, typeof(UIParent));
                        }
                        if (EntityManager.HasComponent(childEntity, typeof(UIPreviousParent)))
                        {
                            EntityManager.RemoveComponent(childEntity, typeof(UIPreviousParent));
                        }
                    }

                    childEntities.Dispose();
                }
                EntityManager.RemoveComponent(m_DeletedParentsGroup, typeof(UIChild));
                previousParents.Dispose();
            }
        }
    protected override void OnUpdate()
    {
        // character controller
        if (m_CharacterControllerInputQuery.CalculateLength() == 0)
        {
            EntityManager.CreateEntity(typeof(CharacterControllerInput));
        }

        m_CharacterControllerInputQuery.SetSingleton(new CharacterControllerInput
        {
            Looking  = m_CharacterLooking,
            Movement = m_CharacterMovement,
            Jumped   = m_CharacterJumped ? 1 : 0
        });

        if (m_CharacterGunInputQuery.CalculateLength() == 0)
        {
            EntityManager.CreateEntity(typeof(CharacterGunInput));
        }

        m_CharacterGunInputQuery.SetSingleton(new CharacterGunInput
        {
            Looking = m_CharacterLooking,
            Firing  = m_CharacterFiring,
        });

        m_CharacterJumped = false;

        // vehicle
        if (m_VehicleInputQuery.CalculateLength() == 0)
        {
            EntityManager.CreateEntity(typeof(VehicleInput));
        }

        m_VehicleInputQuery.SetSingleton(new VehicleInput
        {
            Looking  = m_VehicleLooking,
            Steering = m_VehicleSteering,
            Throttle = m_VehicleThrottle,
            Change   = m_VehicleChanged
        });

        m_VehicleChanged = 0;
    }
Beispiel #16
0
        private void UpdateChangeParents()
        {
            using (new ProfilerSample("UpdateChangeParents"))
            {
                if (m_ExistingParentsGroup.CalculateLength() < 1)
                {
                    return;
                }

                var changeParentsChunks = m_ExistingParentsGroup.CreateArchetypeChunkArray(Allocator.TempJob);
                if (changeParentsChunks.Length > 0)
                {
                    var parentType         = GetArchetypeChunkComponentType <UIParent>(true);
                    var previousParentType = GetArchetypeChunkComponentType <UIPreviousParent>(true);
                    var entityType         = GetArchetypeChunkEntityType();
                    var changedParents     = new NativeList <ChangedParent>(Allocator.TempJob);

                    var filterChangedParentsJob = new FilterChangedParents
                    {
                        Chunks             = changeParentsChunks,
                        ChangedParents     = changedParents,
                        ParentType         = parentType,
                        PreviousParentType = previousParentType,
                        EntityType         = entityType
                    };
                    var filterChangedParentsJobHandle = filterChangedParentsJob.Schedule();
                    filterChangedParentsJobHandle.Complete();

                    for (int i = 0; i < changedParents.Length; i++)
                    {
                        var childEntity          = changedParents[i].ChildEntity;
                        var previousParentEntity = changedParents[i].PreviousParentEntity;
                        var parentEntity         = changedParents[i].ParentEntity;

                        RemoveChildFromParent(childEntity, previousParentEntity);
                        AddChildToParent(childEntity, parentEntity);
                    }
                    changedParents.Dispose();
                }
                changeParentsChunks.Dispose();
            }
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        NativeArray<Entity> enemiesArray = new NativeArray<Entity>(0, Allocator.TempJob);

        if (Time.time - timer > cooldownTime)
        {
            EntityQuery enemyQuery = GetEntityQuery(ComponentType.ReadOnly<Enemy>(), ComponentType.ReadOnly<Disabled>());

            NativeArray<Entity> tempArray = enemyQuery.ToEntityArray(Allocator.TempJob);




            NativeSlice<Entity> nativeSlice = tempArray.Slice(0, math.min(enemyQuery.CalculateLength(), multiplier * 2));


            enemiesArray.Dispose();

            enemiesArray = new NativeArray<Entity>(nativeSlice.Length, Allocator.TempJob);

            nativeSlice.CopyTo(enemiesArray);
            tempArray.Dispose();

            timer = Time.time;
            multiplier++;
        }



        SpawnJob spawnJob = new SpawnJob
        {
            commandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent(),
            enemiesArray = enemiesArray
        };

        JobHandle jobHandle = spawnJob.Schedule(inputDeps);
        endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);
        jobHandle.Complete();

        enemiesArray.Dispose();
        return jobHandle;
    }
Beispiel #18
0
        public void UpdateChunkComponent()
        {
            var         arch0  = m_Manager.CreateArchetype(ComponentType.ChunkComponent <EcsTestData>(), typeof(EcsTestData2));
            EntityQuery group0 = m_Manager.CreateEntityQuery(typeof(ChunkHeader), typeof(EcsTestData));

            var         entity0  = m_Manager.CreateEntity(arch0);
            var         chunk0   = m_Manager.GetChunk(entity0);
            EcsTestData testData = new EcsTestData {
                value = 7
            };

            Assert.AreEqual(1, group0.CalculateLength());

            m_Manager.SetChunkComponentData(chunk0, testData);

            Assert.AreEqual(1, group0.CalculateLength());

            Assert.AreEqual(7, m_Manager.GetChunkComponentData <EcsTestData>(entity0).value);

            m_Manager.SetComponentData(entity0, new EcsTestData2 {
                value0 = 1, value1 = 2
            });

            var entity1 = m_Manager.CreateEntity(arch0);
            var chunk1  = m_Manager.GetChunk(entity1);

            Assert.AreEqual(7, m_Manager.GetChunkComponentData <EcsTestData>(entity0).value);
            Assert.AreEqual(7, m_Manager.GetChunkComponentData <EcsTestData>(entity1).value);

            Assert.AreEqual(1, group0.CalculateLength());

            m_Manager.SetChunkComponentData(chunk1, testData);

            Assert.AreEqual(1, group0.CalculateLength());

            m_Manager.SetComponentData(entity1, new EcsTestData2 {
                value0 = 2, value1 = 3
            });

            Assert.AreEqual(1, group0.CalculateLength());

            m_Manager.SetChunkComponentData <EcsTestData>(chunk0, new EcsTestData {
                value = 10
            });

            Assert.AreEqual(10, m_Manager.GetChunkComponentData <EcsTestData>(entity0).value);

            Assert.AreEqual(1, group0.CalculateLength());
        }
Beispiel #19
0
    protected override void OnUpdate()
    {
        if (HasSingleton <GameState>() == false)
        {
            return;
        }

        var G_State = GetSingleton <GameState>();

        if (G_State.IsActive == false)
        {
            return;
        }


        if (G_State.GameEnd == true)
        {
            return;
        }

        if (!(GridEntity.CalculateLength() > 0))
        {
            return;
        }

        NativeArray <Entity> GridDatas = new NativeArray <Entity>(0, Allocator.Temp);

        GetGirdArray(ref GridDatas);


        Entities.With(GridEntity).ForEach((Entity EntityData, ref GridComp GridData) =>
        {
            if (GridData.TapFlag == true)
            {
                SetSingleton <GameState>(G_State);
                RefreshBoardColor();
            }
        });

        GridDatas.Dispose();
    }
Beispiel #20
0
    protected override void OnUpdate()
    {
        if (HasSingleton <BoardState>() == false)
        {
            return;
        }
        if (HasSingleton <GameState>() == false)
        {
            return;
        }
        if (!((GridEntity.CalculateLength() > 0)))
        {
            return;
        }
        var Config = GetSingleton <BoardState>();

        if (GetSingleton <BoardState>().EmitBoard == false)
        {
            InitBoard();
        }
    }
Beispiel #21
0
        /// <summary>
        /// Clone from the world this system resides in to any destination world.
        /// TODO : Add `EntityArchetypeQuery` support
        /// </summary>
        public void CloneTo(World destinationWorld)
        {
            EntityManager destinationEntityManager = destinationWorld.EntityManager;

            using (var ea = EntityManager.GetAllEntities(Allocator.Temp))
            {
                for (int i = 0; i < ea.Length; i++)
                {
                    Entity cloned = EntityManager.Instantiate(ea[i]);
                    EntityManager.AddComponentData(cloned, new Cloned());
                }
            }
            using (var remap = new NativeArray <EntityRemapUtility.EntityRemapInfo>(clonedGroup.CalculateLength(), Allocator.TempJob))
            {
                destinationEntityManager.MoveEntitiesFrom(EntityManager, clonedGroup, remap);
            }
            var destEcs = destinationWorld.CreateSystem <EntityCloningSystem>();

            destEcs.CleanCloned();
            destinationWorld.DestroySystem(destEcs);
        }
        protected override void OnUpdate()
        {
            int total = m_TweenCompleteCallbacks.CalculateLength();

            if (total == 0)
            {
                return;
            }
            var entities = m_TweenCompleteCallbacks.ToEntityArray(Allocator.TempJob);

            for (int i = 0; i < total; i++)
            {
                var id = entities[i].Index;
                if (m_Callbacks.ContainsKey(id))
                {
                    m_Callbacks[id].Invoke();
                    m_Callbacks.Remove(id);
                }
            }
            entities.Dispose();
        }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (m_MouseGroup.CalculateLength() == 0)
            {
                return(inputDeps);
            }

            var handle = JobHandle.CombineDependencies(inputDeps, m_BuildPhysicsWorldSystem.FinalJobHandle);

            if (Input.GetMouseButtonDown(0) && (Camera.main != null))
            {
                var mice           = m_MouseGroup.ToComponentDataArray <MousePick>(Allocator.TempJob);
                var IgnoreTriggers = mice[0].IgnoreTriggers != 0;
                mice.Dispose();

                // Schedule picking job, after the collision world has been built
                handle = new Pick
                {
                    CollisionWorld   = m_BuildPhysicsWorldSystem.PhysicsWorld.CollisionWorld,
                    NumDynamicBodies = m_BuildPhysicsWorldSystem.PhysicsWorld.NumDynamicBodies,
                    SpringData       = SpringDatas,
                    RayInput         = MousePickBehaviour.CreateRayCastFromMouse(),
                    Near             = Camera.main.nearClipPlane,
                    Forward          = Camera.main.transform.forward,
                    IgnoreTriggers   = IgnoreTriggers,
                }.Schedule(JobHandle.CombineDependencies(handle, m_BuildPhysicsWorldSystem.FinalJobHandle));

                PickJobHandle = handle;

                handle.Complete(); // TODO.ma figure out how to do this properly...we need a way to make physics sync wait for
                // any user jobs that touch the component data, maybe a JobHandle LastUserJob or something that the user has to set
            }

            if (Input.GetMouseButtonUp(0))
            {
                SpringDatas[0] = new SpringData();
            }

            return(handle);
        }
Beispiel #24
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (m_KeyboardEventGroup.CalculateLength() > 0 || m_PointerEventGroup.CalculateLength() > 0)
            {
                m_TargetToKeyboardEvent.Clear();
                m_TargetToPointerEvent.Clear();
                CreateTargetToKeyboardEvent createTargetToKeyboardEvent = new CreateTargetToKeyboardEvent()
                {
                    EntityType    = GetArchetypeChunkEntityType(),
                    KbdEventType  = GetArchetypeChunkComponentType <KeyboardEvent>(true),
                    TargetToEvent = m_TargetToKeyboardEvent.ToConcurrent()
                };
                inputDeps = createTargetToKeyboardEvent.Schedule(m_KeyboardEventGroup, inputDeps);
                CreateTargetToPointerEvent createTargetToPointerEvent = new CreateTargetToPointerEvent()
                {
                    EntityType       = GetArchetypeChunkEntityType(),
                    PointerEventType = GetArchetypeChunkComponentType <PointerEvent>(true),
                    TargetToEvent    = m_TargetToPointerEvent.ToConcurrent()
                };
                inputDeps = createTargetToPointerEvent.Schedule(m_PointerEventGroup, inputDeps);
                EventProcessor inputEventProcessor = new EventProcessor()
                {
                    KeyboardInputBufferType       = GetBufferFromEntity <KeyboardInputBuffer>(true),
                    PointerInputBufferType        = GetBufferFromEntity <PointerInputBuffer>(true),
                    InputFieldCaretLinkFromEntity = GetComponentDataFromEntity <InputFieldCaretEntityLink>(true),
                    EntityType            = GetArchetypeChunkEntityType(),
                    CaretStateType        = GetArchetypeChunkComponentType <InputFieldCaretState>(),
                    InputFieldType        = GetArchetypeChunkComponentType <InputField>(),
                    TextDataFromEntity    = GetBufferFromEntity <TextData>(),
                    TargetToKeyboardEvent = m_TargetToKeyboardEvent,
                    TargetToPointerEvent  = m_TargetToPointerEvent,
                    CommandBuff           = m_InputSystemBarrier.CreateCommandBuffer().ToConcurrent(),
                    CaretArchetype        = m_CaretArchetype
                };
                inputDeps = inputEventProcessor.Schedule(m_InputFieldGroup, inputDeps);
                m_InputSystemBarrier.AddJobHandleForProducer(inputDeps);
            }

            return(inputDeps);
        }
        protected override void OnUpdate()
        {
            MultiHashMap.Clear(); // need to be cleared because it is persistent

            // adjust its size to match the current needs
            int entityNumber = _query.CalculateLength();

            if (entityNumber > MultiHashMap.Capacity)
            {
                MultiHashMap.Capacity = entityNumber;
            }

            var setQuadrantDataHashMapJob = new SetQuadrantHashMapDataJob
            {
                NativeMultiHashMap = MultiHashMap.ToConcurrent()
            };

            JobHandle jobHandle = JobForEachExtensions.Schedule(setQuadrantDataHashMapJob, _query);

            jobHandle.Complete();

            // === DEBUG DRAW ===
            // draw quadrants around the player's
            if (Debug.isDebugBuild && GameEngine.Instance.DrawCollisionQuadrants)
            {
                float posX = GameEngine.SpaceshipInstance.transform.position.x;
                float posY = GameEngine.SpaceshipInstance.transform.position.y;
                for (int i = -1; i <= 1; i++)
                {
                    for (int y = -1; y <= 1; y++)
                    {
                        DebugDrawMethods.DebugDrawQuadrant(posX + i * QuadrantCellSize, posY + y * QuadrantCellSize, Color.yellow);
                    }
                }

                Debug.Log(GetEntityCountInHashMap(MultiHashMap, GetPositionHashMapKey(Utils.GetMouseWorldPosition())));
            }
        }
Beispiel #26
0
        protected override void OnUpdate()
        {
            var dataSize      = _query.CalculateLength();
            var healthBarData = _query.ToComponentDataArray <UIHealthBar>(Allocator.TempJob);
            var healthData    = _query.ToComponentDataArray <Health>(Allocator.TempJob);
            var positionData  = _query.ToComponentDataArray <Translation>(Allocator.TempJob);
            var scaleData     = _query.ToComponentDataArray <Scale>(Allocator.TempJob);

            var material = _graphicsProvider.Material;
            var mesh     = _graphicsProvider.GetMesh(1f);

            for (int i = 0; i < dataSize; i += BATCH_SIZE)
            {
                var endIndex  = Mathf.Min(i + BATCH_SIZE, dataSize);
                var batchSize = endIndex - i;
                for (int j = 0; j < batchSize; j++)
                {
                    var index = i + j;
                    _matrices[j]     = GetTransform(positionData[index], scaleData[index], healthBarData[index]);
                    _healthValues[j] = GetHealthValue(healthData[index]);
                }

                _propertyBlock.SetFloatArray(_fillPropIndex, _healthValues);
                UnityEngine.Graphics.DrawMeshInstanced(
                    mesh,
                    0,
                    material,
                    _matrices,
                    batchSize,
                    _propertyBlock
                    );
            }

            healthBarData.Dispose();
            healthData.Dispose();
            positionData.Dispose();
            scaleData.Dispose();
        }
Beispiel #27
0
        protected override void OnUpdate()
        {
            if (mapQuery.CalculateLength() == 0)
            {
                return;
            }
            NativeArray <Entity> cell = mapQuery.ToEntityArray(Allocator.TempJob);

            var woodsCoverRate = ILabBootstrap.Settings.forestCoverRate;

            //后期这里应该同时处理许多地形要求
            for (int i = 0; i < cell.Length; i++)
            {
                if ((randomGenerator.NextInt(0, 10) < woodsCoverRate))
                {
                    PostUpdateCommands.SetComponent(cell[i], new HexCellData
                    {
                        existTree = 1,
                    });
                }
            }
            cell.Dispose();
        }
Beispiel #28
0
 protected override void OnUpdate()
 {
     if (turnCounter == amountTurnsToDraw)
     {
         Debug.Log("Draw");
         World.GetExistingSystem(typeof(InitiativeSystem)).Enabled = false;
         this.Enabled = false;
     }
     readyCheck  = GetEntityQuery(readyQueue);
     updateQuery = GetEntityQuery(typeof(Unit));
     if (readyCheck.CalculateLength() == 0)
     {
         turnCounter++;
         var updateArray = updateQuery.ToEntityArray(Allocator.TempJob);
         for (int i = 0; i < updateArray.Length; i++)
         {
             PostUpdateCommands.AddComponent <ReadyToAction>(updateArray[i], new ReadyToAction()
             {
             });
         }
         updateArray.Dispose();
     }
 }
        /// <summary>
        /// Handles Selection
        /// </summary>
        /// <param name="inputDeps">Input-Dependencies</param>
        /// <returns>JobHandle for final job</returns>
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            inputDeps.Complete();
            if (camera == null)
            {
                camera = Camera.main;
            }
            int amountOfIntersectables = selectables.CalculateLength();

            // Check if creation of (new) NativeArray is required
            if (!intersectionResults.IsCreated || !intersectionResults.Length.Equals(amountOfIntersectables))
            {
                // Dispose previous if it exists
                if (intersectionResults.IsCreated)
                {
                    intersectionResults.Dispose();
                }
                // Create new array. Persistent because it can be re-used as long as the amount of selectables does not change (i.e. Pieces get slain)
                // Size of array should only go down during play
                intersectionResults = new NativeArray <RayIntersectionResult>(amountOfIntersectables, Allocator.Persistent);
            }
            // Handle Keyboard
            HandleKeyboardInput();
            // Get position of Mouse on Screen
            Vector2 mousePos = Input.mousePosition;

            // Check whether MousePos is in Screen
            if (mousePos.x >= 0 && mousePos.x <= Screen.width &&
                mousePos.y >= 0 && mousePos.y <= Screen.height)
            {
                return(HandleMouseInput(inputDeps, mousePos)); // Handle Mouse
            }
            else
            {
                return(inputDeps); // Nothing else to do, return inputDeps
            }
        }
Beispiel #30
0
    protected override void OnStartRunning()
    {
        // Retrieve tank player entities
        if (playersQuery.CalculateLength() == 0)
        {
            throw new InvalidOperationException("no player tanks detected");
        }
        var players = playersQuery.ToEntityArray(Allocator.TempJob);
        ComponentDataFromEntity <TankPlayer> tankPlayers = GetComponentDataFromEntity <TankPlayer>();

        for (int i = 0; i < players.Length; i++)
        {
            TankPlayer tankPlayer = tankPlayers[players[i]];
            if (tankPlayer.PlayerId == 0)
            {
                player1Entity = players[i];
            }
            else if (tankPlayer.PlayerId == 1)
            {
                player2Entity = players[i];
            }
        }
        players.Dispose();

        // Retrieve health masks
        Entities.WithAll <SpriteMask, HealthSlider>().ForEach((Entity e, SpriteMask spriteMask, ref HealthSlider healthSlider) => {
            if (healthSlider.PlayerId == 0)
            {
                player1HealthMask = spriteMask;
            }
            else
            {
                player2HealthMask = spriteMask;
            }
        });
    }