public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            var randomizers = chunk.GetNativeArray(RandomizerType).Reinterpret <Random>();
            var entities    = chunk.GetNativeArray(EntityType);

            for (int i = 0; i < chunk.Count; i++)
            {
                if (randomizers[i].NextFloat(0f, 1f) < Aggression && Enemies.Length > 0)
                {
                    var target = Enemies[randomizers[i].NextInt(0, Enemies.Length)];
                    CommandBuffer.AddComponent(chunkIndex, entities[i], new CTarget {
                        Value = target
                    });
                    CommandBuffer.AddComponent(chunkIndex, entities[i], new TEnemyTarget {
                    });
                }
                else if (Resources.Length > 0)
                {
                    var target      = Resources[randomizers[i].NextInt(0, Resources.Length)];
                    var targetIdx2D = ResourceGridIndex[target].Value;
                    var targetIdx   = targetIdx2D.y * GridCellCount[GridEntity].Value.x + targetIdx2D.x;
                    if (ResourceStackHeight[target].Value == GridStackHeights[GridEntity][targetIdx].Value - 1)
                    {
                        CommandBuffer.AddComponent(chunkIndex, entities[i], new CTarget {
                            Value = target
                        });
                        CommandBuffer.AddComponent(chunkIndex, entities[i], new TResourceTarget {
                        });
                    }
                }
            }
        }
Exemple #2
0
 public static void SetParent(this EntityCommandBuffer.ParallelWriter entityCommandBuffer, int jobIndex, Entity parent, Entity child)
 {
     entityCommandBuffer.AddComponent(jobIndex, child, new Parent {
         Value = parent
     });
     entityCommandBuffer.AddComponent(jobIndex, child, new LocalToParent());
 }
