protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var handle = inputDeps;

        if (PlayerPositionChanged())
        {
            var jobDespawn = new DeSpawnChunksAround
            {
                childBuffer    = GetBufferFromEntity <ChunkChildBlock>(true),
                commandBuffer  = ecbSystem.CreateCommandBuffer().ToConcurrent(),
                playerPosition = GetPlayerPosition()
            };
            handle = jobDespawn.Schedule(this, handle);

            var job = new SpawnChunksAround
            {
                commandBuffer  = ecbSystem.CreateCommandBuffer(),
                playerPosition = GetPlayerPosition()
            };
            handle = job.Schedule(handle);
            ecbSystem.AddJobHandleForProducer(handle);
        }

        return(handle);
    }
    protected override JobHandle OnUpdate(JobHandle inputDep)
    {
        if (!m_DriverSystem.ClientDriver.IsCreated)
        {
            return(inputDep);
        }
        PingClientUIBehaviour.UpdateStats(m_pingStats[0], m_pingStats[1]);
        if (PingClientUIBehaviour.ServerEndPoint.IsValid && m_ConnectionGroup.IsEmptyIgnoreFilter)
        {
            var conJob = new ConnectJob
            {
                driver        = m_DriverSystem.ClientDriver,
                serverEP      = PingClientUIBehaviour.ServerEndPoint,
                commandBuffer = m_Barrier.CreateCommandBuffer()
            };
            inputDep = conJob.Schedule(inputDep);
            m_Barrier.AddJobHandleForProducer(inputDep);
            return(inputDep);
        }
        var pingJob = new PingJob
        {
            driver        = m_DriverSystem.ClientDriver,
            serverEP      = PingClientUIBehaviour.ServerEndPoint,
            pendingPings  = m_pendingPings,
            pingStats     = m_pingStats,
            fixedTime     = Time.fixedTime,
            commandBuffer = m_Barrier.CreateCommandBuffer()
        };
        var handle = pingJob.ScheduleSingle(this, inputDep);

        m_Barrier.AddJobHandleForProducer(handle);
        return(handle);
    }
Beispiel #3
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        JobHandle queryJob;
        var       connection   = m_ConnectionQuery.ToEntityArray(Allocator.TempJob, out queryJob);
        var       sendSetupJob = new SendPlayerSetupJob {
            CommandBuffer    = m_CommandBuffer.CreateCommandBuffer(),
            RpcQueue         = m_RpcSettingsQueue,
            ConnectionEntity = connection,
            RpcBuffer        = GetBufferFromEntity <OutgoingRpcDataStreamBufferComponent>()
        };
        var jobHandle = sendSetupJob.ScheduleSingle(this, JobHandle.CombineDependencies(inputDeps, queryJob));

        var remoteCommandJob = new SendRemoteCommandJob()
        {
            CommandBuffer    = m_CommandBuffer.CreateCommandBuffer(),
            RpcQueue         = m_RpcRemoteCmdQueue,
            ConnectionEntity = connection,
            RpcBuffer        = GetBufferFromEntity <OutgoingRpcDataStreamBufferComponent>()
        };

        jobHandle = remoteCommandJob.ScheduleSingle(this, jobHandle);

        m_CommandBuffer.AddJobHandleForProducer(jobHandle);
        return(jobHandle);
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            var inputDeps1 = new AddSystemStateJob
            {
                Ecb        = m_EntityCommandBuffer.CreateCommandBuffer().ToConcurrent(),
                EntityType = GetArchetypeChunkEntityType(),
                Targets    = GetArchetypeChunkComponentType <AbilityOwnerComponent>()
            }.Schedule(m_AddSystemState, inputDeps);

            var inputDeps2 = new CleanupEntityJob
            {
                Ecb        = m_EntityCommandBuffer.CreateCommandBuffer().ToConcurrent(),
                EntityType = GetArchetypeChunkEntityType(),
            }.Schedule(m_RemoveSystemState, inputDeps);

            inputDeps = JobHandle.CombineDependencies(inputDeps, inputDeps1, inputDeps2);

            inputDeps = new RemoveElementFromDynamicBuffer
            {
                bufferFromEntity = GetBufferFromEntity <GrantedAbilityBufferElement>(),
                entities         = m_RemoveSystemState.ToEntityArray(Allocator.TempJob),
                targetComponents = m_RemoveSystemState.ToComponentDataArray <GrantedAbilitySystemStateComponent>(Allocator.TempJob)
            }.Schedule(inputDeps);

            inputDeps = new AddElementToDynamicBuffer
            {
                bufferFromEntity = GetBufferFromEntity <GrantedAbilityBufferElement>(),
                entities         = m_AddSystemState.ToEntityArray(Allocator.TempJob),
                targetComponents = m_AddSystemState.ToComponentDataArray <AbilityOwnerComponent>(Allocator.TempJob)
            }.Schedule(inputDeps);


            m_EntityCommandBuffer.AddJobHandleForProducer(inputDeps);
            return(inputDeps);
        }
