예제 #1
0
        public Entity CreateHealingItem(EntityCommandBuffer ecb, int2 xy, float3 pos, int healAmount)
        {
            Entity entity = ecb.CreateEntity(HealingPotion);

            HealItem         heal = new HealItem();
            Sprite2DRenderer s    = new Sprite2DRenderer();
            Translation      t    = new Translation();
            WorldCoord       c    = new WorldCoord();
            LayerSorting     l    = new LayerSorting();

            t.Value = pos;

            c.x = xy.x;
            c.y = xy.y;

            // Only tint sprites if ascii
            s.color = GlobalGraphicsSettings.ascii
                ? new Unity.Tiny.Core2D.Color(1.0f, 0.26f, 0.23f)
                : Color.Default;
            if (GlobalGraphicsSettings.ascii)
            {
                s.color.a = 0;
            }

            s.sprite = SpriteSystem.IndexSprites[SpriteSystem.ConvertToGraphics((char)235)];
            l.layer  = 1;

            heal.HealAmount = healAmount;

            ecb.SetComponent(entity, s);
            ecb.SetComponent(entity, t);
            ecb.SetComponent(entity, c);
            ecb.SetComponent(entity, l);
            ecb.SetComponent(entity, heal);

            return(entity);
        }
예제 #2
0
        public Entity CreateDoorway(EntityCommandBuffer ecb, int2 xy, float3 pos, bool horizontal)
        {
            Entity entity = ecb.CreateEntity(Doorway);

            Sprite2DRenderer s = new Sprite2DRenderer();
            Translation      t = new Translation();
            WorldCoord       c = new WorldCoord();
            LayerSorting     l = new LayerSorting();
            Door             d = new Door();

            d.Horizontal = horizontal;
            t.Value      = pos;

            c.x = xy.x;
            c.y = xy.y;

            // Only tint sprites if ascii
            s.color = GlobalGraphicsSettings.ascii
                ? new Unity.Tiny.Core2D.Color(18 / 255.0f, 222 / 255.0f, 23.0f / 255.0f)
                : Color.Default;
            if (GlobalGraphicsSettings.ascii)
            {
                s.color.a = 0;
            }

            s.sprite = SpriteSystem.IndexSprites[SpriteSystem.ConvertToGraphics(horizontal ? '\\' : '/')];
            // Have to draw above character in graphical
            l.layer = (short)(GlobalGraphicsSettings.ascii ? 1 : 3);

            ecb.SetComponent(entity, s);
            ecb.SetComponent(entity, t);
            ecb.SetComponent(entity, c);
            ecb.SetComponent(entity, l);
            ecb.SetComponent(entity, d);

            return(entity);
        }
        void UpdateMissingVisibleLocalToWorld()
        {
            var localToWorldOrderVersion = EntityManager.GetComponentOrderVersion <LocalToWorld>();

            if (localToWorldOrderVersion == m_LastLocalToWorldOrderVersion)
            {
                return;
            }

            EntityCommandBuffer entityCommandBuffer = new EntityCommandBuffer(Allocator.Temp);

            var query = new EntityArchetypeQuery
            {
                Any  = Array.Empty <ComponentType>(),
                None = new ComponentType[] { typeof(VisibleLocalToWorld) },
                All  = new ComponentType[] { typeof(TrackedMeshInstanceRenderer), typeof(LocalToWorld) }
            };
            var entityType = GetArchetypeChunkEntityType();
            var chunks     = EntityManager.CreateArchetypeChunkArray(query, Allocator.TempJob);

            for (int i = 0; i < chunks.Length; i++)
            {
                var chunk    = chunks[i];
                var entities = chunk.GetNativeArray(entityType);
                for (int j = 0; j < chunk.Count; j++)
                {
                    var entity = entities[j];
                    entityCommandBuffer.AddComponent(entity, default(VisibleLocalToWorld));
                }
            }

            entityCommandBuffer.Playback(EntityManager);
            entityCommandBuffer.Dispose();
            chunks.Dispose();

            m_LastLocalToWorldOrderVersion = localToWorldOrderVersion;
        }