Exemple #3
0
 protected override void OnUpdate()
 {
     if (ToParallelLooseCordon)
     {
         //float spacing = LineSpacing;
         //float width = LineWidth;
         EntityCommandBuffer.ParallelWriter commandBuffer = commandBufferSystem.CreateCommandBuffer().AsParallelWriter(); // create a command buffer
         JobHandle cordonHandle = Entities
                                  .WithAll <PoliceUnitComponent, SelectedPoliceUnit>()                                    // if police units are selected
                                  .ForEach((Entity policeUnit, int entityInQueryIndex, ref DynamicBuffer <OfficerInFormation> inFormation, in PoliceUnitDimensions dimensions, in DynamicBuffer <OfficerInPoliceUnit> officers) => {
             for (int i = 0; i < officers.Length; i++)
             {
                 //Debug.Log("Changing : " + i +"!");
                 commandBuffer.AddComponent <ToParallelCordonFormComponent>(entityInQueryIndex, officers[i].officer, new ToParallelCordonFormComponent {
                     LineSpacing        = dimensions.LineSpacing,
                     OfficerLength      = dimensions.OfficerLength,
                     OfficerWidth       = dimensions.OfficerWidth,
                     OfficerSpacing     = LooseCordonOfficerSpacing,
                     NumOfficersInLine1 = dimensions.NumOfficersInLine1,
                     NumOfficersInLine2 = dimensions.NumOfficersInLine2,
                     NumOfficersInLine3 = dimensions.NumOfficersInLine3
                 });         // Add component to change to cordon
             }
             inFormation.Clear();
             commandBuffer.AddComponent <PoliceUnitGettingIntoFormation>(entityInQueryIndex, policeUnit, new PoliceUnitGettingIntoFormation {
             });
         }).Schedule(this.Dependency);
        // Command Buffer Variants

        /// <summary>
        /// Adds a Parent and LocalToParent to the given child entity
        /// </summary>
        /// <param name="entityManager"></param>
        /// <param name="child"></param>
        /// <param name="parent"></param>
        public static void AddParent(EntityCommandBuffer.ParallelWriter commandBuffer, int jobIndex, Entity child, Entity parent)
        {
            commandBuffer.AddComponent(jobIndex, child, new Parent {
                Value = parent
            });
            commandBuffer.AddComponent(jobIndex, child, new LocalToParent());
        }
            public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
            {
                bool hasTweenBuffer = chunk.Has(TweenBufferType);
                bool hasTargetType  = chunk.Has(TargetType);

                NativeArray <Entity>        entities = chunk.GetNativeArray(EntityType);
                NativeArray <TTweenCommand> commands = chunk.GetNativeArray(TweenCommandType);

                for (int i = 0; i < entities.Length; i++)
                {
                    Entity        entity  = entities[i];
                    TTweenCommand command = commands[i];

                    if (!hasTweenBuffer)
                    {
                        ParallelWriter.AddBuffer <TweenState>(chunkIndex, entity);
                        break;
                    }

                    if (!hasTargetType)
                    {
                        ParallelWriter.AddComponent <TTarget>(chunkIndex, entity);
                    }

                    TweenState tween = new TweenState(command.GetTweenParams(), ElapsedTime, chunkIndex, TweenInfoTypeIndex);
                    ParallelWriter.AppendToBuffer(chunkIndex, entity, tween);

                    TTweenInfo info = new TTweenInfo();
                    info.SetTweenId(tween.Id);
                    info.SetTweenInfo(command.GetTweenStart(), command.GetTweenEnd());
                    ParallelWriter.AddComponent(chunkIndex, entity, info);

                    ParallelWriter.RemoveComponent <TTweenCommand>(chunkIndex, entity);
                }
            }
        static void HandleCompletePath(ComponentDataFromEntity <LocalToWorld> localToWorldFromEntity, Entity entity, Rotation rotation, ref NavAgent agent, Parent surface, Translation translation, PhysicsWorld physicsWorld, float elapsedSeconds, EntityCommandBuffer.ParallelWriter commandBuffer, int entityInQueryIndex, NavSettings settings)
        {
            var rayInput = new RaycastInput
            {
                Start  = localToWorldFromEntity[entity].Position + agent.Offset,
                End    = math.forward(rotation.Value) * settings.ObstacleRaycastDistanceMax,
                Filter = new CollisionFilter
                {
                    BelongsTo    = NavUtil.ToBitMask(settings.ColliderLayer),
                    CollidesWith = NavUtil.ToBitMask(settings.ObstacleLayer)
                }
            };

            if (
                !surface.Value.Equals(agent.DestinationSurface) &&
                !NavUtil.ApproxEquals(translation.Value, agent.LocalDestination, settings.StoppingDistance) &&
                !physicsWorld.CastRay(rayInput, out _)
                )
            {
                agent.JumpSeconds = elapsedSeconds;

                commandBuffer.RemoveComponent <NavWalking>(entityInQueryIndex, entity);
                commandBuffer.RemoveComponent <NavSteering>(entityInQueryIndex, entity);
                commandBuffer.AddComponent <NavJumping>(entityInQueryIndex, entity);
                commandBuffer.AddComponent <NavPlanning>(entityInQueryIndex, entity);

                return;
            }

            commandBuffer.RemoveComponent <NavWalking>(entityInQueryIndex, entity);
            commandBuffer.RemoveComponent <NavSteering>(entityInQueryIndex, entity);
            commandBuffer.RemoveComponent <NavDestination>(entityInQueryIndex, entity);
        }
Exemple #7
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity> entityArray = chunk.GetNativeArray(entityType);
            NativeArray <HasReynoldsSeekTargetPos> reynoldsArray = chunk.GetNativeArray(reynoldsType);
            NativeArray <GoHomeAction>             goHomeArray   = chunk.GetNativeArray(goHomeType);
            NativeArray <Translation> transArray    = chunk.GetNativeArray(translationType);
            BufferAccessor <Action>   actionBuffers = chunk.GetBufferAccessor <Action>(actionBufferType);



            for (int i = 0; i < chunk.Count; i++)
            {
                Entity entity = entityArray[i];
                DynamicBuffer <Action>   actions = actionBuffers[i];
                HasReynoldsSeekTargetPos seek    = reynoldsArray[i];
                GoHomeAction             data    = goHomeArray[i];
                Translation trans = transArray[i];

                //Debug.Log("Something? " + copy.Value);


                if (actions.Length > 0)                                             //if there are actions
                {
                    if (actions[0].id == data.id)                                   //if the current action is the same as the action in the first position
                    {
                        if (math.distance(trans.Value, seek.targetPos) < tolerance) // if the entity is within tolerance of the home point
                        //Remove the entity from the simulation (the crowd agent is going home)
                        {
                            Debug.Log("Going home!");
                            // 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++){
                             *  entityCommandBuffer.DestroyEntity(chunkIndex,actions[j].dataHolder);
                             * }
                             * entityCommandBuffer.DestroyEntity(chunkIndex, entity); // remove the crowd agent*/
                            entityCommandBuffer.AddComponent <CrowdToDelete>(chunkIndex, entity, new CrowdToDelete {
                            });
                        }
                    }
                    else  // if there are actions but this action is not the right one
                    {
                        Debug.Log("Gotta change from going home!");
                        //If there were data to store, this would be the point to do it
                        entityCommandBuffer.RemoveComponent <HasReynoldsSeekTargetPos>(chunkIndex, entity); // remove the seek target pos from the crowd agent
                        entityCommandBuffer.RemoveComponent <GoHomeAction>(chunkIndex, entity);             // remove the going home action from the crowd agent
                        entityCommandBuffer.AddComponent <ChangeAction>(chunkIndex, entity, new ChangeAction {
                        });                                                                                 //signify that the action should be changed
                    }
                }
                else  // if there are no actions in the action queue
                {
                    Debug.Log("Nothin left!");
                    entityCommandBuffer.RemoveComponent <HasReynoldsSeekTargetPos>(chunkIndex, entity); // remove the seek target pos from the crowd agent
                    entityCommandBuffer.RemoveComponent <GoHomeAction>(chunkIndex, entity);             // remove the going home action from the crowd agent
                    entityCommandBuffer.AddComponent <ChangeAction>(chunkIndex, entity, new ChangeAction {
                    });                                                                                 //signify that the action should be changed (will remove action)
                }
            }
        }
            public void Execute(int i)
            {
                Entity populationEntity = na_populationEntities [i];

                ecbp.AddComponent <NNIsPreviousGenerationTag> (i, populationEntity);
                ecbp.AddComponent <NNIsFinishedTag> (i, populationEntity);
                ecbp.RemoveComponent <NNIsFirstGenerationTag> (i, populationEntity);
            }
            public void Execute(int i)
            {
                Entity populationEntity = na_populationEntities [i];

                // Also checks, incase is parent already.
                ecbp.AddComponent <NNIsPreviousGenerationTag> (i, populationEntity);
                ecbp.AddComponent <NNIsFinishedTag> (i, populationEntity);
            }