Beispiel #5
0
        void Generate(Entity mapEntity, float2 resize)
        {
            var mapData = EntityManager.GetComponentData <MapData>(mapEntity);

            var commandBuffer = _barrierSystem.CreateCommandBuffer();

            int monsterCount = _monstersQuery.CalculateEntityCount();

            Job.WithCode(() =>
            {
                var genData          = GenerateMap.Default;
                genData.monsterCount = monsterCount;
                commandBuffer.AddComponent(mapEntity, genData);

                mapData.width  += (int)resize.x;
                mapData.height += (int)resize.y;

                mapData.width  = math.max(15, mapData.width);
                mapData.height = math.max(15, mapData.height);

                commandBuffer.SetComponent(mapEntity, mapData);
            }).Schedule();

            _barrierSystem.AddJobHandleForProducer(Dependency);
        }
Beispiel #6
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var mouse = GetSingleton <SingletonMouseInput>();

        var jobHandle = inputDeps;

        if (mouse.LeftClickUp)
        {
            var selectionBoxJob = new SelectionBoxJob
            {
                currentMouseRayPosition = mouse.CurrentMouseRaycastPosition,
                initialMouseRayPosition = mouse.InitialMouseRaycastPosition,
                selected            = GetComponentDataFromEntity <TagSelected>(),
                entityCommandBuffer = m_EntityCommandBufferSystem.CreateCommandBuffer(),
            };

            jobHandle = selectionBoxJob.ScheduleSingle(this, inputDeps);
        }
        else if (mouse.LeftClickDown)
        {
            var selectClickJob = new SelectClickJob
            {
                currentMouseRayPosition = mouse.CurrentMouseRaycastPosition,
                selected            = GetComponentDataFromEntity <TagSelected>(),
                entityCommandBuffer = m_EntityCommandBufferSystem.CreateCommandBuffer(),
            };

            jobHandle = selectClickJob.Schedule(this, inputDeps);
        }

        m_EntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);

        return(jobHandle);
    }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        inputDeps.Complete();

        JobHandle serverJobHandle;

        //Debug.Log("server system on update");
        if (!m_Driver.IsCreated)
        {
            ReliableUtility.Parameters reliabilityParams = new ReliableUtility.Parameters {
                WindowSize = 32
            };
            SimulatorUtility.Parameters simulatorParams = new SimulatorUtility.Parameters {
                MaxPacketSize = k_PacketSize, MaxPacketCount = 30, PacketDelayMs = 100
            };

            m_Driver = new UdpNetworkDriver(simulatorParams, reliabilityParams);
            NetworkEndPoint endpoint = NetworkEndPoint.AnyIpv4;
            endpoint.Port = 9000;
            if (m_Driver.Bind(endpoint) != 0)
            {
                Debug.Log("Failed to bind to port 9000");
            }
            else
            {
                m_Driver.Listen();
                Debug.Log("driver listening on port 9000");
            }

            currentId = new NativeList <int>(1, Allocator.Persistent);
            currentId.Add(0);
        }
        else
        {
            serverJobHandle = m_Driver.ScheduleUpdate(inputDeps);
            serverJobHandle = new ListenForConnectionsJob
            {
                commandBuffer = m_Barrier.CreateCommandBuffer(),
                driver        = m_Driver,
            }.Schedule(serverJobHandle);

            serverJobHandle.Complete();

            serverJobHandle = new UpdateServerJob
            {
                commandBuffer = m_Barrier.CreateCommandBuffer().ToConcurrent(),
                driver        = m_Driver.ToConcurrent(),
                id            = currentId.AsDeferredJobArray()
            }.Schedule(this, serverJobHandle);

            m_Barrier.AddJobHandleForProducer(serverJobHandle);
            //Debug.Log("about to listen for connections");
            return(serverJobHandle);
        }

        return(inputDeps);
    }