예제 #4
0
        // Request to add some instances.
        // User is responsible to ensure, that instances IDs are unique in the octrtree.
        static public void _RequesAddInstances(EntityCommandBuffer ecb, Entity octreeEntity, BufferFromEntity <AddInstanceBufferElement> addInstanceBufferElement, ref NativeArray <Entity> a_instanceEntities, int i_instances2AddCount)
        {
            DynamicBuffer <AddInstanceBufferElement> a_addInstanceBufferElement = addInstanceBufferElement [octreeEntity];

            int i_instanceEntityIndex = 0;

            for (int i_instanceID = 0; i_instanceID < i_instances2AddCount; i_instanceID++)
            {
                Entity newBlockEntity = a_instanceEntities [i_instanceEntityIndex];
                i_instanceEntityIndex++;

                int    x = i_instanceID % 1000;
                int    y = i_instanceID % 100;
                int    z = (int)math.floor(i_instanceID / 1000);
                float3 f3_blockCenter = new float3(x, y, z) + new float3(1, 1, 1) * 0.5f;

                Blocks.PublicMethods._AddBlockRequestViaCustomBufferWithEntity(ecb, newBlockEntity, f3_blockCenter, new float3(1, 1, 1) * 1);



                // Bounds of instance node,
                // hence entity block as well.
                Bounds bounds = new Bounds()
                {
                    center = f3_blockCenter, size = new float3(1, 1, 1) * 1
                };

                AddInstanceBufferElement addInstanceBuffer = new AddInstanceBufferElement()
                {
                    i_instanceID   = newBlockEntity.Index,
                    i_version      = newBlockEntity.Version,
                    instanceBounds = bounds
                };

                a_addInstanceBufferElement.Add(addInstanceBuffer);
            }
        }
예제 #5
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.TempJob);

        Entities
        .WithAll <BallTag>()
        // .WithStructuralChanges()
        // we can use EntityManager because we say .WithStructuralChanges(),
        // that create a special version of the data that allows us to modify it without invalidating the structural data
        // But it is only ok for very simple jobs like this one but for more complex games, it can create some slow down
        // because it create a specialised copy of the data
        .WithoutBurst()     // we cannot reference GameManager with Burst, no disable it
        .ForEach((Entity entity, in Translation trans) =>
        {
            float3 pos  = trans.Value;
            float bound = GameManager.main.xBound;

            if (pos.x >= bound)
            {
                GameManager.main.PlayerScored(0);
                // EntityManager.DestroyEntity(entity);
                ecb.DestroyEntity(entity);
            }
            else if (pos.x <= -bound)
            {
                GameManager.main.PlayerScored(1);
                // EntityManager.DestroyEntity(entity);
                ecb.DestroyEntity(entity);
            }
        }).Run();

        // say to the EntityManager to do all the command that we recorded
        ecb.Playback(EntityManager);
        ecb.Dispose();

        return(default);
예제 #6
0
    protected override unsafe void OnUpdate()
    {
        var deltaTime = UnityEngine.Time.deltaTime;

        using (var commandBuffer = new EntityCommandBuffer(Allocator.TempJob))
        {
            Entities
            .WithName("ChangeColliderType")
            .WithAll <PhysicsCollider, RenderMesh>()
            .WithoutBurst()
            .ForEach((Entity entity, ref ChangeColliderType modifier) =>
            {
                modifier.LocalTime -= deltaTime;

                if (modifier.LocalTime > 0.0f)
                {
                    return;
                }

                modifier.LocalTime = modifier.TimeToSwap;
                var collider       = EntityManager.GetComponentData <PhysicsCollider>(entity);
                if (collider.ColliderPtr->Type == modifier.ColliderA.ColliderPtr->Type)
                {
                    commandBuffer.SetComponent(entity, modifier.ColliderB);
                    commandBuffer.SetSharedComponent(entity, EntityManager.GetSharedComponentData <RenderMesh>(modifier.EntityB));
                }
                else
                {
                    commandBuffer.SetComponent(entity, modifier.ColliderA);
                    commandBuffer.SetSharedComponent(entity, EntityManager.GetSharedComponentData <RenderMesh>(modifier.EntityA));
                }
            }).Run();

            commandBuffer.Playback(EntityManager);
        }
    }