Exemple #10
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity> entityArray = chunk.GetNativeArray(entityType);
            NativeArray <ToParallelCordonFormComponent> pCordonArray    = chunk.GetNativeArray(pCordonType);
            NativeArray <PoliceOfficerNumber>           officerNumArray = chunk.GetNativeArray(officerNumType);
            NativeArray <PoliceOfficerPoliceLineNumber> lineNumArray    = chunk.GetNativeArray(lineNumType);

            for (int i = 0; i < chunk.Count; i++)
            {
                Entity entity = entityArray[i];
                ToParallelCordonFormComponent pCordon       = pCordonArray[i];
                PoliceOfficerNumber           officerNumber = officerNumArray[i];
                PoliceOfficerPoliceLineNumber lineNumber    = lineNumArray[i];

                int officersInLine;
                if (lineNumber.Value == 0)
                {
                    officersInLine = pCordon.NumOfficersInLine1;
                }
                else if (lineNumber.Value == 1)
                {
                    officersInLine = pCordon.NumOfficersInLine2;
                }
                else
                {
                    officersInLine = pCordon.NumOfficersInLine3;
                }

                float xLocation;
                float leftside;
                float xOffset;

                if (officersInLine % 2 == 1) // if there are an odd number of police officers
                {
                    leftside = -((officersInLine / 2) * pCordon.OfficerSpacing + (officersInLine / 2) * pCordon.OfficerWidth);
                }
                else  // if there are an even number of police officers
                {
                    leftside = -(((officersInLine / 2) - 0.5f) * pCordon.OfficerSpacing + (officersInLine / 2) * pCordon.OfficerWidth);
                }
                xOffset   = (officerNumber.Value + 0.5f) * pCordon.OfficerWidth + officerNumber.Value * pCordon.OfficerSpacing;
                xLocation = leftside + xOffset;

                float topPosition = 1.5f * pCordon.OfficerLength + pCordon.LineSpacing;
                float zOffset     = -(lineNumber.Value * pCordon.LineSpacing + (0.5f + lineNumber.Value) * pCordon.OfficerLength);
                float zLocation   = topPosition + zOffset;

                commandBuffer.AddComponent <FormationLocation>(chunkIndex, entity, new FormationLocation {
                    Value = new float3(xLocation, 0f, zLocation)
                });
                commandBuffer.AddComponent <FormationRotation>(chunkIndex, entity, new FormationRotation {
                    Value = quaternion.RotateY(math.radians(0)) // rotate to forward
                });
                commandBuffer.AddComponent <PoliceOfficerOutOfFormation>(chunkIndex, entity, new PoliceOfficerOutOfFormation {
                });
                commandBuffer.RemoveComponent <ToParallelCordonFormComponent>(chunkIndex, entity);
            }
        }