Beispiel #8
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            JobHandle bulletHandle;
            JobHandle asteroidHandle;
            JobHandle levelHandle;
            JobHandle settingsHandle;

            var asteroidJob = new DestroyAsteroidJob
            {
                commandBuffer = barrier.CreateCommandBuffer().ToConcurrent(),
                bulletChunks  = bulletGroup.CreateArchetypeChunkArrayAsync(Allocator.TempJob, out bulletHandle),
                bulletAgeType = GetArchetypeChunkComponentType <BulletAgeComponent>(true),
                positionType  = GetArchetypeChunkComponentType <Translation>(true),
                sphereType    = GetArchetypeChunkComponentType <CollisionSphereComponent>(true),
                entityType    = GetArchetypeChunkEntityType(),
                level         = m_LevelGroup.ToComponentDataArrayAsync <LevelComponent>(Allocator.TempJob, out levelHandle)
            };
            var shipJob = new DestroyShipJob
            {
                commandBuffer    = barrier.CreateCommandBuffer().ToConcurrent(),
                asteroidChunks   = asteroidGroup.CreateArchetypeChunkArrayAsync(Allocator.TempJob, out asteroidHandle),
                bulletChunks     = asteroidJob.bulletChunks,
                bulletAgeType    = asteroidJob.bulletAgeType,
                positionType     = asteroidJob.positionType,
                sphereType       = asteroidJob.sphereType,
                playerIdType     = GetArchetypeChunkComponentType <PlayerIdComponentData>(),
                entityType       = asteroidJob.entityType,
                serverSettings   = settingsGroup.ToComponentDataArrayAsync <ServerSettings>(Allocator.TempJob, out settingsHandle),
                playerClearQueue = playerClearQueue.AsParallelWriter(),
                level            = asteroidJob.level
            };
            var asteroidDep = JobHandle.CombineDependencies(inputDeps, bulletHandle, levelHandle);
            var shipDep     = JobHandle.CombineDependencies(asteroidDep, asteroidHandle, settingsHandle);

            var h1 = asteroidJob.Schedule(asteroidGroup, asteroidDep);
            var h2 = shipJob.Schedule(shipGroup, shipDep);

            var handle = JobHandle.CombineDependencies(h1, h2);

            barrier.AddJobHandleForProducer(handle);

            var cleanupShipJob = new ClearShipPointerJob
            {
                playerClearQueue = playerClearQueue,
                commandTarget    = GetComponentDataFromEntity <CommandTargetComponent>()
            };
            var cleanupChunkJob = new ChunkCleanupJob
            {
                bulletChunks   = shipJob.bulletChunks,
                asteroidChunks = shipJob.asteroidChunks,
                level          = shipJob.level
            };

            return(JobHandle.CombineDependencies(cleanupShipJob.Schedule(h2), cleanupChunkJob.Schedule(handle)));
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        inputDeps.Complete();

        JobHandle clientJobHandle;

        if (!m_Driver.IsCreated)
        {
            ReliableUtility.Parameters reliabilityParams = new ReliableUtility.Parameters {
                WindowSize = 32
            };
            SimulatorUtility.Parameters simulatorParams = new SimulatorUtility.Parameters {
                MaxPacketSize = k_PacketSize, MaxPacketCount = 30, PacketDelayMs = 100
            };

            m_Driver = new UdpNetworkDriver(simulatorParams, reliabilityParams);

            m_Server_EndPoint      = NetworkEndPoint.LoopbackIpv4;
            m_Server_EndPoint.Port = 9000;
        }
        else
        {
            clientJobHandle = m_Driver.ScheduleUpdate(inputDeps);

            if (m_Server_EndPoint.IsValid && m_ConnectionGroup.IsEmptyIgnoreFilter)
            {
                //Debug.Log("client job handle about to be created");
                clientJobHandle = new SendConnectionRequestJob
                {
                    commandBuffer  = m_Barrier.CreateCommandBuffer(),
                    driver         = m_Driver,
                    serverEndPoint = m_Server_EndPoint,
                }.Schedule(clientJobHandle);
            }

            clientJobHandle.Complete();

            clientJobHandle = new UpdateClientJob
            {
                commandBuffer  = m_Barrier.CreateCommandBuffer().ToConcurrent(),
                driver         = m_Driver.ToConcurrent(),
                serverEndPoint = m_Server_EndPoint,
            }.Schedule(this, clientJobHandle);

            m_Barrier.AddJobHandleForProducer(clientJobHandle);

            return(clientJobHandle);
        }


        return(inputDeps);
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (_options == null)
            {
                _options = GameObject.Find("Options").GetComponent <Options>();
            }

            inputDeps = JobHandle.CombineDependencies(inputDeps, _terrain.UpdateCacheJob);
            var       blockHitCounts = new NativeArray <int>(_options.terrainSizeX * _options.terrainSizeZ, Allocator.TempJob);
            JobHandle outputJob      = new UpdateCannonballJob
            {
                PlayerCenterPosition = _playerPosCache.PlayerPosition + new float3(0, PLAYER_RADIUS, 0),
                ElapsedTime          = Time.time,
                TerrainSize          = new int2(_options.terrainSizeX, _options.terrainSizeZ),
                EnableInvincibility  = _options.invincibility,
                BlockHeights         = _terrain.CachedBlockHeights,
                BlockEntities        = _terrain.BlockEntities,
                BlockHitCounts       = blockHitCounts,
                BoxHeightDamage      = _options.boxHeightDamage,
                CommandBuffer        = _barrier.CreateCommandBuffer().ToConcurrent(),
            }.Schedule(_cannonballQuery, inputDeps);

            _barrier.AddJobHandleForProducer(outputJob);
            return(outputJob);
        }
Beispiel #11
0
    protected override void OnUpdate()
    {
        var ecb     = BeginSimulationEntityCommandBufferSystem.CreateCommandBuffer();
        var prefabs = GetSingleton <EntityPrefabs>();

        Entities
        .WithName("Spawn_Balls")
        .ForEach((ref BallSpawner spawner, in LocalToWorld localToWorld) => {
            var r  = spawner.Random.NextFloat2Direction();
            var xz = float3(r.x, 0, r.y);
            var up = float3(0, 1, 0);

            spawner.TimeRemainder += spawner.SpawnsPerTick;
            while (spawner.TimeRemainder >= 1)
            {
                var ball = ecb.Instantiate(prefabs.Ball);

                ecb.SetComponent(ball, new Translation {
                    Value = localToWorld.Position
                });
                ecb.SetComponent(ball, new Rotation {
                    Value = Quaternion.LookRotation(xz, up)
                });
                spawner.TimeRemainder--;
            }
        })
        .WithBurst()
        .Schedule();
        BeginSimulationEntityCommandBufferSystem.AddJobHandleForProducer(Dependency);
    }