예제 #7
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            using (var commandBuffer = new EntityCommandBuffer(Allocator.TempJob))
            {
                inputDeps = new ShipDestroyMessageJob
                {
                    OnDestroyMessage = typeof(OnDestroyMessage),

                    Weapon_OnShipDestroyMessage = typeof(Weapon_OnShipDestroyMessage),
                    Player_OnShipDestroyMessage = typeof(Player_OnShipDestroyMessage),

                    commandBuffer    = commandBuffer.ToConcurrent(),
                    endCommandBuffer = endBarrier.CreateCommandBuffer().ToConcurrent(),

                    playerFromEntity = GetComponentDataFromEntity <Player>(true),
                }
                .Schedule(this, inputDeps);

                inputDeps.Complete();
                commandBuffer.Playback(EntityManager);
            }

            return(inputDeps);
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var materialReferencesEntity = GetSingletonEntity <MaterialReferencesTag>();
        var gameData = GetSingleton <GameData>();

        var nBuffer   = EntityManager.GetBuffer <UIMaterialReference>(materialReferencesEntity);
        var materials = nBuffer.ToNativeArray(Allocator.TempJob);

        var ecb = new EntityCommandBuffer(Allocator.Temp);

        Entities
        .WithAll <UpdateScoreTag, ActivatedTag>()
        .ForEach((Entity entity, ref MeshRenderer meshRenderer, in ScorePart scorePart) =>
        {
            int digit             = (int)((float)gameData.score / scorePart.Divisor);
            meshRenderer.material = materials[digit % 10].materialEntity;
            ecb.RemoveComponent <ActivatedTag>(entity);
        }).Run();

        ecb.Playback(EntityManager);
        ecb.Dispose();

        materials.Dispose();
        return(default);
예제 #9
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var PostUpdateCommands     = new EntityCommandBuffer(Allocator.TempJob);
        var LocalToWorldFromEntity = GetComponentDataFromEntity <Unity.Transforms.LocalToWorld>(true);

        Entities
        .WithReadOnly(LocalToWorldFromEntity)
        .WithNativeDisableContainerSafetyRestriction(PostUpdateCommands)
        .WithoutBurst()     // Uses EntityManager.Exists
        .ForEach((Entity e, ref SoundRequest req) =>
        {
            // If handle is invalid, let go of this tracker
            if (!SoundSystem.Instance.IsValid(ref req.soundHandle))
            {
                PostUpdateCommands.DestroyEntity(e);
                return;
            }
            // Update position
            if (!EntityManager.Exists(req.trackEntity))
            {
                GameDebug.LogWarning("Sound trying to follow invalid entity " + req.trackEntity);
                PostUpdateCommands.DestroyEntity(e);
                return;
            }
            if (!LocalToWorldFromEntity.HasComponent(req.trackEntity))
            {
                GameDebug.LogWarning("Sound trying to follow entity " + req.trackEntity + " which does not have a transform");
                PostUpdateCommands.DestroyEntity(e);
                return;
            }
            var ltw = LocalToWorldFromEntity[req.trackEntity];
            SoundSystem.Instance.UpdatePosition(ref req.soundHandle, ltw.Position);
        }).Run();
        PostUpdateCommands.Playback(EntityManager);
        PostUpdateCommands.Dispose();
        return(default);
        protected override void OnCreate()
        {
            ecbSource = World.GetExistingSystem <EndSimulationEntityCommandBufferSystem>();

            // Create some test entities
            // This runs on the main thread, but it is still faster to use a command buffer
            EntityCommandBuffer creationBuffer = new EntityCommandBuffer(Allocator.Temp);
            EntityArchetype     archetype      = EntityManager.CreateArchetype(typeof(GeneralPurposeComponentA));

            for (int i = 0; i < 10000; i++)
            {
                Entity newEntity = creationBuffer.CreateEntity(archetype);
                creationBuffer.SetComponent <GeneralPurposeComponentA>
                (
                    newEntity,
                    new GeneralPurposeComponentA()
                {
                    Lifetime = i
                }
                );
            }
            //Execute the command buffer
            creationBuffer.Playback(EntityManager);
        }