Exemple #11
0
    /// <summary>
    /// Used to add the components needed to be in the Idling State
    /// </summary>
    /// <param name="ecb">The ECB used to transition between states</param>
    /// <param name="e">The guard entity we are modifying</param>
    /// <param name="index"></param>
    public static void TransitionToIdle(EntityCommandBuffer.ParallelWriter ecb, Entity e, int index)
    {
        ecb.AddComponent(index, e, new IdleTimer {
            Value = 0.0f
        });
#if !UNITY_DISABLE_MANAGED_COMPONENTS
        ecb.AddComponent <IsInTransitionTag>(index, e);
#endif
    }
Exemple #12
0
    /// <summary>
    /// Used to add the components needed to be in the Patrolling State
    /// </summary>
    /// <param name="ecb">The ECB used to transition between states</param>
    /// <param name="e">The guard entity we are modifying</param>
    /// <param name="index">A unique index per-guard entity. Used by the ECB to deterministically sort operations.</param>
    /// <param name="waypointPosition">The position of the waypoint we are setting as our new TargetPosition.</param>
    public static void TransitionToPatrolling(EntityCommandBuffer.ParallelWriter ecb, Entity e, int index, float3 waypointPosition)
    {
        ecb.AddComponent(index, e, new TargetPosition {
            Value = waypointPosition
        });
#if !UNITY_DISABLE_MANAGED_COMPONENTS
        ecb.AddComponent <IsInTransitionTag>(index, e);
#endif
    }
 private static void SetupViewPart(int entityInQueryIndex, Entity entity, Entity parent, float4x4 localToParent, EntityCommandBuffer.ParallelWriter commandBuffer)
 {
     commandBuffer.AddComponent(entityInQueryIndex, entity, new Parent {
         Value = parent
     });
     commandBuffer.AddComponent(entityInQueryIndex, entity, new LocalToParent {
         Value = localToParent
     });;
     commandBuffer.AddComponent(entityInQueryIndex, entity, new ViewPart());
 }