Beispiel #12
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (m_Prefab == Entity.Null)
            {
                var prefabs       = GetSingleton <GhostPrefabCollectionComponent>();
                var serverPrefabs = EntityManager.GetBuffer <GhostPrefabBuffer>(prefabs.serverPrefabs);
                m_Prefab = serverPrefabs[AsteroidsGhostSerializerCollection.FindGhostType <ShipSnapshotData>()].Value;
                m_Radius = EntityManager.GetComponentData <CollisionSphereComponent>(m_Prefab).radius;
            }

            JobHandle levelHandle;
            var       spawnJob = new SpawnJob
            {
                commandBuffer           = barrier.CreateCommandBuffer(),
                playerStateFromEntity   = GetComponentDataFromEntity <PlayerStateComponentData>(),
                commandTargetFromEntity = GetComponentDataFromEntity <CommandTargetComponent>(),
                networkIdFromEntity     = GetComponentDataFromEntity <NetworkIdComponent>(),
                shipPrefab = m_Prefab,
                shipRadius = m_Radius,
                level      = m_LevelGroup.ToComponentDataArray <LevelComponent>(Allocator.TempJob, out levelHandle),
                rand       = new Unity.Mathematics.Random((uint)Stopwatch.GetTimestamp())
            };
            var handle = spawnJob.ScheduleSingle(this, JobHandle.CombineDependencies(inputDeps, levelHandle));

            barrier.AddJobHandleForProducer(handle);
            return(handle);
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityCommandBuffer.Concurrent CommandBuffer = m_EntityCommandBuffer.CreateCommandBuffer().ToConcurrent();

        JobHandle handle = Entities
                           .WithNone <TC_CooldownRunning>()
                           .WithAll <TC_CooldownCompleted, TC_CreationCooldown>()
                           .ForEach(
            (Entity entity, int entityInQueryIndex) =>
        {
            CommandBuffer.RemoveComponent <TC_CreationCooldown>(entityInQueryIndex, entity);
            CommandBuffer.RemoveComponent <TC_CooldownCompleted>(entityInQueryIndex, entity);
            CommandBuffer.AddComponent <PlayMonoAnimation_C>(entityInQueryIndex, entity);
            CommandBuffer.SetComponent(entityInQueryIndex, entity, new PlayMonoAnimation_C
            {
                id = UnityEngine.Animator.StringToHash("Caixa@Open")
            });
        })
                           .WithoutBurst()
                           .Schedule(inputDeps);

        handle.Complete();

        return(handle);
    }
Beispiel #14
0
    protected override void OnUpdate()
    {
        var playerEntity            = GetSingletonEntity <NetworkIdComponent>();
        var commandTargetFromEntity = GetComponentDataFromEntity <CommandTargetComponent>();

        var commandBuffer = m_Barrier.CreateCommandBuffer().AsParallelWriter();

        Entities
        .WithNone <GhostShipState>()
        .WithAll <ShipTagComponentData, PredictedGhostComponent>()
        .ForEach((Entity entity) => {
            var state          = commandTargetFromEntity[playerEntity];
            state.targetEntity = entity;
            commandTargetFromEntity[playerEntity] = state;
            commandBuffer.AddComponent(0, entity, new GhostShipState());
        }).Schedule();

        Entities.WithNone <SnapshotData>()
        .WithAll <GhostShipState>()
        .WithNativeDisableParallelForRestriction(commandTargetFromEntity)
        .ForEach((Entity ent, int entityInQueryIndex) => {
            var commandTarget = commandTargetFromEntity[playerEntity];

            if (ent == commandTarget.targetEntity)
            {
                commandTarget.targetEntity            = Entity.Null;
                commandTargetFromEntity[playerEntity] = commandTarget;
            }
            commandBuffer.RemoveComponent <GhostShipState>(entityInQueryIndex, ent);
        }).ScheduleParallel();
        m_Barrier.AddJobHandleForProducer(Dependency);
    }
    protected override void OnUpdate()
    {
        var entityType = GetEntityTypeHandle();

        var playerEntity            = GetSingletonEntity <NetworkIdComponent>();
        var commandTargetFromEntity = GetComponentDataFromEntity <CommandTargetComponent>();

        var commandBuffer = m_Barrier.CreateCommandBuffer().AsParallelWriter();

        Entities.WithNone <GhostShipState>().WithAll <ShipTagComponentData, PredictedGhostComponent>().ForEach((Entity entity) => {
            var state          = commandTargetFromEntity[playerEntity];
            state.targetEntity = entity;
            commandTargetFromEntity[playerEntity] = state;
            commandBuffer.AddComponent(0, entity, new GhostShipState());
        }).Schedule();

        var destroyJob = new DestroyJob
        {
            commandBuffer           = commandBuffer,
            entityType              = entityType,
            playerEntity            = playerEntity,
            commandTargetFromEntity = GetComponentDataFromEntity <CommandTargetComponent>()
        };
        var inputDeps = destroyJob.Schedule(m_DestroyGroup, Dependency);

        m_Barrier.AddJobHandleForProducer(inputDeps);
        Dependency = inputDeps;
    }