예제 #11
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityCommandBuffer entityOriginsCommandBuffer = new EntityCommandBuffer(Allocator.TempJob, PlaybackPolicy.SinglePlayback);

        Entities.WithNone <BallOriginalTranslation>().ForEach((Entity entity, Translation translation, SphereId sphereId) =>
        {
            entityOriginsCommandBuffer.AddComponent(entity, new BallOriginalTranslation {
                Value = translation.Value
            });
        }).Run();
        entityOriginsCommandBuffer.Playback(EntityManager);
        entityOriginsCommandBuffer.Dispose();

        var moveBallJob = new MoveBall
        {
            TranslationType             = GetArchetypeChunkComponentType <Translation>(),
            BallOriginalTranslationType = GetArchetypeChunkComponentType <BallOriginalTranslation>(true),
            LastSystemVersion           = LastSystemVersion,
            ElapsedTime = Time.ElapsedTime
        };
        var moveBallJobHandle = moveBallJob.Schedule(m_Group, inputDeps);

        return(moveBallJobHandle);
    }
        public void ShouldReplaceManyWithOne()
        {
            using var memory = new HeapAllocator(_logFactory);
            using var em     = new EntityManager(_logFactory, memory);
            using var buffer = new EntityCommandBuffer(em, memory);

            var spec = new EntitySpec(ComponentType <Position> .Type, ComponentType <Velocity> .Type);

            var       position = new Position(10, 10);
            const int samples  = 32;

            var ids = new uint[samples];

            em.Create(spec, ids);

            buffer.Replace(ids, position);
            buffer.Execute();

            em.EntityCount.ShouldBe(32);
            em.EntityArrays[0].EntityCount.ShouldBe(32);
            var positions = ids.Select(id => em.Get <Position>(id)).ToArray();

            positions.ShouldAllBe(x => x == position);
        }
예제 #13
0
        protected override void OnUpdate()
        {
            var state = GetSingleton <GameState>();

            if (state.Value != GameStateEnum.InGame)
            {
                return;
            }

            var cmdBuffer = new EntityCommandBuffer(Allocator.TempJob);

            Entities
            .WithAll <CarrotTag>()
            .ForEach((Entity entity, int entityInQueryIndex, in Translation trans) =>
            {
                if (trans.Value.x <= -5)
                {
                    cmdBuffer.DestroyEntity(entity);
                }
            }).Run();

            cmdBuffer.Playback(EntityManager);
            cmdBuffer.Dispose();
        }
예제 #14
0
        public void Empty()
        {
            ECSWorld world  = new ECSWorld();
            var      buffer = new EntityCommandBuffer(world);

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

            prefab.AddComponent(new TestComponentVector3()
            {
                value = Vector3.UnitY
            });
            prefab.AddSharedComponent(shared1);

            Assert.True(buffer.IsEmpty());

            buffer.CreateEntity(prefab);

            Assert.False(buffer.IsEmpty());

            buffer.Playback();

            Assert.True(buffer.IsEmpty());
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        float tTime          = Time.DeltaTime;
        float EnemyPositionX = m_GameData.m_LevelData.m_EnemySpawnPointX;
        EntityCommandBuffer tCommandBuffer = m_EndSimulationEntityCommandBufferSystem.CreateCommandBuffer();
        int tRandomCount = 0;

        Entities.ForEach(
            (Entity entity, ref C_SpawnData spawnData, ref Prefab prefab, in T_Enemy eEnemy) =>
        {
            spawnData.TimeCache += tTime;
            if (spawnData.TimeCache > spawnData.Cooldown)
            {
                for (int i = 0; i < spawnData.SpawnAmount; i++)
                {
                    Entity tSpawnEntity = tCommandBuffer.CreateEntity();
                    tCommandBuffer.AddComponent(tSpawnEntity, typeof(C_SpawnRequest));

                    float tX = Random.Range(spawnData.SpawnArea.x, spawnData.SpawnArea.y);
                    float tZ = Random.Range(spawnData.SpawnArea.z, spawnData.SpawnArea.w);

                    tCommandBuffer.SetComponent(tSpawnEntity, new C_SpawnRequest
                    {
                        Position  = new float3(EnemyPositionX + tX, (int)spawnData.MechaLane, tZ) + spawnData.Offset,
                        Direction = 1,
                        Reference = entity
                    });
                }
                spawnData.TimeCache = 0;
            }
        })
        .WithoutBurst()
        .Run();

        return(inputDeps);
    }
예제 #16
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var entityCommandBuffer = new EntityCommandBuffer(Allocator.Temp);

            var gameManager = GameManager.Instance;
            var xBound      = gameManager.xBound;

            Entities
            .WithAll <BallTag>()
            .WithoutBurst()
            .ForEach((Entity entity, in Translation position) =>
            {
                var positionX = position.Value.x;

                if (positionX >= xBound)
                {
                    gameManager.PlayerScored(0);
                    // ReSharper disable once AccessToDisposedClosure
                    entityCommandBuffer.DestroyEntity(entity);
                    return;
                }

                if (!(positionX <= -xBound))
                {
                    return;
                }
                gameManager.PlayerScored(1);
                // ReSharper disable once AccessToDisposedClosure
                entityCommandBuffer.DestroyEntity(entity);
            })
            .Run();

            entityCommandBuffer.Playback(EntityManager);
            entityCommandBuffer.Dispose();

            return(default);