Exemple #14
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity>        entityArray    = chunk.GetNativeArray(entityType);
            NativeArray <CurrentAction> curActionArray = chunk.GetNativeArray(curActionType);
            BufferAccessor <Action>     buffers        = chunk.GetBufferAccessor <Action>(actionBufferType);

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

                if (actions.Length > 0) //if there are actions, add another action
                {
                    Entity holder = actions[0].dataHolder;
                    current.id         = actions[0].id;
                    current.dataHolder = holder;
                    switch (actions[0].type)                                                                       // add a component based on what action has the highest priority
                    {
                    case ActionType.Follow_WayPoints:                                                              // if the action to add is a Follow waypoints action
                        entityCommandBuffer.AddComponent <FetchWayPoints>(chunkIndex, entity, new FetchWayPoints { // tell the system to fetch the waypoints for the action
                            id         = actions[0].id,
                            dataHolder = holder
                        });
                        current.type = ActionType.Follow_WayPoints;
                        //Debug.Log("Changing to Action " + actions[0].id + "!");
                        break;

                    case ActionType.Go_Home:
                        entityCommandBuffer.AddComponent <FetchGoHomeData>(chunkIndex, entity, new FetchGoHomeData {   // tell the system to fetch the go home data for the action
                            id         = actions[0].id,
                            dataHolder = holder
                        });
                        current.type = ActionType.Go_Home;
                        //Debug.Log("Changing to Action " + actions[0].id + "!");
                        break;

                    case ActionType.Go_And_Wait:
                        entityCommandBuffer.AddComponent <FetchGoToAndWaitData>(chunkIndex, entity, new FetchGoToAndWaitData {   // tell the system to fetch the go home data for the action
                            id         = actions[0].id,
                            dataHolder = holder
                        });
                        current.type = ActionType.Go_And_Wait;
                        //Debug.Log("Changing to Action " + actions[0].id + "!");
                        break;
                    }
                }
                else                                                                    // if there are no more actions to do
                {
                    current.id   = -1;                                                  // set id to a nonsense value
                    current.type = ActionType.No_Action;                                // Tell the system that there is no current action
                }
                entityCommandBuffer.RemoveComponent <ChangeAction>(chunkIndex, entity); // remove this component to show that there is no need to change the action anymore
            }
        }
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity> entityArray = chunk.GetNativeArray(entityType);
            NativeArray <ToWedgeFormComponent>          wedgeArray      = chunk.GetNativeArray(wedgeType);
            NativeArray <PoliceOfficerNumber>           officerNumArray = chunk.GetNativeArray(officerNumType);
            NativeArray <PoliceOfficerPoliceLineNumber> lineNumArray    = chunk.GetNativeArray(lineNumType);

            for (int i = 0; i < chunk.Count; i++)
            {
                Entity entity = entityArray[i];
                ToWedgeFormComponent          wedge         = wedgeArray[i];
                PoliceOfficerNumber           officerNumber = officerNumArray[i];
                PoliceOfficerPoliceLineNumber lineNumber    = lineNumArray[i];

                int officerNumInUnit = 1;

                if (lineNumber.Value == 0) // if in the first line
                {
                    officerNumInUnit += officerNumber.Value;
                }
                else if (lineNumber.Value == 1) // if in the second line
                {
                    officerNumInUnit += officerNumber.Value + wedge.NumOfficersInLine1;
                }
                else   // if in the third line
                {
                    officerNumInUnit += officerNumber.Value + wedge.NumOfficersInLine1 + wedge.NumOfficersInLine2;
                }

                int relNumToFront = officerNumInUnit - wedge.MiddleOfficerNum;

                float frontOfficerZPos = ((float)wedge.MiddleOfficerNum / 2) * wedge.OfficerLength;
                float zOffset          = math.abs(relNumToFront) * wedge.OfficerLength;
                float zLocation        = frontOfficerZPos - zOffset;

                float xLocation = relNumToFront * wedge.OfficerLength * math.tan(math.radians(wedge.Angle / 2));

                quaternion formRot = quaternion.RotateY(math.radians(0));



                float3 formLocation = new float3(xLocation, 0f, zLocation);

                commandBuffer.AddComponent <FormationLocation>(chunkIndex, entity, new FormationLocation {
                    Value = formLocation
                });
                commandBuffer.AddComponent <FormationRotation>(chunkIndex, entity, new FormationRotation {
                    Value = formRot
                });
                commandBuffer.AddComponent <PoliceOfficerOutOfFormation>(chunkIndex, entity, new PoliceOfficerOutOfFormation {
                });
                commandBuffer.RemoveComponent <ToWedgeFormComponent>(chunkIndex, entity);
            }
        }
Exemple #16
0
        static private void _ResetStates(ref VehicleControllsComponent controlls, ref VehicleVelocityComponent velocity, ref ShaderAlphaComponent alphaColor, ref EntityCommandBuffer.ParallelWriter ecbp, int entityInQueryIndex, Entity entity)
        {
            controlls.f_steering    = 0;
            controlls.f_throtle     = 0;
            velocity.f3_speed       = 0;
            velocity.f_acceleration = 0;
            alphaColor.f            = 0.2f;

            ecbp.AddComponent <NNIsFinishedTag> (entityInQueryIndex, entity);

            // This is required, to eliminate continous collidion detection and prevent BuildpPhysicsWorld system, from creating NativeArray memory leaks.
            ecbp.AddComponent <Unity.Physics.PhysicsExclude> (entityInQueryIndex, entity);
        }
