Ejemplo n.º 1
0
 private void CheckCollisions(int chunkIndex, Entity asteroidEntity, float2 firstPos, float firstRadius)
 {
     if (firstPos.x - firstRadius < 0 || firstPos.y - firstRadius < 0 ||
         firstPos.x + firstRadius > level[0].width ||
         firstPos.y + firstRadius > level[0].height)
     {
         commandBuffer.DestroyEntity(chunkIndex, asteroidEntity);
         return;
     }
     // TODO: can check asteroid / asteroid here if required
     for (int bc = 0; bc < bulletChunks.Length; ++bc)
     {
         var bulletAge    = bulletChunks[bc].GetNativeArray(bulletAgeType);
         var bulletPos    = bulletChunks[bc].GetNativeArray(positionType);
         var bulletSphere = bulletChunks[bc].GetNativeArray(sphereType);
         for (int bullet = 0; bullet < bulletAge.Length; ++bullet)
         {
             if (bulletAge[bullet].age > bulletAge[bullet].maxAge)
             {
                 return;
             }
             var secondPos    = bulletPos[bullet].Value.xy;
             var secondRadius = bulletSphere[bullet].radius;
             if (Intersect(firstRadius, secondRadius, firstPos, secondPos))
             {
                 commandBuffer.DestroyEntity(chunkIndex, asteroidEntity);
             }
         }
     }
 }
Ejemplo n.º 2
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity>    entityArray   = chunk.GetNativeArray(entityType);
            BufferAccessor <Action> actionBuffers = chunk.GetBufferAccessor <Action>(actionBufferType);

            for (int i = 0; i < chunk.Count; i++)
            {
                Entity entity = entityArray[i];
                DynamicBuffer <Action> actions = actionBuffers[i];

                // loop through all of the actions in the agent's list, and destroy all of the data holder entities
                for (int j = 0; j < actions.Length; j++)
                {
                    commandBuffer.DestroyEntity(chunkIndex, actions[j].dataHolder);
                }
                if (chunk.Has <Child>(childBufferType))
                {
                    BufferAccessor <Child> childBuffers = chunk.GetBufferAccessor <Child>(childBufferType);
                    DynamicBuffer <Child>  children     = childBuffers[i];
                    for (int j = 0; j < children.Length; j++)
                    {
                        commandBuffer.DestroyEntity(chunkIndex, children[j].Value); //remove the child
                    }
                }
                //)

                commandBuffer.DestroyEntity(chunkIndex, entity); //remove the crowd agent
            }
        }
 public void Execute(FindPairsResult result)
 {
     if (Physics.DistanceBetween(result.bodyA.collider, result.bodyA.transform, result.bodyB.collider, result.bodyB.transform, 0f, out ColliderDistanceResult _))
     {
         ecb.DestroyEntity(result.jobIndex, result.bodyA.entity);
         ecb.DestroyEntity(result.jobIndex, result.bodyB.entity);
     }
 }
    private void CutTrees(EntityCommandBuffer.ParallelWriter ecb, int sortKey, Environment env)
    {
        /* Burst requires conversion to locals */

        NativeMultiHashMap <uint2, TreeHashNode> hashTable = this.hashTable;

        Entities.ForEach((Entity entity, int entityInQueryIndex, in RoadSegment roadSegment) =>
        {
            NativeList <uint2> nodes = new NativeList <uint2>(Allocator.Temp);

            float3 mid   = (roadSegment.initial + roadSegment.final) / 2;
            float length = math.distance(roadSegment.initial, roadSegment.final) / 2;

            float2 center = (mid.xz - Environment.TerrainBoundaries.Min.xz) /
                            env.gridSize;
            float radius = (length + env.roadWidth) / env.gridSize;

            Circle influenceZone = new Circle(center, radius);

            GridIntersection.Circle(influenceZone, nodes);

            for (int i = 0; i < nodes.Length; i++)
            {
                RemoveTreeFromSegment(hashTable, nodes[i], roadSegment, ecb, sortKey, env);
            }

            ecb.DestroyEntity(entityInQueryIndex, entity);
            nodes.Dispose();
        })
        .WithReadOnly(hashTable)
        .ScheduleParallel(Dependency).Complete();
    }
        protected override void OnUpdate()
        {
            // The command buffer to record commands,
            // which are executed by the command buffer system later in the frame
            EntityCommandBuffer.ParallelWriter commandBuffer
                = CommandBufferSystem.CreateCommandBuffer().AsParallelWriter();
            //The DataToSpawn component tells us how many entities with buffers to create
            Entities.ForEach((Entity spawnEntity, int entityInQueryIndex, in DataToSpawn data) =>
            {
                for (int e = 0; e < data.EntityCount; e++)
                {
                    //Create a new entity for the command buffer
                    Entity newEntity = commandBuffer.CreateEntity(entityInQueryIndex);

                    //Create the dynamic buffer and add it to the new entity
                    DynamicBuffer <MyBufferElement> buffer =
                        commandBuffer.AddBuffer <MyBufferElement>(entityInQueryIndex, newEntity);

                    //Reinterpret to plain int buffer
                    DynamicBuffer <int> intBuffer = buffer.Reinterpret <int>();

                    //Optionally, populate the dynamic buffer
                    for (int j = 0; j < data.ElementCount; j++)
                    {
                        intBuffer.Add(j);
                    }
                }

                //Destroy the DataToSpawn entity since it has done its job
                commandBuffer.DestroyEntity(entityInQueryIndex, spawnEntity);
            }).ScheduleParallel();

            CommandBufferSystem.AddJobHandleForProducer(this.Dependency);
        }