예제 #17
0
    public static void DropItem(EntityCommandBuffer postUpdateCommands, EntityManager entityManager, Entity itemEntity, Transform inventoryTransform, Entity inventoryEntity, ref ActorInventory actorInventory)
    {
        //Item is no longer parent of a entity
        postUpdateCommands.RemoveComponent(actorInventory.equippedEntiy, typeof(Parent));

        //Rest transform parent, physics and collision
        var itemTransform = entityManager.GetComponentObject <Transform>(actorInventory.equippedEntiy);

        itemTransform.GetComponent <Rigidbody>().useGravity  = true;
        itemTransform.GetComponent <Rigidbody>().isKinematic = false;
        itemTransform.GetComponent <Collider>().enabled      = true;
        itemTransform.SetParent(null, true);

        //Were dropping main entity
        if (actorInventory.equippedEntiy == itemEntity)
        {
            actorInventory.isEquipped = 0;
            inventoryTransform.GetComponentInChildren <Animator>().SetFloat("itemType", 0.0f);
            if (entityManager.HasComponent(inventoryEntity, typeof(ActorTagCanMeleeAttack)))
            {
                postUpdateCommands.RemoveComponent <ActorTagCanMeleeAttack>(inventoryEntity);
            }
        }
    }
예제 #18
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Random random = new Random((uint)(Time.ElapsedTime * 100000));
            EntityCommandBuffer commandBuffer      = beginSimulationEntityCBS.CreateCommandBuffer();
            EntityCommandBuffer.ParallelWriter ecb = commandBuffer.AsParallelWriter();
            inputDeps = Entities.ForEach((int entityInQueryIndex, ref BoidSpawnerComponent prefabComponent) =>
            {
                float3 spawnOffset = prefabComponent.Offsets;
                for (int i = 0; i < prefabComponent.SpawnNumber; i++)
                {
                    float3 offset = new float3(
                        spawnOffset.x * (2 * random.NextFloat() - 1),
                        spawnOffset.y * (2 * random.NextFloat() - 1),
                        spawnOffset.z * (2 * random.NextFloat() - 1)
                        );
                    Entity entity = ecb.Instantiate(entityInQueryIndex, prefabComponent.Entity);
                    //Entity entity = EntityManager.Instantiate(prefabComponent.Entity);

                    float3 position = prefabComponent.Center + offset;
                    ecb.SetComponent(entityInQueryIndex, entity, new Translation {
                        Value = position
                    });
                    ecb.SetComponent(entityInQueryIndex, entity, new Rotation {
                        Value = new quaternion(random.NextFloat(), random.NextFloat(), random.NextFloat(), random.NextFloat())
                    });
                    //EntityManager.AddComponentData(entity, new Translation { Value = position });
                    //EntityManager.AddComponentData(entity, new Rotation { Value = new quaternion(random.NextFloat(), random.NextFloat(), random.NextFloat(), random.NextFloat())});
                }
            }).Schedule(inputDeps);
            //commandBuffer.Playback(EntityManager);
            beginSimulationEntityCBS.AddJobHandleForProducer(inputDeps);
        }
        return(inputDeps);
    }
        public void ActionFailsToBindArguments()
        {
            var statesToExpand = new NativeList <StateEntityKey>(1, Allocator.TempJob);

            statesToExpand.Add(KeyDomainUtility.InitialStateKey);

            var unlockRoomDataContext = m_StateManager.StateDataContext;
            var unlockRoomECB         = new EntityCommandBuffer(Allocator.TempJob);

            unlockRoomDataContext.EntityCommandBuffer = unlockRoomECB.AsParallelWriter();

            var unlockRoomAction = new UnlockRoomAction(statesToExpand, unlockRoomDataContext);
            var jobHandle        = JobHandle.CombineDependencies(unlockRoomAction.Schedule(statesToExpand, default), m_StateManager.EntityManager.ExclusiveEntityTransactionDependency);

            jobHandle.Complete();

            unlockRoomECB.Playback(m_StateManager.ExclusiveEntityTransaction);
            unlockRoomECB.Dispose();
            statesToExpand.Dispose();

            var unlockRoomTransitions = m_StateManager.EntityManager.GetBuffer <UnlockRoomAction.FixupReference>(KeyDomainUtility.InitialStateKey.Entity);

            Assert.AreEqual(0, unlockRoomTransitions.Length);
        }