Exemple #17
0
            public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
            {
                var entities      = chunk.GetNativeArray(EntityType);
                var renderBuffers = chunk.GetBufferAccessor(RenderBufferType);

                if (chunk.Has(DisableRenderingType))
                {
                    for (int i = 0; i < chunk.Count; i++)
                    {
                        var entity         = entities[i];
                        var renderElements = renderBuffers[i].AsNativeArray();
                        var rootVertices   = new NativeList <RootVertexData>(Allocator.Temp);
                        ConsolidateRenderElements(renderElements, ref rootVertices);

                        var rootBuffer = CmdBuffer.SetBuffer <RootVertexData>(chunkIndex, entity);
                        rootBuffer.ResizeUninitialized(rootVertices.Length);

                        UnsafeUtility.MemCpy(rootBuffer.GetUnsafePtr(), rootVertices.GetUnsafePtr(),
                                             UnsafeUtility.SizeOf <RootVertexData>() * rootVertices.Length);

                        rootVertices.Dispose();

                        CmdBuffer.RemoveComponent <DisableRenderingTag>(chunkIndex, entity);
                        CmdBuffer.AddComponent <BatchCanvasTag>(chunkIndex, entity);
                    }
                }

                if (chunk.Has(UpdateVertexType))
                {
                    for (int i = 0; i < chunk.Count; i++)
                    {
                        var entity         = entities[i];
                        var renderElements = renderBuffers[i].AsNativeArray();
                        var rootVertices   = new NativeList <RootVertexData>(Allocator.Temp);
                        ConsolidateRenderElements(renderElements, ref rootVertices);

                        var rootBuffer = CmdBuffer.SetBuffer <RootVertexData>(chunkIndex, entity);
                        rootBuffer.ResizeUninitialized(rootVertices.Length);

                        UnsafeUtility.MemCpy(rootBuffer.GetUnsafePtr(), rootVertices.GetUnsafePtr(),
                                             UnsafeUtility.SizeOf <RootVertexData>() * rootVertices.Length);

                        rootVertices.Dispose();

                        CmdBuffer.RemoveComponent <UpdateVertexColorTag>(chunkIndex, entity);
                        CmdBuffer.AddComponent <BuildCanvasTag>(chunkIndex, entity);
                    }
                }
            }
Exemple #18
0
 //Returns true if entity is already on location, false if it is not
 private static bool GoToLocation(Entity location, Entity movedEntity, ComponentDataFromEntity <CurrentLocationComponent> currentLocationData,
                                  ComponentDataFromEntity <ExchangeTaskLocationComponent> exchangeTaskLocationData, EntityCommandBuffer.ParallelWriter ecb, int entityInQueryIndex)
 {
     if (location == movedEntity)
     {
         return(true);
     }
     if (!currentLocationData.HasComponent(movedEntity) || !(currentLocationData[movedEntity].entity == location))
     {
         var exchangeTaskLocation = new ExchangeTaskLocationComponent {
             Entity = location
         };
         if (exchangeTaskLocationData.HasComponent(movedEntity))
         {
             exchangeTaskLocationData[movedEntity] = exchangeTaskLocation;
         }
         else
         {
             ecb.AddComponent(entityInQueryIndex, movedEntity, exchangeTaskLocation);
         }
         return(false);
     }
     else
     {
         return(true);
     }
 }
        public static void Execute(NativeArray <byte> inputData, ComponentType componentType, int typeSize, NativeArray <Entity> entityArray,
                                   NativeArray <PersistenceState> persistenceStateArray, EntityCommandBuffer.ParallelWriter ecb, int batchIndex)
        {
            int totalElementSize = typeSize + PersistenceMetaData.SizeOfStruct;

            for (int i = 0; i < entityArray.Length; i++)
            {
                PersistenceState persistenceState = persistenceStateArray[i];
                int inputMetaByteIndex            = persistenceState.ArrayIndex * totalElementSize;
                int inputDataByteIndex            = inputMetaByteIndex + PersistenceMetaData.SizeOfStruct;

#if ENABLE_UNITY_COLLECTIONS_CHECKS
                if (persistenceState.ArrayIndex * totalElementSize >= inputData.Length)
                {
                    throw new IndexOutOfRangeException("AddMissingComponent:: persistenceState.ArrayIndex seems to be out of range. Or the totalElementSize is wrong.");
                }
#endif

                var metaData = UnsafeUtility.ReadArrayElementWithStride <PersistenceMetaData>(inputData.GetUnsafeReadOnlyPtr(), persistenceState.ArrayIndex, totalElementSize);

                if (metaData.AmountFound == 1)
                {
                    ecb.AddComponent(batchIndex, entityArray[i], componentType);
                    if (typeSize != 0)
                    {
                        ecb.SetComponent(batchIndex, entityArray[i], componentType, typeSize, inputData.GetSubArray(inputDataByteIndex, typeSize));
                    }
                }
            }
        }