Beispiel #16
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            // Deserialize the command type from the reader stream
            // Execute the RPC
            inputDeps = JobHandle.CombineDependencies(inputDeps, m_ReceiveSystem.LastDriverWriter);
            var execJob = new RpcExecJob
            {
                commandBuffer    = m_Barrier.CreateCommandBuffer().ToConcurrent(),
                entityType       = GetArchetypeChunkEntityType(),
                connectionType   = GetArchetypeChunkComponentType <NetworkStreamConnection>(),
                inBufferType     = GetArchetypeChunkBufferType <IncomingRpcDataStreamBufferComponent>(),
                outBufferType    = GetArchetypeChunkBufferType <OutgoingRpcDataStreamBufferComponent>(),
                execute          = m_RpcData,
                hashToIndex      = m_RpcTypeHashToIndex,
                driver           = m_ReceiveSystem.ConcurrentDriver,
                reliablePipeline = m_ReceiveSystem.ReliablePipeline,
                protocolVersion  = GetSingleton <NetworkProtocolVersion>()
            };
            var handle = execJob.Schedule(m_RpcBufferGroup, inputDeps);

            m_Barrier.AddJobHandleForProducer(handle);
            handle = m_ReceiveSystem.Driver.ScheduleFlushSend(handle);
            m_ReceiveSystem.LastDriverWriter = handle;
            return(handle);
        }
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        EntityCommandBuffer.Concurrent commandBuffer = m_EntityCommandBuffer.CreateCommandBuffer().ToConcurrent();


        JobHandle jobConfigureDrop = Entities
                                     .WithAll <TC_PerformingAction>()
                                     .ForEach((Entity entity, int entityInQueryIndex, in Translation translation, in C_HoldComponentData holdComponent, in DirectionData directionData) =>
        {
            int2 i2Direction     = directionData.directionLook;
            float fXDropPosition = translation.Value.x + (float)i2Direction.x / 2;

            commandBuffer.AddComponent <MC_RemoveInHold>(entityInQueryIndex, holdComponent.Item);
            commandBuffer.SetComponent(entityInQueryIndex, holdComponent.Item, new MC_RemoveInHold
            {
                Position = new float3(fXDropPosition, translation.Value.y, 0)
            });
            commandBuffer.RemoveComponent <TC_PerformingAction>(entityInQueryIndex, entity);
            commandBuffer.RemoveComponent <C_HoldComponentData>(entityInQueryIndex, entity);
            commandBuffer.AddComponent <TC_CooldownAction>(entityInQueryIndex, entity);
            commandBuffer.AddComponent <TC_CooldownRunning>(entityInQueryIndex, entity);
            commandBuffer.SetComponent(entityInQueryIndex, entity, new C_CooldownComponent
            {
                Cooldown  = 1,
                DeltaTime = 0
            });
        }).Schedule(inputDeps);
Beispiel #18
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            if (m_LevelGroup.IsEmptyIgnoreFilter)
            {
                var settings = GetSingleton <ServerSettings>();
                var level    = EntityManager.CreateEntity();
                EntityManager.AddComponentData(level, new LevelComponent
                {
                    width          = settings.levelWidth,
                    height         = settings.levelHeight,
                    playerForce    = settings.playerForce,
                    bulletVelocity = settings.bulletVelocity
                });
                return(inputDeps);
            }
            JobHandle levelDep;
            var       job = new RequestLoadJob
            {
                commandBuffer = m_Barrier.CreateCommandBuffer(),
                level         = m_LevelGroup.ToComponentDataArray <LevelComponent>(Allocator.TempJob, out levelDep)
            };
            var handle = job.ScheduleSingle(this, JobHandle.CombineDependencies(inputDeps, levelDep));

            m_Barrier.AddJobHandleForProducer(handle);
            return(handle);
        }