예제 #20
0
    void Update()
    {
        EntityCommandBuffer _ecb = _beginInitializationEntityCommandBufferSystem.CreateCommandBuffer();


        miniJob _miniJob = new miniJob
        {
            Input_A            = Input.GetKey(KeyCode.A),
            Input_Z            = Input.GetKey(KeyCode.Z),
            Input_Mouse_0_Down = Input.GetMouseButton(0),
            Input_Mouse_1_Down = Input.GetMouseButton(1),
            Input_Mouse_0_Up   = !Input.GetMouseButton(0),
            Input_Mouse_1_Up   = !Input.GetMouseButton(1),
            _ecb           = _ecb,
            _entityManager = _entityManager,
            _inputEntity   = _inputEntity
        };

        JobHandle _handle = _miniJob.ScheduleSingle(_query);

        _handle.Complete();

        _beginInitializationEntityCommandBufferSystem.AddJobHandleForProducer(_handle);
    }
예제 #21
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        NativeArray <PlayableCameraDeviceInputData> activeCameras = activeCamerasQuery.ToComponentDataArray <PlayableCameraDeviceInputData>(Allocator.TempJob);
        EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.TempJob);

        Entities
        .WithoutBurst()
        .ForEach((in PlayableCharacterDeviceInputComponentData playableCharacterDeviceInput) =>
        {
            bool hasPlayableCharacterCamera = false;
            foreach (PlayableCameraDeviceInputData camera in activeCameras)
            {
                if (camera.DeviceInputId == playableCharacterDeviceInput.DeviceInputId)
                {
                    hasPlayableCharacterCamera = true;
                    break;
                }
            }

            if (hasPlayableCharacterCamera == false)
            {
                SpawnPlayableCamera(ecb, playableCharacterDeviceInput.DeviceInputId);
            }
        }).Run();
예제 #22
0
    public void GetRandomCollectible(EntityCommandBuffer ecb, Entity entity, CanBePickedUp c, HealthBonus hb)
    {
        if (collectiblesList.Count <= 0)
        {
            return;
        }

        var colEntry = collectiblesList[RandomRogue.Next(0, collectiblesList.Count)];

        c.appearance.sprite = GlobalGraphicsSettings.ascii ? colEntry.spriteAscii : colEntry.spriteGraphics;
        c.description       = colEntry.description;
        c.name = colEntry.name;

        ecb.SetComponent(entity, c);

        if (colEntry.healthBonus != 0)
        {
            hb.healthAdded = colEntry.healthBonus;

            //TODO: fix this
            //entityManager.SetComponentData(entity, hb);
            ecb.SetComponent(entity, hb);
        }
    }
        public void ConcurrentRecordParallelFor()
        {
            const int kCreateCount = 10000;
            var       cmds         = new EntityCommandBuffer(Allocator.TempJob);

            cmds.CreateEntity();
            new TestConcurrentParallelForJob {
                Buffer = cmds.ToConcurrent()
            }.Schedule(kCreateCount, 64).Complete();
            cmds.Playback(m_Manager);
            cmds.Dispose();

            var allEntities = m_Manager.GetAllEntities();
            int count       = allEntities.Length;

            Assert.AreEqual(kCreateCount + 1, count);
            bool[] foundEntity = new bool[kCreateCount];
            for (int i = 0; i < foundEntity.Length; ++i)
            {
                foundEntity[i] = false;
            }
            for (int i = 0; i < count; ++i)
            {
                if (m_Manager.HasComponent <EcsTestData>(allEntities[i]))
                {
                    var data1 = m_Manager.GetComponentData <EcsTestData>(allEntities[i]);
                    Assert.IsFalse(foundEntity[data1.value]);
                    foundEntity[data1.value] = true;
                }
            }
            for (int i = 0; i < foundEntity.Length; ++i)
            {
                Assert.IsTrue(foundEntity[i]);
            }
            allEntities.Dispose();
        }