Ejemplo n.º 6
0
        public override void UpdateSystem()
        {
            EntityCommandBuffer.ParallelWriter ecb = m_endSimulationECB.CreateCommandBuffer().AsParallelWriter();
            Entities.ForEach((Entity entity, int entityInQueryIndex, ref PhysicsVelocity velocity, ref Projectile projectile, in Translation translation) =>
            {
                float distanceSqrd = math.distancesq(translation.Value, projectile.targetPos);

                if (HasComponent <Translation>(projectile.targetEntity))
                {
                    projectile.targetPos = GetComponent <Translation>(projectile.targetEntity).Value + GetComponent <Attackable>(projectile.targetEntity).centreOffset;
                }
                else if (distanceSqrd <= 1.0f)
                {
                    ecb.DestroyEntity(entityInQueryIndex, entity);
                }

                float3 directionToTarget = math.normalize(projectile.targetPos - translation.Value);
                velocity.Linear          = directionToTarget * projectile.projectileSpeed;
            }).ScheduleParallel();

            Dependency = new OnProjectileCollisionJob
            {
                projectileLookup = GetComponentDataFromEntity <Projectile>(true),
                healthLookup     = GetComponentDataFromEntity <Health>(),
                ecb = m_endSimulationECB.CreateCommandBuffer()
            }.Schedule(m_stepPhysicsWorld.Simulation, ref m_buildPhysicsWorldSystem.PhysicsWorld, Dependency);
        }
Ejemplo n.º 7
0
 public void Execute(Entity entity, int jobIndex, ref TimeToLive timeToLive)
 {
     timeToLive.Value -= dt;
     if (timeToLive.Value <= 0f)
     {
         commands.DestroyEntity(jobIndex, entity);
     }
 }
Ejemplo n.º 8
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            var entities = chunk.GetNativeArray(EntityType);

            if (chunk.Archetype == EntityOnlyArchetype)
            {
                for (var i = 0; i < chunk.Count; i++)
                {
                    CmdBuffer.DestroyEntity(firstEntityIndex + i, entities[i]);
                }
            }
        }
Ejemplo n.º 9
0
        public static void DestroyEntityWithChildren(this EntityCommandBuffer.ParallelWriter ecb, int sortKey, Entity entity, BufferFromEntity <Child> childrenLookup)
        {
            if (TryGetBufferFromEntity(childrenLookup, entity, out DynamicBuffer <Child> children))
            {
                for (int childIndex = 0; childIndex < children.Length; childIndex++)
                {
                    ecb.DestroyEntityWithChildren(sortKey, children[childIndex].Value, childrenLookup);
                }
            }

            ecb.DestroyEntity(sortKey, entity);
        }