Exemple #20
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            if (Enemies.Length == 0)
            {
                return;
            }

            var randomizers = chunk.GetNativeArray(RandomizerType).Reinterpret <Random>();
            var entities    = chunk.GetNativeArray(EntityType);

            for (int i = 0; i < chunk.Count; i++)
            {
                if (randomizers[i].NextFloat(0f, 1f) >= Aggression)
                {
                    continue;
                }

                var target = Enemies[randomizers[i].NextInt(0, Enemies.Length)];
                CommandBuffer.AddComponent(chunkIndex, entities[i], new CTarget {
                    Value = target
                });
                CommandBuffer.AddSharedComponent(chunkIndex, entities[i], new STargetType {
                    Value = TargetTypes.Enemy
                });
            }
        }
            public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
            {
                var entities           = chunk.GetNativeArray(EntityType);
                var vertexAccessor     = chunk.GetBufferAccessor(CanvasVertexType);
                var triangleAccessor   = chunk.GetBufferAccessor(CanvasIndexType);
                var batchedRenders     = chunk.GetBufferAccessor(RenderElementType);
                var batchedSpans       = chunk.GetBufferAccessor(SpanType);
                var submeshDescriptors = chunk.GetBufferAccessor(SubMeshType);

                for (int i = 0; i < chunk.Count; i++)
                {
                    var entity         = entities[i];
                    var rootVertices   = vertexAccessor[i];
                    var rootTriangles  = triangleAccessor[i];
                    var renderElements = batchedRenders[i].AsNativeArray();
                    var spans          = batchedSpans[i].AsNativeArray();
                    var submesh        = submeshDescriptors[i];

                    rootVertices.Clear();
                    rootTriangles.Clear();
                    submesh.Clear();

                    PopulateRootCanvas(in renderElements, in spans, ref rootVertices, ref rootTriangles, ref submesh);

                    // The canvas does not have to be rebatched.
                    CommandBuffer.RemoveComponent <BatchCanvasTag>(entity.Index, entity);
                    CommandBuffer.AddComponent <BuildCanvasTag>(entity.Index, entity);
                }
            }
Exemple #22
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            var entities     = chunk.GetNativeArray(EntityType);
            var translations = chunk.GetNativeArray(TranslationType);

            for (int i = 0; i < chunk.Count; i++)
            {
                var translation       = translations[i];
                var loopingChunkIndex = 127 % (chunkIndex + 1);
                var random            = Randoms[loopingChunkIndex];
                var end = random.NextInt2(new int2(0, 0), GridSize - 1);
                //var end = EndPos;
                Randoms[loopingChunkIndex] = random;
                ValidateGridPosition(GridSize, ref end);
                GetXY(OriginOffset, CellSize, translation.Value + OriginOffset * CellSize * 0.5f,
                      out int startX, out int startY);
                ValidateGridPosition(GridSize, ref startX, ref startY);
                CommandBuffer.AddComponent(chunkIndex, entities[i], new PathfindingParams()
                {
                    StartPosition = new int2(startX, startY),
                    EndPosition   = end
                });
                CommandBuffer.RemoveComponent <AwaitingOrder>(chunkIndex, entities[i]);
            }
        }
    protected override void OnUpdate()
    {
        EntityCommandBuffer.ParallelWriter commandBuffer = endSimulationEcbSystem.CreateCommandBuffer().AsParallelWriter();

        Entities
        .WithAll <PurpleGooCubeData>()
        .ForEach((Entity entity, int entityInQueryIndex, ref PurpleGooCubeData cubeData) => {
            if (cubeData.height <= 0)
            {
                //If cube height is zero or negative, move it out of the play area
                if (cubeData.active)
                {
                    cubeData.active = false;
                    commandBuffer.AddComponent <InactiveGooCubeTag>(entityInQueryIndex, entity);
                }
            }
            else
            {
                // Move it back to the play area otherwise (but only if still inactive)
                if (!cubeData.active)
                {
                    cubeData.active = true;
                    commandBuffer.RemoveComponent <InactiveGooCubeTag>(entityInQueryIndex, entity);
                }
            }
        }).ScheduleParallel();

        endSimulationEcbSystem.AddJobHandleForProducer(Dependency);
    }
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity>         entityArray = chunk.GetNativeArray(entityType);
            NativeArray <PoliceUnitName> nameArray   = chunk.GetNativeArray(nameType);

            if (chunk.Has(selectedType)) //if the chunk has police units that are selected
            {
                for (int i = 0; i < chunk.Count; i++)
                {
                    if (nameArray[i].String != selectedUnitName[0])                                     //if the name of the police unit that was selected is not the same as the police unit in question
                    {
                        commandBuffer.RemoveComponent <SelectedPoliceUnit>(chunkIndex, entityArray[i]); //deselect the police unit
                    }
                }
            }
            else  // if the chunk does not have selected police units
            {
                for (int i = 0; i < chunk.Count; i++)
                {
                    if (nameArray[i].String == selectedUnitName[0])                                  //if the name of the police unit that was selected is the same as the police unit in question
                    {
                        commandBuffer.AddComponent <SelectedPoliceUnit>(chunkIndex, entityArray[i]); //select the police unit
                    }
                }
            }
        }