예제 #24
0
 private static void LeaveMark(int2 size,
                               int2 current,
                               EntityCommandBuffer buffer,
                               float amount,
                               NativeHashMap <int2, Entity> map,
                               ComponentDataFromEntity <Depth> depthLookup,
                               Worker worker)
 {
     if (current.x < size.x && current.y < size.y && current.y >= 0 && current.x >= 0)
     {
         Entity block = map[current];
         Depth  depth = depthLookup[block];
         depth.Value += amount;
         buffer.SetComponent(block, depth);
         buffer.AddComponent(block,
                             new Mark()
         {
             Power    = amount,
             Color    = worker.Color,
             Duration = worker.MarkDuration,
             Block    = block
         });
     }
 }
        public void TestMultiChunks()
        {
            const int count = 65536;

            var cmds = new EntityCommandBuffer(Allocator.TempJob);

            cmds.MinimumChunkSize = 512;

            for (int i = 0; i < count; ++i)
            {
                cmds.CreateEntity();
                cmds.AddComponent(new EcsTestData {
                    value = i
                });
                cmds.AddComponent(new EcsTestData2 {
                    value0 = i, value1 = i
                });
            }

            cmds.Playback(m_Manager);
            cmds.Dispose();

            {
                var group = m_Manager.CreateComponentGroup(typeof(EcsTestData), typeof(EcsTestData2));
                var arr   = group.GetComponentDataArray <EcsTestData>();
                var arr2  = group.GetComponentDataArray <EcsTestData2>();
                Assert.AreEqual(count, arr.Length);
                for (int i = 0; i < count; ++i)
                {
                    Assert.AreEqual(i, arr[i].value);
                    Assert.AreEqual(i, arr2[i].value0);
                    Assert.AreEqual(i, arr2[i].value1);
                }
                group.Dispose();
            }
        }
예제 #26
0
            private void CreateBlast(Entity entity, Blast blast, EntityCommandBuffer buffer)
            {
                float radian = math.PI / 180f;

                buffer.SetComponent(entity, new Rotation
                {
                    Value = quaternion.Euler(90 * radian, 0, 0, math.RotationOrder.Default),
                });
                buffer.SetComponent(entity, new NonUniformScale
                {
                    Value = new float3(1, 1, 1)
                });
                buffer.SetComponent(entity, new Translation
                {
                    Value = blast.Pos,
                });
                buffer.SetSharedComponent(entity, new RenderMesh
                {
                    mesh           = ECSWorld.Instance.meshBlast,
                    material       = ECSWorld.Instance.materialBlast,
                    castShadows    = ShadowCastingMode.Off,
                    receiveShadows = false
                });
            }
예제 #27
0
 private void spawn_internal(EntityCommandBuffer entity_command_buffer,
                             float current_time,
                             Entity target_entity,
                             Material mat)
 {
     // Develop.print("yes");
     entity_command_buffer.CreateEntity(arche_type_);
     entity_command_buffer.SetComponent(new AlivePeriod {
         start_time_ = current_time, period_ = 0.3f,
     });
     entity_command_buffer.SetComponent(new StartTime {
         value_ = current_time,
     });
     entity_command_buffer.SetComponent(new Sight {
         target_entity_ = target_entity,
     });
     entity_command_buffer.SetSharedComponent(new CustomMeshInstanceRenderer {
         mesh           = mesh_,
         material       = mat,
         castShadows    = UnityEngine.Rendering.ShadowCastingMode.Off,
         receiveShadows = false,
         layer          = 9 /* final */,
     });
 }
 public override void CleanupEvents(ComponentGroup[] eventGroups, ref EntityCommandBuffer buffer)
 {
 }
 public override void CleanupCommands(ComponentGroup[] commandCleanupGroups, ref EntityCommandBuffer buffer)
 {
 }
            public override void CleanupAuthChanges(ComponentGroup authorityChangeGroup, ref EntityCommandBuffer buffer)
            {
                var entities = authorityChangeGroup.GetEntityArray();
                var data     = authorityChangeGroup.GetComponentDataArray <AuthorityChanges <Improbable.Gdk.Tests.ExhaustiveOptional.Component> >();

                for (var i = 0; i < entities.Length; i++)
                {
                    buffer.RemoveComponent <AuthorityChanges <Improbable.Gdk.Tests.ExhaustiveOptional.Component> >(entities[i]);
                    AuthorityChangesProvider.Free(data[i].Handle);
                }
            }