예제 #1
0
        protected override void OnUpdate()
        {
            var ecb = endInitializationEcbSystem.CreateCommandBuffer();

            Entities
            .WithoutBurst()
            .WithNone <Bounds>()
            .ForEach((Entity entity, in Terrain terrain) =>
            {
                var shift = terrain.terrainData.size / 2;

                var bounds = new Bounds
                {
                    Value = new UnityEngine.Bounds
                    {
                        center  = terrain.GetPosition() + shift,
                        extents = terrain.terrainData.size
                    }
                };

                ecb.AddComponent(entity, bounds);
            }).Run();

            endInitializationEcbSystem.AddJobHandleForProducer(this.Dependency);
        }
예제 #2
0
    protected override void OnUpdate()
    {
        EntityCommandBuffer.Concurrent ecb = endInitializationECBSystem.CreateCommandBuffer().ToConcurrent();
        float deltaTime = UnityEngine.Time.deltaTime;

        Entities.ForEach((Entity entity, int entityInQueryIndex, ref SpawnerEntitiesCubes spawner, ref LocalToWorld localToWorld) =>
        {
            spawner.secondsToNextSpawn -= deltaTime;
            if (spawner.secondsToNextSpawn >= 0)
            {
                return;
            }                                                          //exit, no time to spawn yet

            //queue an instantiate command to the EntityCommandBuffer
            Entity prefabToSpawn      = (spawner.randomness.NextFloat() > 0.5f) ? spawner.redCubePrefab : spawner.blueCubePrefab;
            Entity instantiatedPrefab = ecb.Instantiate(entityInQueryIndex, prefabToSpawn);

            //queue a SetComponent command to position the newly created entity at the back of the scene
            float3 RandomOffset = spawner.randomness.NextFloat3Direction() * spawner.randomness.NextFloat() * spawner.spawnRadius; //random.NextFloat3Direction() gives a random unit-long vector3, and random.NextFloat() returns random float between 0 and 1
            ecb.SetComponent(entityInQueryIndex, instantiatedPrefab, new Translation
            {
                Value = new float3(localToWorld.Position.x + RandomOffset.x, -9, localToWorld.Position.z + RandomOffset.z)
            });

            //update the time to the next entity spawn
            spawner.secondsToNextSpawn += spawner.spawnFrequency;
        }).Schedule();
    }