Beispiel #19
0
    protected override void OnUpdate()
    {
        var commandBuffer = m_Barrier.CreateCommandBuffer();

        var serverData   = GetSingleton <GameSettingsComponent>();
        var gameNameData = GetSingleton <ServerDataComponent>();

        Entities
        .WithNone <SentClientGameRpcTag>()
        .ForEach((Entity entity, in NetworkIdComponent netId) =>
        {
            commandBuffer.AddComponent(entity, new SentClientGameRpcTag());
            var req = commandBuffer.CreateEntity();
            commandBuffer.AddComponent(req, new SendClientGameRpc
            {
                levelWidth     = serverData.levelWidth,
                levelHeight    = serverData.levelHeight,
                levelDepth     = serverData.levelDepth,
                playerForce    = serverData.playerForce,
                bulletVelocity = serverData.bulletVelocity,
                gameName       = gameNameData.GameName
            });

            commandBuffer.AddComponent(req, new SendRpcCommandRequestComponent {
                TargetConnection = entity
            });
        }).Schedule();

        m_Barrier.AddJobHandleForProducer(Dependency);
    }
        protected override void OnUpdate()
        {
            var actualNumSpawners = q_spawners.CalculateEntityCount();

            var ecb = _ecb.CreateCommandBuffer().AsParallelWriter();

            Entities
            .ForEach((int entityInQueryIndex, in SpawnerEntityData spawnerEntity, in SpawnerNumberData spawnerNumber) =>
            {
                var suppoedNumSpawners = spawnerNumber.Value;
                if (suppoedNumSpawners > actualNumSpawners)
                {
                    //Get the difference first.
                    var diffNumSpawner = suppoedNumSpawners - actualNumSpawners;
                    for (int i = 0; i < diffNumSpawner; i++)
                    {
                        var spawner = ecb.Instantiate(entityInQueryIndex, spawnerEntity.spawner);
#if UNITY_EDITOR
                        //Debugging purposes.
                        ecb.SetComponent(entityInQueryIndex, spawner, new PatternBlobIndexData {
                            index = i
                        });
                        ecb.SetComponent(entityInQueryIndex, spawner, new BulletBlobIndexData {
                            index = i
                        });
#endif
                    }
                }
            }).ScheduleParallel();
        protected override void OnUpdate()
        {
            uint interpolatedTick = _networkTimeSystem.interpolateTargetTick;
            uint predictedTick    = _networkTimeSystem.predictTargetTick;
            var  commandBuffer    = _barrier.CreateCommandBuffer();

            // 插值类型的Ghost销毁
            while (_interpolatedDespawnQueue.Count > 0 &&
                   !SequenceHelpers.IsNewer(_interpolatedDespawnQueue.Peek().Tick, interpolatedTick))
            {
                var desspawnGhost = _interpolatedDespawnQueue.Dequeue();
                if (_ghostReceiveSystem.SpawnedGhostEntityMap.TryGetValue(desspawnGhost.Ghost, out Entity ent))
                {
                    commandBuffer.DestroyEntity(ent);
                    _ghostReceiveSystem.SpawnedGhostEntityMap.Remove(desspawnGhost.Ghost);
                }
            }

            // 预测类型的Ghost销毁
            while (_predictedDespawnQueue.Count > 0 &&
                   !SequenceHelpers.IsNewer(_predictedDespawnQueue.Peek().Tick, predictedTick))
            {
                var desspawnGhost = _predictedDespawnQueue.Dequeue();
                if (_ghostReceiveSystem.SpawnedGhostEntityMap.TryGetValue(desspawnGhost.Ghost, out Entity ent))
                {
                    commandBuffer.DestroyEntity(ent);
                    _ghostReceiveSystem.SpawnedGhostEntityMap.Remove(desspawnGhost.Ghost);
                }
            }
        }
Beispiel #22
0
        protected override void OnUpdate()
        {
            var spawnListEnt = GetSingletonEntity <PredictedGhostSpawnList>();
            var spawnList    = EntityManager.GetBuffer <PredictedGhostSpawn>(spawnListEnt);

            var commandBuffer = _barrier.CreateCommandBuffer();

            Entities.ForEach((DynamicBuffer <GhostSpawnBuffer> ghosts, DynamicBuffer <SnapshotDataBuffer> data) =>
            {
                for (int i = 0; i < ghosts.Length; i++)
                {
                    var ghost = ghosts[i];
                    if (ghost.SpawnType == GhostSpawnBuffer.Type.Predicted)
                    {
                        for (int j = 0; j < spawnList.Length; j++)
                        {
                            if (ghost.GhostType == spawnList[j].GhostType)
                            {
                                ghost.PredictedSpawnEntity = spawnList[j].Entity;
                                spawnList[j] = spawnList[spawnList.Length - 1];
                                spawnList.RemoveAt(spawnList.Length - 1);

                                commandBuffer.RemoveComponent <PredictedGhostSpawnPendingComponent>(
                                    ghost.PredictedSpawnEntity);
                                break;
                            }
                        }

                        ghosts[i] = ghost;
                    }
                }
            });
        }
Beispiel #23
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var projectileTranslations = m_projectilesQuery.ToComponentDataArray <Translation>(Allocator.TempJob);
        var projectileCollisions   = m_projectilesQuery.ToComponentDataArray <CollisionSize>(Allocator.TempJob);
        var projectiles            = m_projectilesQuery.ToEntityArray(Allocator.TempJob);

        poolLocations.Clear();
        EntityManager.GetAllUniqueSharedComponentData <ProjectilePoolLocation>(poolLocations);

        if (projectileCollisions.Length > 0 && poolLocations.Count > 1)
        {
            var job = new ProjectileCollisionJob
            {
                ProjectileTranslations = projectileTranslations,
                ProjectileCollisions   = projectileCollisions,
                Projectiles            = projectiles,
                ECB          = m_beginSimEcbSystem.CreateCommandBuffer().ToConcurrent(),
                PoolLocation = poolLocations[1].Value
            };

            inputDeps = job.Schedule(this, inputDeps);
            m_projectilesQuery.AddDependency(inputDeps);
            m_beginSimEcbSystem.AddJobHandleForProducer(inputDeps);
        }
        else
        {
            projectileTranslations.Dispose();
            projectileCollisions.Dispose();
            projectiles.Dispose();
        }

        return(inputDeps);
    }