Exemple #25
0
            public void Execute(int index)
            {
                var tree       = Keys[index];
                var enumerator = Operations.GetValuesForKey(tree);

                while (enumerator.MoveNext())
                {
                    var op = enumerator.Current;
                    switch (op.Type)
                    {
                    case TreeOperationType.Insert:
                    {
                        var id    = tree.CreateProxy(AABB.FromRadius(op.Pos, op.Radius), op.Agent);
                        var state = new ElementSystemStateComponent {
                            Id = id, PreviousPosition = op.Pos, TreeEntity = op.TreeEntity, TreeRef = tree
                        };
                        Ecb.AddComponent(index, op.Agent, state);
                        break;
                    }

                    case TreeOperationType.Move:
                    {
                        tree.MoveProxy(op.Id, AABB.FromRadius(op.Pos, op.Radius), op.Displacement);
                        break;
                    }

                    case TreeOperationType.Reinsert:
                    {
                        var id    = tree.CreateProxy(AABB.FromRadius(op.Pos, op.Radius), op.Agent);
                        var state = new ElementSystemStateComponent {
                            Id = id, PreviousPosition = op.Pos, TreeEntity = op.TreeEntity, TreeRef = tree
                        };
                        Ecb.AddComponent(index, op.Agent, state);
                        break;
                    }

                    case TreeOperationType.Destroy:
                    {
                        tree.DestroyProxy(op.Id);
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
Exemple #26
0
 protected override void OnUpdate()
 {
     EntityCommandBuffer.ParallelWriter ecb = entityCommandBuffer.CreateCommandBuffer().AsParallelWriter();
     Entities.WithNone <DisableRendering>().WithAll <TreeIntersectsRoadTag>().ForEach((Entity e, int entityInQueryIndex) =>
     {
         ecb.AddComponent <DisableRendering>(entityInQueryIndex, e);
     }).ScheduleParallel(Dependency).Complete();
 }
 public void Execute(Entity entity, int jobIndex, ref NetworkStreamConnection connection, [ReadOnly] ref NetworkStreamRequestDisconnect disconnect)
 {
     driver.Disconnect(connection.Value);
     commandBuffer.AddComponent(jobIndex, entity, new NetworkStreamDisconnected {
         Reason = disconnect.Reason
     });
     commandBuffer.RemoveComponent <NetworkStreamRequestDisconnect>(jobIndex, entity);
 }
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity> entityArray = chunk.GetNativeArray(entityType);

            for (int i = 0; i < chunk.Count; i++)
            {
                commandBuffer.AddComponent <SelectedPoliceUnit>(chunkIndex, entityArray[i]); //select the police unit
            }
        }
        public static NativeArray <Entity> GenerateEntities(EntityCommandBuffer.ParallelWriter ecb, int jobIndex, Entity proceduralAreaEntity, ProceduralGenerationSpawnData spawnData, Allocator allocator)
        {
            NativeArray <Entity> entities = new NativeArray <Entity>(spawnData.Amount, allocator);

            foreach (Entity entity in entities)
            {
                ecb.AddComponent(jobIndex, entity, new ProceduralGenerationElement(ecb, jobIndex, proceduralAreaEntity, spawnData.EntityPrefab.Entity));
            }
            return(entities);
        }
 /// <summary>
 ///
 /// </summary>
 public void Change(int motionIndex, bool isContinuous = true)
 {
     cmd.AddComponent(this.jobIndex, this.entity,
                      new Motion.InitializeData
     {
         MotionIndex  = motionIndex,
         IsContinuous = isContinuous,
     }
                      );
 }