예제 #3
0
    public override void UpdateSystem()
    {
        Dependency = JobHandle.CombineDependencies(Dependency, m_spawningQueueSystem.spawnQueueDependencies);

        EntityCommandBuffer       ecb        = m_entityCommandBuffer.CreateCommandBuffer();
        NativeQueue <Translation> spawnQueue = m_spawningQueueSystem.spawnQueue;

        Dependency = Entities.ForEach((ref RuntimePrefabData runtimePrefabData) =>
        {
            Translation translation;
            while (spawnQueue.TryDequeue(out translation))
            {
                Rotation rotation = GetComponent <Rotation>(runtimePrefabData.aiDrone);

                Entity e = ecb.Instantiate(runtimePrefabData.aiDrone);

                ecb.SetComponent(e, translation);
                ecb.SetComponent(e, new LocalToWorld {
                    Value = new float4x4(rotation.Value, translation.Value)
                });
            }
        }).Schedule(Dependency);

        m_entityCommandBuffer.AddJobHandleForProducer(Dependency);
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        GlobalData gd = util.GetGlobalData();

        if (!gd)
        {
            Debug.LogError("NO GLOBAL DATA");
        }
        else
        {
            throwCurve = gd.armThrowingCurve;
        }

        var handle = inputDeps;

        var job = new ArmAnimationJob()
        {
            worldTime                = Time.time,
            matrixBufferLookup       = GetBufferFromEntity <ArmMatrixBuffer>(),
            armChainsBufferLookup    = GetBufferFromEntity <ArmChainsBuffer>(),
            fingerChainsBufferLookup = GetBufferFromEntity <FingerChainsBuffer>(),
            thumbChainsBufferLookup  = GetBufferFromEntity <ThumbChainsBuffer>(),
            ecb = ecbSystem.CreateCommandBuffer().ToConcurrent()
        };

        handle = job.Schedule(this, inputDeps);
        ecbSystem.AddJobHandleForProducer(handle);
        return(handle);
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            Debug.Log("Remove Octree Instance.");

            // int i_groupLength = group.CalculateLength () ;

            JobHandle removeInstanceJobHandle = new RemoveInstanceJob
            {
                // a_octreeEntities                    = group.GetEntityArray (),

                // Contains a list of instances to add, with its properties.
                // removeInstanceBufferElement         = GetBufferFromEntity <RemoveInstanceBufferElement> (),

                a_rootNodeData = GetComponentDataFromEntity <RootNodeData> (),

                nodeSparesBufferElement          = GetBufferFromEntity <NodeSparesBufferElement> (),
                nodeBufferElement                = GetBufferFromEntity <NodeBufferElement> (),
                nodeInstancesIndexBufferElement  = GetBufferFromEntity <NodeInstancesIndexBufferElement> (),
                nodeChildrenBufferElement        = GetBufferFromEntity <NodeChildrenBufferElement> (),
                instanceBufferElement            = GetBufferFromEntity <InstanceBufferElement> (),
                instancesSpareIndexBufferElement = GetBufferFromEntity <InstancesSpareIndexBufferElement> ()
            }.Schedule(group, inputDeps);



            JobHandle completeRemoveInstanceJobHandle = new CompleteRemoveInstanceJob
            {
                ecb = eiecb.CreateCommandBuffer().ToConcurrent(),
                // a_octreeEntities                 = group.GetEntityArray ()
            }.Schedule(group, removeInstanceJobHandle);

            eiecb.AddJobHandleForProducer(completeRemoveInstanceJobHandle);

            return(completeRemoveInstanceJobHandle);
        }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var transforms = m_InitialTransformGroup.GetTransformAccessArray();
            var entities   = m_InitialTransformGroup.ToEntityArray(Allocator.TempJob);

            var transformStashes   = new NativeArray <TransformStash>(transforms.length, Allocator.TempJob);
            var stashTransformsJob = new StashTransforms
            {
                transformStashes = transformStashes
            };

            var stashTransformsJobHandle = stashTransformsJob.Schedule(transforms, inputDeps);

            var copyTransformsJob = new CopyTransforms
            {
                transformStashes = transformStashes,
            };

            var copyTransformsJobHandle = copyTransformsJob.Schedule(m_InitialTransformGroup, stashTransformsJobHandle);

            var removeComponentsJob = new RemoveCopyInitialTransformFromGameObjectComponent
            {
                entities            = entities,
                entityCommandBuffer = m_EntityCommandBufferSystem.CreateCommandBuffer()
            };
            var removeComponentsJobHandle = removeComponentsJob.Schedule(copyTransformsJobHandle);

            m_EntityCommandBufferSystem.AddJobHandleForProducer(removeComponentsJobHandle);
            return(removeComponentsJobHandle);
        }