Beispiel #24
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (Time.time - oldTime > updateTime)
        {
            oldTime = Time.time;

            var nativeArr = new NativeList <PlayerState>(100, Allocator.TempJob);

            var playerStateJob = new CreatePlayerStateJob()
            {
                arr = nativeArr
            }.ScheduleSingle(this, inputDeps);

            playerStateJob.Complete();

            var serializeJob = new SerializeStateJob()
            {
                CommandBuffer = m_EndFrameBarrier.CreateCommandBuffer(),
                players       = nativeArr
            }.Schedule(playerStateJob);

            m_EndFrameBarrier.AddJobHandleForProducer(serializeJob);

            serializeJob.Complete();

            nativeArr.Dispose();

            return(serializeJob);
        }
        return(inputDeps);
    }
Beispiel #25
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var entityType = GetArchetypeChunkEntityType();

        JobHandle playerHandle;
        var       playerEntity = playerGroup.ToEntityArray(Allocator.TempJob, out playerHandle);

        var updateJob = new UpdateJob
        {
            snapshotFromEntity = GetBufferFromEntity <ShipSnapshotData>(),
            targetTick         = NetworkTimeSystem.interpolateTargetTick
        };

        inputDeps = updateJob.Schedule(this, inputDeps);
        var destroyJob = new DestroyJob
        {
            commandBuffer         = m_Barrier.CreateCommandBuffer().ToConcurrent(),
            entityType            = entityType,
            playerEntity          = playerEntity,
            playerStateFromEntity = GetComponentDataFromEntity <PlayerStateComponentData>()
        };

        inputDeps = destroyJob.Schedule(destroyGroup, JobHandle.CombineDependencies(inputDeps, playerHandle));
        m_Barrier.AddJobHandleForProducer(inputDeps);
        return(inputDeps);
    }
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            inputDeps.Complete();
            var barrier = m_Barrier.CreateCommandBuffer();

            Entities
            .WithoutBurst()
            .WithAll <MeshAssignTag>()
            .ForEach((Entity entity, ref ChunkComponent cc, in RenderMesh rnd, in DynamicBuffer <IntBuffer> triangles, in DynamicBuffer <VectorBuffer> vertices) =>
            {
                barrier.RemoveComponent <MeshAssignTag>(entity);
                var trianglesArray = new int[triangles.Length];;                         // triangles.Reinterpret<int>().ToArray();
                var verticesArray  = new Vector3[vertices.Length];                       // vertices.Reinterpret<Vector3>().ToArray();

                for (int i = 0; i < triangles.Length; i++)
                {
                    trianglesArray[i] = triangles[i];
                }
                for (int i = 0; i < vertices.Length; i++)
                {
                    verticesArray[i] = vertices[i];
                }
                rnd.mesh.Clear();
                rnd.mesh.vertices  = verticesArray;
                rnd.mesh.triangles = trianglesArray;
                rnd.mesh.normals   = verticesArray.Select(x => new Vector3(0, 0, 1)).ToArray();
                rnd.mesh.RecalculateBounds();

                barrier.SetSharedComponent(entity, rnd);
            }).Run();