Ejemplo n.º 10
0
        void DestroyHierarchy(EntityCommandBuffer.ParallelWriter cmdBuffer, Entity entity, int index, BufferFromEntity <Child> childrenFromEntity)
        {
            cmdBuffer.DestroyEntity(index, entity);
            if (!childrenFromEntity.HasComponent(entity))
            {
                return;
            }
            var children = childrenFromEntity[entity];

            for (var i = 0; i < children.Length; ++i)
            {
                DestroyHierarchy(cmdBuffer, children[i].Value, index, childrenFromEntity);
            }
        }
Ejemplo n.º 11
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <SouffleDeFeuTemp> _souffleArray     = chunk.GetNativeArray(_souffleHandle);
            NativeArray <Entity>           _entityArray      = chunk.GetNativeArray(_entityHandle);
            NativeArray <SouffleDeFeuTemp> _souffleTempArray = _souffleDeFeuTempArray;

            for (int i = 0; i < chunk.Count; i++)
            {
                _souffleTempArray[i] = _souffleArray[i];
                _ecb.SetComponent <SouffleDeFeuTemp>(chunkIndex, _entityArray[i], new SouffleDeFeuTemp {
                    _damage = 1, _position = new Vector3(0, 0, 0), _radius = 15, _team = 18
                });
                _ecb.DestroyEntity(chunkIndex, _entityArray[i]);
            }
        }
Ejemplo n.º 12
0
        public void Execute(int index)
        {
            if (EntitiesToAdd.Length == 0)
            {
                return;
            }

            var newEntity = EntitiesToAdd[index];
            var value     = IntBufferData[newEntity][0].Value;

            if (!IntToEntityLookup.TryAdd(value, newEntity))
            {
                ECB.DestroyEntity(index, newEntity);
            }
        }
Ejemplo n.º 13
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityCommandBuffer.ParallelWriter entityCommandBuffer = endSimulationEntityCommandBufferSystem.CreateCommandBuffer().AsParallelWriter();

        float     destroyXPosition = -10f;
        JobHandle jobHandle        = Entities.WithAll <Pipe>().ForEach((int entityInQueryIndex, Entity entity, ref Translation translation) => {
            if (translation.Value.x <= destroyXPosition)
            {
                entityCommandBuffer.DestroyEntity(entityInQueryIndex, entity);
            }
        }).Schedule(inputDeps);

        endSimulationEntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);

        return(jobHandle);
    }
Ejemplo n.º 14
0
            public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
            {
                var entities    = chunk.GetNativeArray(entitiesType);
                var rpcRequests = chunk.GetNativeArray(rpcRequestType);
                var requests    = chunk.GetNativeArray(reqType);

                for (int i = 0; i < chunk.Count; i++)
                {
                    commandBuffer.DestroyEntity(chunkIndex, entities[i]);
                    if (rpcRequests[i].TargetConnection != Entity.Null)
                    {
                        var buffer = rpcFromEntity[rpcRequests[i].TargetConnection];
                        rpcQueue.Schedule(buffer, requests[i]);
                    }
                }
            }