예제 #7
0
        protected override void OnUpdate()
        {
            var commandBuffer = m_EndInitializationEcbSystem.CreateCommandBuffer().ToConcurrent();

            var grid          = worldGridSystem.Grid;
            var occupiedCells = worldGridSystem.OccupiedCells;
            var blockedCells  = worldGridSystem.BlockedCells;

            Entities
            .WithNone <OccupyingCell>()
            .ForEach((Entity entity, int entityInQueryIndex,
                      in CellOccupant occupant, in Translation position) =>
            {
                int2 gridPos = grid.GetGridPosition(position.Value);
                int index    = grid.GetCellIndex(gridPos);

                if (occupiedCells[index])
                {
                    return;                           // Already occupied
                }
                occupiedCells[index] = true;
                blockedCells[index]  = occupant.BlocksMovement;

                commandBuffer.AddComponent(entityInQueryIndex, entity, new OccupyingCell
                {
                    Value = gridPos
                });
            }).ScheduleParallel();
        protected override void OnUpdate( )
        {
            var commandBuffer = m_barrier.CreateCommandBuffer( );

            var networkId = GetSingleton <NetworkIdComponent>( ).Value;

            Entities.ForEach((Entity ent, ref DynamicBuffer <PhysicsSnapshotBufferElement> snapshots, in SimulationBodyOwner bodyOwner) =>
            {
                var doesClientHaveAuthorityFlagAssignedToEntity = HasComponent <HasAuthorityOverPhysicsBody>(ent);
                var shouldHaveFlagAssigned = bodyOwner.Value == networkId;

                if (shouldHaveFlagAssigned && !doesClientHaveAuthorityFlagAssignedToEntity)
                {
                    commandBuffer.AddComponent <HasAuthorityOverPhysicsBody>(ent);
                }
                if (!shouldHaveFlagAssigned && doesClientHaveAuthorityFlagAssignedToEntity)
                {
                    commandBuffer.RemoveComponent <HasAuthorityOverPhysicsBody>(ent);
                    snapshots.Clear( );
                }
            }).Schedule( );

            commandBuffer.RemoveComponent <HasAuthorityOverPhysicsBody>(m_bodiesWithoutOwnerComponent);

            m_barrier.AddJobHandleForProducer(Dependency);
        }
예제 #9
0
 private void RemapBuffers(NativeArray <Entity> .Enumerator enumerator)
 {
     while (enumerator.MoveNext())
     {
         Entity entity = enumerator.Current;
         ProcessEntity(entity, m_EndInitializationEntityCommandBufferSystem.CreateCommandBuffer());
     }
 }
    protected override JobHandle OnUpdate(JobHandle inputDependencies)
    {
        //shared ECB between all jobs
        EntityCommandBuffer.Concurrent ecb = endInitECBSystem.CreateCommandBuffer().ToConcurrent();

        //Job 1
        //First we run through all the enemies finding the closest player (generally there's only one).
        //We prepare 2 NativeArrays: a reference to the players, and to their positions. This way enemies can run distance checks and note down which Entity is the closest player.
        NativeArray <Entity>      players         = playersGroup.ToEntityArray(Allocator.TempJob, out JobHandle handle1);
        NativeArray <Translation> playerPositions = playersGroup.ToComponentDataArray <Translation>(Allocator.TempJob, out JobHandle handle2);

        //This code is running on the main thread but the 2 NativeArrays above are fetched in a job.
        //This is why we combine the dependencies and pass them all to the job when we schedule it (see below), to ensure that all the data is ready at the moment the job is launched.
        //For more info: https://gametorrahod.com/minimum-main-thread-block-with-out-jobhandle-overload/ (first section)
        JobHandle newInputDependencies = JobHandle.CombineDependencies(inputDependencies, handle1, handle2);

        var job1 = new FindClosestPlayerJob()
        {
            players   = players,
            positions = playerPositions,
            ECB       = ecb,
        };

        JobHandle job1Handle = job1.Schedule(this, newInputDependencies);

        //Job 2
        //Now iterating through the players (only one) finding the closest enemy.
        //We prepare the NativeArrays like in the job above.
        NativeArray <Entity>      enemies        = enemyGroup.ToEntityArray(Allocator.TempJob, out JobHandle handle3);
        NativeArray <Translation> enemyPositions = enemyGroup.ToComponentDataArray <Translation>(Allocator.TempJob, out JobHandle handle4);

        //Again, we combine dependencies to make sure that job1 is run as well as the fetching of the 2 NativeArrays, before running job2
        JobHandle job1Dependencies = JobHandle.CombineDependencies(job1Handle, handle3, handle4);

        var job2 = new FindClosestEnemyJob()
        {
            enemies   = enemies,
            positions = enemyPositions,
            ECB       = ecb,
        };

        JobHandle job2Handle = job2.Schedule(this, job1Dependencies);

        endInitECBSystem.AddJobHandleForProducer(job2Handle);

        //Job 3
        //All characters already with a Target but not currently dealing an attack, check if the target is still in range or dead.
        var job3 = new CheckIfTargetValidJob()
        {
            ECB = ecb,
            targetTranslations = GetComponentDataFromEntity <Translation>(true),
        };
        JobHandle job3Handle = job3.Schedule(this, job2Handle);

        endInitECBSystem.AddJobHandleForProducer(job3Handle);

        return(job3Handle);
    }
예제 #11
0
        protected override void OnUpdate()
        {
            GenerateRegionHeightMapSettings settings = GenerateRegionHeightMapSettings.Default;
            var settingsUI = GameObject.FindObjectOfType <MapGenerationSettingsUI>();

            if (settingsUI != null)
            {
                settings = settingsUI.Settings;
            }

            var ecb = _barrier.CreateCommandBuffer().ToConcurrent();

            var regionArchetype = _regionArchetype;

            NativeList <int2> loadedPoints = new NativeList <int2>(100, Allocator.TempJob);

            int range = GameObject.FindObjectOfType <MapGenerationSettingsUI>()._range;

            // Assign region loader indices
            Entities
            .ForEach((ref RegionLoader loader, in Translation t) =>
            {
                loader.regionIndex = (int2)math.floor(t.Value.xz / Constants.ChunkSize.xz);
                GetPointsInRange(loader.regionIndex, loadedPoints, range);
            }).Schedule();

            Entities
            .WithAll <Region>()
            .ForEach((int entityInQueryIndex, Entity e, in RegionIndex regionIndexComp,
                      in DynamicBuffer <LinkedEntityGroup> linkedGroup) =>
            {
                // Remove any currently loaded regions from the list
                int2 regionIndex = regionIndexComp;
                for (int i = loadedPoints.Length - 1; i >= 0; --i)
                {
                    int2 p = loadedPoints[i];
                    if (regionIndex.x == p.x && regionIndex.y == p.y)
                    {
                        loadedPoints.RemoveAtSwapBack(i);
                        return;
                    }
                }

                // Any regions not in our loaded list can be unloaded/destroyed
                // Note that "LinkedEntityGroup" only destroys linked entities automatically if
                // the root entity is destroyed via an entity query, so we do it manually here.
                for (int i = 0; i < linkedGroup.Length; ++i)
                {
                    ecb.DestroyEntity(entityInQueryIndex, linkedGroup[i].Value);
                }
                ecb.DestroyEntity(entityInQueryIndex, e);
            }).Schedule();
예제 #12
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var commandBuffer = _cbSystem.CreateCommandBuffer();
            var job           = new UpdateUIDataJob
            {
                commands = commandBuffer.ToConcurrent()
            };

            inputDeps = job.Schedule(this, inputDeps);
            _cbSystem.AddJobHandleForProducer(inputDeps);

            return(inputDeps);
        }
        protected override void OnUpdate( )
        {
            var commandBuffer = m_barrier.CreateCommandBuffer( );

            Entities.WithAll <HasAuthorityOverPhysicsBody, ShouldSimulatePhysicsBody>( ).ForEach((in PhysicsBodyReference reference, in PhysicsBodyVelocity velocity) =>
            {
                if (HasComponent <PhysicsVelocity>(reference.Value))
                {
                    return;
                }

                commandBuffer.AddComponent(reference.Value, velocity.Value);
            }).Schedule( );
        protected override void OnUpdate()
        {
            var shader = World.GetExistingSystem <SpriteRendererSubmitSystem>().DefaultShader;

            if (!shader.IsInitialized)
            {
                return;
            }

            var cmd = m_Barrier.CreateCommandBuffer();

            Dependency = Entities
                         .WithName("CreateMesh2D")
                         .WithoutBurst()
                         .WithNone <SpriteMeshBuffers>()
                         .ForEach((Entity entity, in Sprite sprite) =>
            {
                var blob        = sprite.Mesh;
                var indexCount  = blob.Value.Indices.Length;
                var vertexCount = blob.Value.Vertices.Length;

                unsafe
                {
                    cmd.AddComponent(entity, new SpriteMeshBuffers
                    {
                        IndexCount         = indexCount,
                        VertexCount        = vertexCount,
                        VertexLayoutHandle = shader.LayoutHandle,
                        IndexBufferHandle  = bgfx.create_index_buffer(RendererBGFXStatic.CreateMemoryBlock((byte *)blob.Value.Indices.GetUnsafePtr(), indexCount * 2), (ushort)bgfx.BufferFlags.None).idx,
                        VertexBufferHandle = bgfx.create_vertex_buffer(RendererBGFXStatic.CreateMemoryBlock((byte *)blob.Value.Vertices.GetUnsafePtr(), vertexCount * sizeof(SpriteVertex)), (bgfx.VertexLayout *)shader.VertexLayout.GetUnsafeReadOnlyPtr(), (ushort)bgfx.BufferFlags.None).idx
                    });
                }
            }).Schedule(Dependency);

            Dependency = Entities
                         .WithName("RemoveMesh2D")
                         .WithoutBurst()
                         .WithNone <Sprite>()
                         .ForEach((Entity entity, in SpriteMeshBuffers mesh) =>
            {
                bgfx.destroy_index_buffer(new bgfx.IndexBufferHandle {
                    idx = mesh.IndexBufferHandle
                });
                bgfx.destroy_vertex_buffer(new bgfx.VertexBufferHandle {
                    idx = mesh.VertexBufferHandle
                });
                cmd.RemoveComponent(entity, typeof(SpriteMeshBuffers));
            }).Schedule(Dependency);

            m_Barrier.AddJobHandleForProducer(Dependency);
        }
        protected override void OnUpdate( )
        {
            var commandBuffer = m_barrier.CreateCommandBuffer( );

            commandBuffer.AddComponent <HasAuthorityOverPhysicsBody>(m_bodiesWithoutOwnerComponent);

            var networkIds = GetEntityQuery(typeof(NetworkIdComponent));

            var validOwnerIds = new NativeHashSet <int>(networkIds.CalculateEntityCount( ), Allocator.TempJob);

            Entities.ForEach((in NetworkIdComponent networkIdComponent) =>
            {
                validOwnerIds.Add(networkIdComponent.Value);
            }).Schedule( );
예제 #16
0
        protected override void OnUpdate()
        {
            var ecb          = _endInitializationEntityCommandBufferSystem.CreateCommandBuffer();
            var spawnerQuery = EntityManager.CreateEntityQuery(typeof(EntitySpawnData));

            if (Input.GetKeyDown(KeyCode.Y))
            {
                ecb.AddComponent <ShouldSpawnTag>(spawnerQuery);
            }

            if (Input.GetKeyDown(KeyCode.N))
            {
                ecb.RemoveComponent <ShouldSpawnTag>(spawnerQuery);
            }
        }
예제 #17
0
    public override void UpdateSystem()
    {
        EntityCommandBuffer.ParallelWriter ecb = m_entityCommandBuffer.CreateCommandBuffer().AsParallelWriter();

        JobHandle freezeRotationJobHandle = Entities.ForEach((Entity entity, int entityInQueryIndex, ref PhysicsMass physicsMass, in FreezeRotation freezeRotation) =>
        {
            physicsMass.InverseInertia[0] = freezeRotation.x ? 0 : physicsMass.InverseInertia[0];
            physicsMass.InverseInertia[1] = freezeRotation.y ? 0 : physicsMass.InverseInertia[1];
            physicsMass.InverseInertia[2] = freezeRotation.z ? 0 : physicsMass.InverseInertia[2];

            ecb.RemoveComponent <FreezeRotation>(entityInQueryIndex, entity);
        }).Schedule(Dependency);

        m_entityCommandBuffer.AddJobHandleForProducer(freezeRotationJobHandle);
        Dependency = freezeRotationJobHandle;
    }
예제 #18
0
    protected override void OnUpdate()
    {
        var cmdBuffer = _cmdBufferSystem.CreateCommandBuffer();
        var deltaTime = Time.DeltaTime;

        Entities
        .ForEach((ref TestSpawnerData spawner) =>
        {
            spawner.SpawnTimer -= deltaTime;
            if (spawner.SpawnTimer <= 0)
            {
                spawner.SpawnTimer += spawner.SpawnCooldown;
                cmdBuffer.Instantiate(spawner.Prefab);
            }
        }).Run();
    }
예제 #19
0
    protected override void OnUpdate()
    {
        var buffer = mCommandBufferSystem.CreateCommandBuffer();

        Entities
        .WithAll <TInitRandomizer>()
        .ForEach((Entity e) =>
        {
            var randomizer = new CRandomizer {
                Value = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(1, int.MaxValue))
            };
            buffer.AddComponent(e, randomizer);
            buffer.RemoveComponent <TInitRandomizer>(e);
        })
        .Run();

        mCommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
예제 #20
0
        protected override JobHandle OnUpdate(JobHandle jobHandle)
        {
            var random        = Random;
            var commandBuffer = commandBufferSystem.CreateCommandBuffer().ToConcurrent();

            jobHandle = Entities
                        .WithNone <AnimationTimeMutator>()
                        .ForEach((Entity entity, int entityInQueryIndex, ref AnimationTimeMutatorRange range) =>
            {
                commandBuffer.AddComponent(entityInQueryIndex, entity,
                                           new AnimationTimeMutator {
                    Value = random.NextFloat(range.Min, range.Max)
                });
            })
                        .Schedule(jobHandle);
            commandBufferSystem.AddJobHandleForProducer(jobHandle);
            return(jobHandle);
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var handle = inputDeps;

        Entities.WithStructuralChanges().WithoutBurst().ForEach((Entity entity, in TerrainGenerator g) =>
        {
            for (int x = 0; x < g.X; x++)
            {
                handle = JobHandle.CombineDependencies(new J {
                    xMax = g.X, yMax = g.Y, Archetype = _archetype, Buffer = _barrier.CreateCommandBuffer().ToConcurrent()
                }.Schedule(g.X * g.Y * g.Z, 128, handle),
                                                       handle);
            }
            EntityManager.DestroyEntity(entity);
        }).Run();
        _barrier.AddJobHandleForProducer(handle);
        return(handle);
    }
예제 #22
0
    protected override void OnUpdate()
    {
        float time = Time.DeltaTime;
        var   ecb  = _entityCommandBufferSystem.CreateCommandBuffer().AsParallelWriter();

        Entities.ForEach((Entity entity, int entityInQueryIndex, ref LifetimeComponent lifetimeComponent) => {
            if (lifetimeComponent.time > 0)
            {
                lifetimeComponent.time -= time;
            }
            else
            {
                ecb.DestroyEntity(entityInQueryIndex, entity);
            }
        }).ScheduleParallel();

        _entityCommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
예제 #23
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            NativeArray <Entity> na_newOctreeEntities = group.ToEntityArray(Allocator.TempJob);

            Debug.Log("Add New Octree System");

            for (int i = 0; i < na_newOctreeEntities.Length; i++)
            {
                Entity e = na_newOctreeEntities [i];

                Debug.Log("#" + i + "; e #" + e.Index);
            }

            na_newOctreeEntities.Dispose();


            int i_groupLength = group.CalculateEntityCount();

            var initialiseOctreeJobHandle = new InitialiseOctreeJob
            {
                // a_newOctreeEntities                 = group.GetEntityArray (),

                // a_addNewOctreeData                  = GetComponentDataFromEntity <AddNewOctreeData> (),
                a_rootNodeData = GetComponentDataFromEntity <RootNodeData> (),

                nodeSparesBufferElement          = GetBufferFromEntity <NodeSparesBufferElement> (),
                nodeBufferElement                = GetBufferFromEntity <NodeBufferElement> (),
                nodeInstancesIndexBufferElement  = GetBufferFromEntity <NodeInstancesIndexBufferElement> (),
                nodeChildrenBufferElement        = GetBufferFromEntity <NodeChildrenBufferElement> (),
                instanceBufferElement            = GetBufferFromEntity <InstanceBufferElement> (),
                instancesSpareIndexBufferElement = GetBufferFromEntity <InstancesSpareIndexBufferElement> ()
            }.Schedule(group, inputDeps);


            var finalizeInitialisationOctreeJobHandle = new FinalizeInitialisationOctreeJob
            {
                ecb = eiecb.CreateCommandBuffer().ToConcurrent(),
                // a_newOctreeEntities                 = group.GetEntityArray ()
            }.Schedule(group, initialiseOctreeJobHandle);

            eiecb.AddJobHandleForProducer(finalizeInitialisationOctreeJobHandle);

            return(finalizeInitialisationOctreeJobHandle);
        }
예제 #24
0
        protected override void OnUpdate()
        {
            var commandBuffer = m_ECBSystem.CreateCommandBuffer().AsParallelWriter();

            Dependency =
                Entities
                .WithoutBurst()     // Burst does not support: TypeManager.GetTypeIndexFromStableTypeHash
                .ForEach(
                    (Entity entity, int entityInQueryIndex, ref DynamicBuffer <AnimationBinding> bindings, in DynamicBuffer <AnimationBindingRetarget> bindingRetargetBuffer) =>
            {
                for (int i = 0; i < bindingRetargetBuffer.Length; ++i)
                {
                    var binding = bindings[i];
                    binding.TargetComponentTypeIndex = TypeManager.GetTypeIndexFromStableTypeHash(bindingRetargetBuffer[i].StableTypeHash);
                    bindings[i] = binding;
                }

                commandBuffer.RemoveComponent <AnimationBindingRetarget>(entityInQueryIndex, entity);
            }).Schedule(Dependency);
예제 #25
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        //Instead of performing structural changes directly, a Job can add a command to an EntityCommandBuffer to perform such changes on the main thread after the Job has finished.
        //Command buffers allow you to perform any, potentially costly, calculations on a worker thread, while queuing up the actual insertions and deletions for later.

        // Schedule the job that will add Instantiate commands to the EntityCommandBuffer.
        var job = new TileSpawnJob
        {
            CommandBuffer = m_EntityCommandBufferSystem.CreateCommandBuffer()
        }.ScheduleSingle(this, inputDeps);


        // SpawnJob runs in parallel with no sync point until the barrier system executes.
        // When the barrier system executes we want to complete the SpawnJob and then play back the commands (Creating the entities and placing them).
        // We need to tell the barrier system which job it needs to complete before it can play back the commands.
        m_EntityCommandBufferSystem.AddJobHandleForProducer(job);

        return(job);
    }
예제 #26
0
        public unsafe override void UpdateSystem()
        {
            Dependency = JobHandle.CombineDependencies(Dependency, m_spawningQueueSystem.spawnQueueDependencies);

            EntityCommandBuffer        ecb        = m_entityCommandBuffer.CreateCommandBuffer();
            NativeQueue <SpawnCommand> spawnQueue = m_spawningQueueSystem.spawnQueue;
            NativeArray2D <MapNode>    grid       = _mMapManager.map;

            Dependency = Job.WithCode(() =>
            {
                while (spawnQueue.TryDequeue(out SpawnCommand spawnCommand))
                {
                    Entity entity;
                    switch (spawnCommand.spawnCommandType)
                    {
                    case SpawnCommandType.Harvester:
                        HarvesterSpawnData harvesterSpawnData = *spawnCommand.CommandData <HarvesterSpawnData>();

                        entity = ecb.Instantiate(spawnCommand.entity);
                        ecb.SetComponent(entity, harvesterSpawnData.translation);
                        ecb.SetComponent(entity, harvesterSpawnData.localToWorld);
                        ecb.SetComponent(entity, harvesterSpawnData.pathFinding);
                        break;

                    case SpawnCommandType.Projectile:
                        ProjectileSpawnData projectileSpawnData = *spawnCommand.CommandData <ProjectileSpawnData>();
                        entity = ecb.Instantiate(spawnCommand.entity);
                        ecb.SetComponent(entity, projectileSpawnData.translation);
                        ecb.SetComponent(entity, projectileSpawnData.projectile);
                        break;

                    default:
                        Debug.LogError("Invalid spawn command type!");
                        break;
                    }
                }
            }).Schedule(Dependency);

            m_entityCommandBuffer.AddJobHandleForProducer(Dependency);
        }
예제 #27
0
        protected override void OnUpdate()
        {
            var commandBuffer = _cmdBufferSystem.CreateCommandBuffer();

            Entities
            .WithAll <MouseAStarSystem.MouseRequestedPath>()
            .WithoutBurst()
            .WithStructuralChanges()
            .ForEach((Entity e, in DynamicBuffer <Waypoint> waypoints) =>
            {
                var materialColor = new float4(_random.NextFloat(), _random.NextFloat(), _random.NextFloat(), 1);

                var length = waypoints.Length;

                for (int x = 0; x < length; x++)
                {
                    var tileEntity = commandBuffer.CreateEntity(_pathTileArchetype);
                    var waypoint   = waypoints[x];
                    commandBuffer.SetSharedComponent(tileEntity, new RenderMesh {
                        mesh = _mesh, material = _material
                    });
                    commandBuffer.SetComponent(tileEntity, new Translation {
                        Value = new float3(waypoint.Position.x, 1, waypoint.Position.y)
                    });
                    commandBuffer.SetComponent(tileEntity, new RenderBounds
                    {
                        Value = new AABB()
                        {
                            Center  = float3.zero,
                            Extents = new float3(EXTEND, 0, EXTEND)
                        }
                    });
                    commandBuffer.SetComponent(tileEntity, new MainColorMaterialProperty
                    {
                        Color = materialColor
                    });
                }

                EntityManager.DestroyEntity(e);
            }).Run();
예제 #28
0
        protected override void OnUpdate( )
        {
            var commandBuffer = m_initializationEntityCommandBufferSystem.CreateCommandBuffer( );
            var isServer      = m_isServer;

            Entities.WithNone <PhysicsBodyReference>( ).ForEach((Entity ent,
                                                                 in SimulationBodyPrefabReference serverOwnedClientControlledPhysicsController, in Translation translation, in Rotation rotation) =>
            {
                var physicsBodyReference = new PhysicsBodyReference( )
                {
                    Value = commandBuffer.Instantiate(serverOwnedClientControlledPhysicsController.Value)
                };

                commandBuffer.AddComponent(ent, physicsBodyReference);
                commandBuffer.AddComponent(physicsBodyReference.Value, new PhysicsBodyOwner
                {
                    Value = ent
                });

                commandBuffer.SetComponent(physicsBodyReference.Value, translation);
                commandBuffer.SetComponent(physicsBodyReference.Value, rotation);
            }).Schedule( );
예제 #29
0
    protected override void OnUpdate()
    {
        var ecb  = _entityCommandBufferSystem.CreateCommandBuffer();
        var time = Time.DeltaTime;

        Entities.WithoutBurst().ForEach((ref AsteroidSpawnerComponent asteroidSpawner) => {
            if (asteroidSpawner.asteroidPrefab != Entity.Null)
            {
                if (asteroidSpawner.cooldown <= 0)
                {
                    var spawnRadius    = _random.NextFloat(asteroidSpawner.spawnRadius.min, asteroidSpawner.spawnRadius.max);
                    var spawnDirection = _random.NextFloat2Direction();
                    var position       = new float3(spawnRadius * spawnDirection.x, spawnRadius * spawnDirection.y, 0f);

                    var instance = ecb.Instantiate(asteroidSpawner.asteroidPrefab);
                    ecb.SetComponent(instance, new Translation()
                    {
                        Value = position
                    });
                    ecb.SetComponent(instance, new ForwardMovementComponent()
                    {
                        speed = _random.NextFloat(2f, 4f), isMoving = true
                    });
                    ecb.SetComponent(instance, new Rotation {
                        Value = quaternion.Euler(0f, 0f, _random.NextFloat(0f, 360f))
                    });

                    asteroidSpawner.cooldown += 1 / asteroidSpawner.spawnRate - time;
                }
                else
                {
                    asteroidSpawner.cooldown -= time;
                }
            }
        }).Run();

        _entityCommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
        protected override void OnUpdate()
        {
            var lookup     = GhostLookup;
            var hashLookup = HashLookup;

            var commandBuffer = m_barrier.CreateCommandBuffer( );

            Entities.WithNone <AddedToLookupTables>( ).ForEach((Entity e, in GhostComponent ghost) =>
            {
                var hash = 13;
                hash     = hash * 7 + ghost.ghostId.GetHashCode( );
                hash     = hash * 7 + ghost.ghostType.GetHashCode( );
                hash     = hash * 7 + ghost.spawnTick.GetHashCode( );

                if (hash == 4459)
                {
                    return;
                }

                lookup.Add(hash, e);
                hashLookup.Add(e, hash);

                commandBuffer.AddComponent <AddedToLookupTables>(e);
            }).Schedule( );

            Entities.WithNone <GhostComponent>( ).WithAll <AddedToLookupTables>().ForEach(( Entity ent ) =>
            {
                var hash = hashLookup[ent];

                lookup.Remove(hash);
                hashLookup.Remove(ent);

                commandBuffer.RemoveComponent <AddedToLookupTables>(ent);
            }).Schedule( );

            m_barrier.AddJobHandleForProducer(Dependency);
        }