Beispiel #27
0
        protected override void OnUpdate()
        {
            var commandBuffer   = m_Barrier.CreateCommandBuffer().ToConcurrent();
            var rpcFromEntity   = GetBufferFromEntity <OutgoingRpcDataStreamBufferComponent>();
            var levelFromEntity = GetComponentDataFromEntity <LevelComponent>();
            var levelSingleton  = m_LevelSingleton;
            var rpcQueue        = m_RpcQueue;

            Entities.ForEach((Entity entity, int nativeThreadIndex, in LevelLoadRequest request, in ReceiveRpcCommandRequestComponent requestSource) =>
            {
                commandBuffer.DestroyEntity(nativeThreadIndex, entity);
                // Check for disconnects
                if (!rpcFromEntity.Exists(requestSource.SourceConnection))
                {
                    return;
                }
                // set the level size - fake loading of level
                levelFromEntity[levelSingleton] = new LevelComponent
                {
                    width          = request.width,
                    height         = request.height,
                    playerForce    = request.playerForce,
                    bulletVelocity = request.bulletVelocity
                };
                commandBuffer.AddComponent(nativeThreadIndex, requestSource.SourceConnection, new PlayerStateComponentData());
                commandBuffer.AddComponent(nativeThreadIndex, requestSource.SourceConnection, default(NetworkStreamInGame));
                rpcQueue.Schedule(rpcFromEntity[requestSource.SourceConnection], new RpcLevelLoaded());
            }).Schedule();
 private void Start()
 {
     if (spawnAtEcs)
     {
         commandBufferSystem = World.DefaultGameObjectInjectionWorld
                               .GetOrCreateSystem <BeginSimulationEntityCommandBufferSystem>();
         var entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(ecsPrefab,
                                                                                   new GameObjectConversionSettings(World.DefaultGameObjectInjectionWorld,
                                                                                                                    GameObjectConversionUtility.ConversionFlags.SceneViewLiveLink, new BlobAssetStore()));
         var jobHandle = new MyEcsSpawnJob()
         {
             CommandBuffer = commandBufferSystem.CreateCommandBuffer(),
             NumberOfCubes = numberOfCubes,
             EcsPrefab     = entityPrefab,
             MyRandom      = new Random((uint)UnityEngine.Random.Range(1, 100000))
         }.Schedule();
         commandBufferSystem.AddJobHandleForProducer(jobHandle);
     }
     else
     {
         for (var i = 0; i < numberOfCubes; i++)
         {
             Instantiate(monoPrefab).transform.position = new Vector3(UnityEngine.Random.Range(-100, 100f), 0, 0);
         }
     }
 }
Beispiel #29
0
        private JobHandle ConsiderOwner(JobHandle prepareDistDataJobHandle, NativeArray <OwnerPosContainer> ownerPosContainers)
        {
            // ecb改成单线程
            // create group
            // group to array
            var entities = m_placeGroup.ToEntityArray(Allocator.TempJob);
            var setPlaceOwnerConsiderers = m_placeGroup.ToComponentDataArray <SetPlaceOwnerConsiderer>(Allocator.TempJob);
            var places       = m_placeGroup.ToComponentDataArray <Place>(Allocator.TempJob);
            var translations = m_placeGroup.ToComponentDataArray <Translation>(Allocator.TempJob);

            var ownerConsiderJobHandle = new OwnerConsiderJob
            {
                BeginEcb = m_beginEcbSystem.CreateCommandBuffer(),
                EndEcb   = m_endEcbSystem.CreateCommandBuffer(),
                Entities = entities,
                SetPlaceOwnerConsiderers = setPlaceOwnerConsiderers,
                Places          = places,
                Translations    = translations,
                OwnPlacesBuffer = GetBufferFromEntity <MyOwnPlace>(),
                OwnersPos       = ownerPosContainers,
            }.Schedule(prepareDistDataJobHandle);

            // TEST 是否可以直接dispose?
            //      看看parentSystem是怎么dispose的。
            //          是在manager操作后dispose的,确保一定完成。
            // 试试不用mananger行不行。
            //      结果:失败,
            //          换成自动模式。
            // entities.Dispose();
            // setPlaceOwnerConsiderers.Dispose();
            // places.Dispose();
            // translations.Dispose();
            return(ownerConsiderJobHandle);
        }
Beispiel #30
0
    protected override JobHandle OnUpdate(JobHandle handle)
    {
        if (init && count > 0)
        {
            em.DestroyEntity(boubleQuery);
            count = 0;
            return(handle);
        }

        count = boubleQuery.CalculateEntityCount();
        var f = GetSingleton <SpawnerRndAreaComp>();

        if (sd.rangeMultChanged)
        {
            List <float> ranges = new List <float>();
            ranges.Add(sd.defaultGrav);
            for (int i = 1; i < 6; i++)
            {
                ranges.Add(ranges[i - 1] * sd.rangeMult);
            }
            f.smallRange  = ranges[1];
            f.mediumRange = ranges[2];
            f.largeRange  = ranges[3];
            f.hugeRange   = ranges[4];
            f.superRange  = ranges[5];
            ranges.Clear();
            sd.rangeMultChanged = false;
            SetSingleton <SpawnerRndAreaComp>(f);
        }

        createCount = sd.totalCount - count;

        for (int i = 0; i < createCount; i++)
        {
            rndDir     = _random.NextFloat2Direction();
            rndPos.x   = rndDir.x;
            rndPos.y   = 0;
            rndPos.z   = rndDir.y;
            rndPos    *= init ? _random.NextFloat(0, sd.cylinderRadius) : sd.cylinderRadius;
            rndPos.y   = _random.NextFloat(-sd.cylinderHeight, sd.cylinderHeight);
            posList[i] = rndPos;
        }

        handle = new Joby {
            ecb          = _ecbs.CreateCommandBuffer().ToConcurrent(),
            f            = f, sd = sd,
            prefabEntity = _prefabEntity,
            absorb       = sd.absorb,
            bounce       = sd.bounce,
            posList      = posList,
            bubFrac      = .5f / BoubleAuth._grad
        }.Schedule(createCount, 10, handle);

        _ecbs.AddJobHandleForProducer(handle);

        init = false;

        return(handle);
    }