Ejemplo n.º 15
0
 protected override void OnUpdate()
 {
     EntityCommandBuffer.ParallelWriter ecb = ei_ECB.CreateCommandBuffer().AsParallelWriter();
     Entities.WithBurst(synchronousCompilation: true)
     .ForEach((Entity e, int entityInQueryIndex, in BlockData block, in LocalToWorld ltw) => {
         for (int i = 0; i < block.xGrid; i++)
         {
             for (int j = 0; j < block.yGrid; j++)
             {
                 Entity defEntity = ecb.Instantiate(entityInQueryIndex, block.prefabToSpawn);
                 float3 pos       = new float3(i * block.xPadding, block.offset, j * block.yPadding);
                 ecb.SetComponent(entityInQueryIndex, defEntity, new Translation {
                     Value = pos
                 });
             }
         }
         ecb.DestroyEntity(entityInQueryIndex, e);
     }).ScheduleParallel();
Ejemplo n.º 16
0
            public void Execute(Entity entity, int index, [ReadOnly] ref SendRpcCommandRequestComponent dest,
                                [ReadOnly] ref TActionRequest action)
            {
                if (dest.TargetConnection != Entity.Null)
                {
                    var buffer = rpcFromEntity[dest.TargetConnection];
                    rpcQueue.Schedule(buffer, action);
                }
                else
                {
                    for (var i = 0; i < connections.Length; ++i)
                    {
                        var buffer = rpcFromEntity[connections[i]];
                        rpcQueue.Schedule(buffer, action);
                    }
                }

                commandBuffer.DestroyEntity(index, entity);
            }
Ejemplo n.º 17
0
    private void CutTrees(EntityCommandBuffer.ParallelWriter ecb, Environment env)
    {
        NativeArray <RoadSegment> roadSegments = new NativeArray <RoadSegment>(env.roadSegmentsResolution, Allocator.TempJob);

        Entities.ForEach((Entity entity, int entityInQueryIndex, in RoadSegment roadSegment) =>
        {
            roadSegments[entityInQueryIndex] = roadSegment;
            ecb.DestroyEntity(entityInQueryIndex, entity);
        }).ScheduleParallel(Dependency).Complete();

        Entities.ForEach((Entity entity, int entityInQueryIndex, in TreeTag tree, in Translation translation) =>
        {
            for (int i = 0; i < roadSegments.Length; i++)
            {
                if (Distance.FromPointToLineSegmentSquared(translation.Value, roadSegments[i].initial, roadSegments[i].final) < env.roadWidth * env.roadWidth)
                {
                    ecb.AddComponent <TreeIntersectsRoadTag>(1, entity);
                }
            }
        }).ScheduleParallel(Dependency).Complete();
        public void Execute(Entity entity, int index, [ReadOnly] ref Spawner_FromEntity spawnerFromEntity,
                            [ReadOnly] ref LocalToWorld location)
        {
            for (var x = 0; x < spawnerFromEntity.CountX; x++)
            {
                for (var y = 0; y < spawnerFromEntity.CountY; y++)
                {
                    var instance = CommandBuffer.Instantiate(index, spawnerFromEntity.Prefab);

                    // Place the instantiated in a grid with some noise
                    var position = math.transform(location.Value,
                                                  new float3(x * 0.7F, noise.cnoise(new float2(x, y) * 0.21F) * 2, y * 0.7F));
                    CommandBuffer.SetComponent(index, instance, new Translation {
                        Value = position
                    });
                }
            }

            CommandBuffer.DestroyEntity(index, entity);
        }
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity>         entityArray = chunk.GetNativeArray(entityType);
            NativeArray <PoliceUnitName> nameArray   = chunk.GetNativeArray(nameType);

            for (int i = 0; i < chunk.Count; i++)
            {
                Entity         entity         = entityArray[i];
                PoliceUnitName policeUnitName = nameArray[i];

                /*eventTrigger.TriggerEvent(chunkIndex, new NameToAddEvent{
                 *  Name = policeUnitName.String
                 * });*/
                eventQueueParallel.Enqueue(new NameToRemoveEvent {
                    Name = policeUnitName.String
                });


                commandBuffer.DestroyEntity(chunkIndex, entity); //remove the police unit
            }
        }
Ejemplo n.º 20
0
        void IJobChunk.Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <DamageCount> _damageCount = chunk.GetNativeArray(_damageCountHandle);
            NativeArray <HealthPoint> _healthPoint = chunk.GetNativeArray(_healthPointHandle);
            NativeArray <Entity>      _entity      = chunk.GetNativeArray(_EntityHandle);

            for (int i = 0; i < _damageCount.Length; i++)
            {
                _healthPoint[i] = new HealthPoint()
                {
                    _healthPoint = _healthPoint[i]._healthPoint + _damageCount[i]._heal - _damageCount[i]._damageExplosionCount - _damageCount[i]._damageFireCount
                };

                _damageCount[i] = new DamageCount();

                if (_healthPoint[i]._healthPoint <= 0)
                {
                    _ecb.DestroyEntity(chunkIndex, _entity[i]);
                }
            }
        }
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity>       entityArray       = chunk.GetNativeArray(entityType);
            NativeArray <RemoveAction> removeActionArray = chunk.GetNativeArray(removeActionType);
            BufferAccessor <Action>    buffers           = chunk.GetBufferAccessor <Action>(actionBufferType);

            for (int i = 0; i < chunk.Count; i++)
            {
                Entity entity = entityArray[i];
                DynamicBuffer <Action> actions = buffers[i];
                RemoveAction           removal = removeActionArray[i];

                if (actions.Length > 0) //if there are actions
                {
                    int j = 0;
                    while (j < actions.Length && actions[j].id != removal.id) // find the index of the action
                    {
                        j++;
                    }
                    if (j < actions.Length) // if the action was found before the end of the buffer
                    {
                        Debug.Log("Removing Action " + "!");
                        ActionType aType = actions[j].type;                                   // get the type of the action that was removed
                        entityCommandBuffer.DestroyEntity(chunkIndex, actions[j].dataHolder); // delete the data holder for the action
                        actions.RemoveAt(j);                                                  //remove the action
                        entityCommandBuffer.AddComponent <ChangeAction>(chunkIndex, entity, new ChangeAction {
                        });                                                                   // tell the system that the current action should be changed
                    }
                    else
                    {
                        Debug.Log("Failed to remove " + "!");
                    }
                }
                entityCommandBuffer.RemoveComponent <RemoveAction>(chunkIndex, entity); // remove this component
            }
        }
    protected override void OnUpdate()
    {
        EntityArchetype roadArch = roadSegmentArchitecture;

        EntityCommandBuffer.ParallelWriter ecb = entityCommandBuffer.CreateCommandBuffer().AsParallelWriter();
        Entities.ForEach((Entity entity, int entityInQueryIndex, in CubicBezier cubicBezier) =>
        {
            // Todo: IJobParallelFor
            float t   = 1.0f / cubicBezier.segments;
            float3 p1 = cubicBezier.p0;
            for (int i = 1; i <= cubicBezier.segments; i++)
            {
                float3 p2 = Evaluate(cubicBezier, t * i);
                Entity e  = ecb.CreateEntity(entityInQueryIndex, roadArch);
                ecb.SetComponent(entityInQueryIndex, e, new RoadSegment
                {
                    initial = p1,
                    final   = p2
                });
                p1 = p2;
            }
            ecb.DestroyEntity(entityInQueryIndex, entity);
        }).ScheduleParallel(Dependency).Complete(); // Do not schedule parallel. It will operate on only one element any
    }
Ejemplo n.º 23
0
    protected override void OnUpdate()
    {
        EntityCommandBuffer.ParallelWriter parallelWriterECB = ecbSource.CreateCommandBuffer().AsParallelWriter();

        // Entities with GeneralPurposeComponentA but not StateComponentB
        Entities
        .WithNone <StateComponentData>()
        .ForEach(
            (Entity entity, int entityInQueryIndex, in GeneralPurposeComponentData gpA) =>
        {
            // Add an ISystemStateComponentData instance
            parallelWriterECB.AddComponent <StateComponentData>
            (
                entityInQueryIndex,
                entity,
                new StateComponentData()
            {
                State = 1
            }
            );
        })
        .ScheduleParallel();
        ecbSource.AddJobHandleForProducer(this.Dependency);

        // Create new command buffer
        parallelWriterECB = ecbSource.CreateCommandBuffer().AsParallelWriter();

        // Entities with both GeneralPurposeComponentA and StateComponentB
        Entities
        .WithAll <StateComponentData>()
        .ForEach(
            (Entity entity,
             int entityInQueryIndex,
             ref GeneralPurposeComponentData gpA) =>
        {
            // Process entity, in this case by decrementing the Lifetime count
            gpA.Lifetime--;

            // If out of time, destroy the entity
            if (gpA.Lifetime <= 0)
            {
                parallelWriterECB.DestroyEntity(entityInQueryIndex, entity);
            }
        })
        .ScheduleParallel();
        ecbSource.AddJobHandleForProducer(this.Dependency);

        // Create new command buffer
        parallelWriterECB = ecbSource.CreateCommandBuffer().AsParallelWriter();

        // Entities with StateComponentB but not GeneralPurposeComponentA
        Entities
        .WithAll <StateComponentData>()
        .WithNone <GeneralPurposeComponentData>()
        .ForEach(
            (Entity entity, int entityInQueryIndex) =>
        {
            // This system is responsible for removing any ISystemStateComponentData instances it adds
            // Otherwise, the entity is never truly destroyed.
            parallelWriterECB.RemoveComponent <StateComponentData>(entityInQueryIndex, entity);
        })
        .ScheduleParallel();
        ecbSource.AddJobHandleForProducer(this.Dependency);
    }
Ejemplo n.º 24
0
 public void Execute(Entity entity, int index, ref T c0)
 {
     nativeList.Add(c0);
     parallelWriter.DestroyEntity(index, entity);
 }
Ejemplo n.º 25
0
            public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
            {
                var shipPos      = chunk.GetNativeArray(positionType);
                var shipSphere   = chunk.GetNativeArray(sphereType);
                var shipPlayerId = chunk.GetNativeArray(playerIdType);
                var shipEntity   = chunk.GetNativeArray(entityType);

                for (int ship = 0; ship < shipPos.Length; ++ship)
                {
                    int alive       = 1;
                    var firstPos    = shipPos[ship].Value.xy;
                    var firstRadius = shipSphere[ship].radius;
                    if (firstPos.x - firstRadius < 0 || firstPos.y - firstRadius < 0 ||
                        firstPos.x + firstRadius > level[0].width ||
                        firstPos.y + firstRadius > level[0].height)
                    {
                        if (shipPlayerId.IsCreated)
                        {
                            playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
                        }
                        commandBuffer.DestroyEntity(chunkIndex, shipEntity[ship]);
                        continue;
                    }

                    if (serverSettings.Length > 0 && !serverSettings[0].damageShips)
                    {
                        continue;
                    }

                    /*for (int bc = 0; bc < bulletChunks.Length && alive != 0; ++bc)
                     * {
                     *  var bulletAge = bulletChunks[bc].GetNativeArray(bulletAgeType);
                     *  var bulletPos = bulletChunks[bc].GetNativeArray(positionType);
                     *  var bulletSphere = bulletChunks[bc].GetNativeArray(sphereType);
                     *  for (int bullet = 0; bullet < bulletAge.Length; ++bullet)
                     *  {
                     *      if (bulletAge[bullet].age > bulletAge[bullet].maxAge)
                     *          continue;
                     *      var secondPos = bulletPos[bullet].Value.xy;
                     *      var secondRadius = bulletSphere[bullet].radius;
                     *      if (Intersect(firstRadius, secondRadius, firstPos, secondPos))
                     *      {
                     *          if (shipPlayerId.IsCreated)
                     *              playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
                     *          commandBuffer.DestroyEntity(chunkIndex, shipEntity[ship]);
                     *          alive = 0;
                     *          break;
                     *      }
                     *  }
                     * }*/
                    for (int ac = 0; ac < asteroidChunks.Length && alive != 0; ++ac)
                    {
                        var asteroidSphere = asteroidChunks[ac].GetNativeArray(sphereType);
                        if (asteroidChunks[ac].Has(staticAsteroidType))
                        {
                            var staticAsteroid = asteroidChunks[ac].GetNativeArray(staticAsteroidType);
                            for (int asteroid = 0; asteroid < staticAsteroid.Length; ++asteroid)
                            {
                                var secondPos    = staticAsteroid[asteroid].GetPosition(tick, 1, frameTime).xy;
                                var secondRadius = asteroidSphere[asteroid].radius;
                                if (Intersect(firstRadius, secondRadius, firstPos, secondPos))
                                {
                                    if (shipPlayerId.IsCreated)
                                    {
                                        playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
                                    }
                                    commandBuffer.DestroyEntity(chunkIndex, shipEntity[ship]);
                                    alive = 0;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            var asteroidPos = asteroidChunks[ac].GetNativeArray(positionType);
                            for (int asteroid = 0; asteroid < asteroidPos.Length; ++asteroid)
                            {
                                var secondPos    = asteroidPos[asteroid].Value.xy;
                                var secondRadius = asteroidSphere[asteroid].radius;
                                if (Intersect(firstRadius, secondRadius, firstPos, secondPos))
                                {
                                    if (shipPlayerId.IsCreated)
                                    {
                                        playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
                                    }
                                    commandBuffer.DestroyEntity(chunkIndex, shipEntity[ship]);
                                    alive = 0;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
Ejemplo n.º 26
0
        public override void UpdateSystem()
        {
            EntityCommandBuffer.ParallelWriter ecb = m_endSimECBSystem.CreateCommandBuffer().AsParallelWriter();

            ComponentDataFromEntity <ResourceNode> resourceNodeLookup = GetComponentDataFromEntity <ResourceNode>();

            JobHandle movingToHarvestHandle = Entities
                                              .WithReadOnly(resourceNodeLookup)
                                              .WithAll <MovingToHarvestState>()
                                              .ForEach((Entity entity, int entityInQueryIndex, ref Harvester harvester, ref CurrentTarget currentTarget, ref DynamicBuffer <Command> commandBuffer, in Translation translation) =>
            {
                if (!resourceNodeLookup.TryGetComponentDataFromEntity(currentTarget.targetData.targetEntity, out ResourceNode resourceNode))
                {
                    Debug.Log($"Harvest node {currentTarget.targetData.targetEntity} destroyed when moving to it, finding nearby resource node of type {currentTarget.targetData.targetType} instead");

                    CommandProcessSystem.CompleteCommand(ref commandBuffer);

                    CommandProcessSystem.QueueCommand(CommandType.Harvest, commandBuffer, new TargetData {
                        targetType = currentTarget.targetData.targetType
                    }, true);
                    return;
                }

                //Get harvestable radius
                float dist  = math.distance(translation.Value, currentTarget.targetData.targetPos);
                float range = resourceNode.harvestableRadius + harvester.harvestRange;

                //Are we close enough to harvest yet?
                if (dist <= range)
                {
                    //Move the command onto the execution phase
                    CommandProcessSystem.ExecuteCommand(ref commandBuffer);

                    //Set type we are harvesting + empty inventory if type is different
                    ResourceNode resource = GetComponent <ResourceNode>(currentTarget.targetData.targetEntity);
                    if (harvester.currentlyCarryingType != resource.resourceType)
                    {
                        Debug.Log($"Harvesting type { resource.resourceType } setting carry amount to 0");

                        harvester.currentlyCarryingAmount = 0;
                        harvester.currentlyCarryingType   = resource.resourceType;
                    }
                }
            }).ScheduleParallel(Dependency);

            float dt = Time.DeltaTime;

            EntityCommandBuffer.ParallelWriter ecb2 = m_endSimECBSystem.CreateCommandBuffer().AsParallelWriter();

            Dependency = Entities
                         .WithReadOnly(resourceNodeLookup)
                         .WithAll <HarvestingState>()
                         .ForEach((Entity entity, int entityInQueryIndex, ref Harvester harvester, ref CurrentTarget currentTarget, ref DynamicBuffer <Command> commandBuffer) =>
            {
                if (!resourceNodeLookup.TryGetComponentDataFromEntity(currentTarget.targetData.targetEntity, out ResourceNode resourceNode))
                {
                    Debug.Log($"Harvest node {currentTarget.targetData.targetEntity} destroyed while harvesting it, finding nearby resource node of type {currentTarget.targetData.targetType} instead");

                    //Complete the harvest command.
                    CommandProcessSystem.CompleteCommand(ref commandBuffer);

                    CommandProcessSystem.QueueCommand(CommandType.Harvest, commandBuffer, new TargetData {
                        targetType = currentTarget.targetData.targetType
                    }, true);
                    return;
                }

                //If harvest is on cd
                if (harvester.harvestTickTimer > 0)
                {
                    //Cooling down
                    harvester.harvestTickTimer -= dt;
                    return;
                }
                //Put harvest on cd
                harvester.harvestTickTimer = harvester.harvestTickCooldown;

                //Harvest the smallest amount between amount of resource, amount harvestable and inventory space
                int inventorySpace = harvester.carryCapacity - harvester.currentlyCarryingAmount;
                int harvestAmount  = math.min(math.min(resourceNode.resourceAmount, harvester.harvestAmount), inventorySpace);

                //Transfer resource from resource node to harvester
                Debug.Log($"Harvested { harvestAmount } of {resourceNode.resourceType}");
                harvester.currentlyCarryingAmount += harvestAmount;
                resourceNode.resourceAmount       -= harvestAmount;

                //If the resource is empty destroy it, we must do this before deciding whether to continue harvesting or go deposit
                if (resourceNode.resourceAmount <= 0)
                {
                    Debug.Log("Fully harvested resource");
                    ecb2.DestroyEntity(entityInQueryIndex, currentTarget.targetData.targetEntity);
                }
                else                 //If the resource isn't being destroyed then update its values
                {
                    ecb2.SetComponent(entityInQueryIndex, currentTarget.targetData.targetEntity, resourceNode);
                }

                //If we are at capacity go back to deposit
                if (harvester.currentlyCarryingAmount >= harvester.carryCapacity)
                {
                    //Complete the harvest command.
                    CommandProcessSystem.CompleteCommand(ref commandBuffer);

                    CommandProcessSystem.QueueCommand(CommandType.Deposit, commandBuffer, new TargetData {
                        targetType = AITargetType.Store
                    }, true);
                    return;
                }

                //If the resource is empty find a new one
                if (resourceNode.resourceAmount <= 0)
                {
                    //Complete the harvest command.
                    CommandProcessSystem.CompleteCommand(ref commandBuffer);

                    CommandProcessSystem.QueueCommand(CommandType.Harvest, commandBuffer, new TargetData {
                        targetType = currentTarget.targetData.targetType
                    }, true);
                    return;
                }
            }).ScheduleParallel(movingToHarvestHandle);

            m_endSimECBSystem.AddJobHandleForProducer(Dependency);
        }
Ejemplo n.º 27
0
 public void Destroy()
 {
     _ecb.DestroyEntity(_jobIndex, _entity);
 }
Ejemplo n.º 28
0
        public void Execute(Entity entity, int index, DynamicBuffer <PathCompleteBuffer> buff, ref PathRequest p)
        {
            if (!p.pathComplete)
            {
                if (p.roadBuilding)
                {
                    if ((tiles[p.startIndex].isValid == 0 && !tiles[p.startIndex].hasRoad) || (tiles[p.endIndex].isValid == 0 && !tiles[p.startIndex].hasRoad))
                    {
                        Debug.Log("AStar Job: start or end tile not valid");
                        commandBuffer.DestroyEntity(index, entity);
                        return;
                    }
                }
                else if (p.roadPathing)
                {
                    if (!tiles[p.startIndex].hasRoad || !tiles[p.endIndex].hasRoad)
                    {
                        Debug.LogFormat("AStar Job: start or end tile not valid,  start: {0}   end: {1}", p.startIndex, p.endIndex);

                        commandBuffer.DestroyEntity(index, entity);
                        return;
                    }
                }

                if (p.startIndex == p.endIndex)
                {
                    buff.Add(p.startIndex);
                    p.pathComplete = true;
                    return;
                }

                Debug.Log("Processing AStar request");

                List <PathCost> openCosts   = new List <PathCost>();
                List <PathCost> closedCosts = new List <PathCost>();

                int currentTileIndex = 0;

                PathCost currentTile = new PathCost
                {
                    tileIndex = p.startIndex,
                    fCost     = 0,
                    gCost     = 0,
                    hCost     = 0
                };

                openCosts.Add(currentTile);

                int i = 0;
                while ((openCosts.Count > 0) && (i < maxIter))
                {
                    currentTileIndex = GetLowestCostTile(openCosts, p);
                    currentTile      = openCosts[currentTileIndex];
                    openCosts.RemoveAtSwapBack(currentTileIndex);
                    CalculateTileCosts(openCosts, closedCosts, p, currentTile);
                    closedCosts.Add(currentTile);

                    if (currentTile.tileIndex == p.endIndex)
                    {
                        // found the path
                        break;
                    }
                    i++;
                }

                //var buff = commandBuffer.SetBuffer<PathCompleteBuffer>(index, entity);

                //buff.Clear();

                int checkIndex = p.endIndex;
                int parentIndex;

                while (checkIndex != p.startIndex)
                {
                    buff.Add(checkIndex);
                    parentIndex = GetParentIndex(closedCosts, checkIndex);
                    if (parentIndex < 0)
                    {
                        Debug.Log("AStar path broken");
                        p.pathComplete = true;
                        return;
                    }
                    checkIndex = parentIndex;
                }
                buff.Add(p.startIndex);

                //Debug.LogFormat("AStar Buff length: {0}   start: {1}   end: {2}", buff.Length, p.startIndex, p.endIndex);

                p.pathComplete = true;

                return;
            }
        }
Ejemplo n.º 29
0
 static void destroyPart_
     (EntityCommandBuffer.ParallelWriter cmd_, int uniqueIndex_, Entity part_)
 {
     cmd_.DestroyEntity(uniqueIndex_, part_);
 }
Ejemplo n.º 30
0
 public void LambdaMethod(Entity entity, int index)
 {
     commandBuffer.DestroyEntity(index, entity);
 }