protected override void OnUpdate() { bool isConnected = !m_clientConnectionGroup.IsEmptyIgnoreFilter; // Trigger connect / disconnect events if (ClientConnectionState == ConnectionState.TriggerDisconnect && isConnected) { var con = m_clientConnectionGroup.ToComponentDataArray <NetworkStreamConnection>(Allocator.TempJob); m_prevEndPoint = World.GetExistingManager <NetworkStreamReceiveSystem>().Driver.RemoteEndPoint(con[0].Value); for (int i = 0; i < con.Length; ++i) { World.GetExistingManager <NetworkStreamReceiveSystem>().Driver.Disconnect(con[i].Value); } con.Dispose(); EntityManager.AddComponent(m_clientConnectionGroup, ComponentType.ReadWrite <NetworkStreamDisconnected>()); } /*else if (ClientConnectionState == ConnectionState.TriggerTimeout && isConnected) * { * EntityManager.AddComponent(m_clientConnectionGroup, ComponentType.ReadWrite<NetworkStreamDisconnected>()); * }*/ else if (ClientConnectionState == ConnectionState.TriggerConnect && !isConnected && m_prevEndPoint.IsValid) { World.GetExistingManager <NetworkStreamReceiveSystem>().Connect(m_prevEndPoint); } // Update connection status ClientConnectionState = isConnected ? ConnectionState.Connected : (m_prevEndPoint.IsValid ? ConnectionState.NotConnected : ConnectionState.Uninitialized); }
NativeArray <SceneTag> ExternalRefToSceneTag(NativeArray <ExternalEntityRefInfo> externalEntityRefInfos, Allocator allocator) { var sceneTags = new NativeArray <SceneTag>(externalEntityRefInfos.Length, allocator); using (var sectionDataEntities = m_SectionData.ToEntityArray(Allocator.TempJob)) { using (var sectionData = m_SectionData.ToComponentDataArray <SceneData>(Allocator.TempJob)) { for (int i = 0; i < sectionData.Length; ++i) { for (int j = 0; j < externalEntityRefInfos.Length; ++j) { if ( externalEntityRefInfos[j].SceneGUID == sectionData[i].SceneGUID && externalEntityRefInfos[j].SubSectionIndex == sectionData[i].SubSectionIndex ) { sceneTags[j] = new SceneTag { SceneEntity = sectionDataEntities[i] }; break; } } } } } return(sceneTags); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { if (m_ContactModifierGroup.CalculateLength() == 0) { return(inputDeps); } if (m_StepPhysicsWorld.Simulation.Type == SimulationType.NoPhysics) { return(inputDeps); } var modifiers = m_ContactModifierGroup.ToComponentDataArray <ModifyNarrowphaseContacts>(Allocator.TempJob); var surfaceNormal = modifiers[0].surfaceNormal; var surfaceRBIdx = m_BuildPhysicsWorld.PhysicsWorld.GetRigidBodyIndex(modifiers[0].surfaceEntity); SimulationCallbacks.Callback callback = (ref ISimulation simulation, JobHandle inDeps) => { inDeps.Complete(); // TODO: shouldn't be needed (jobify the below) SimulationData.Contacts.Iterator iterator = simulation.Contacts.GetIterator(); while (iterator.HasItemsLeft()) { ContactHeader manifold = iterator.GetNextContactHeader(); bool bUpdateNormal = (manifold.BodyPair.BodyAIndex == surfaceRBIdx) || (manifold.BodyPair.BodyBIndex == surfaceRBIdx); float distanceScale = 1; if (bUpdateNormal) { var newNormal = surfaceNormal; distanceScale = math.dot(newNormal, manifold.Normal); //<todo.eoin.hpi Feels pretty weird. //<todo.eoin.hp Need to make this work if user has read a contact iterator.SetManifoldNormal(newNormal); } for (int i = 0; i < manifold.NumContacts; i++) { ContactPoint cp = iterator.GetNextContact(); if (bUpdateNormal) { cp.Distance *= distanceScale; iterator.UpdatePreviousContact(cp); } } } return(inDeps); }; modifiers.Dispose(); m_StepPhysicsWorld.EnqueueCallback(SimulationCallbacks.Phase.PostCreateContacts, callback); return(inputDeps); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { JobHandle bulletHandle; JobHandle asteroidHandle; JobHandle levelHandle; JobHandle settingsHandle; var asteroidJob = new DestroyAsteroidJob { commandBuffer = barrier.CreateCommandBuffer().ToConcurrent(), bulletChunks = bulletGroup.CreateArchetypeChunkArray(Allocator.TempJob, out bulletHandle), bulletAgeType = GetArchetypeChunkComponentType <BulletAgeComponentData>(true), positionType = GetArchetypeChunkComponentType <Translation>(true), sphereType = GetArchetypeChunkComponentType <CollisionSphereComponentData>(true), entityType = GetArchetypeChunkEntityType(), level = m_LevelGroup.ToComponentDataArray <LevelComponent>(Allocator.TempJob, out levelHandle) }; var shipJob = new DestroyShipJob { commandBuffer = barrier.CreateCommandBuffer().ToConcurrent(), asteroidChunks = asteroidGroup.CreateArchetypeChunkArray(Allocator.TempJob, out asteroidHandle), bulletChunks = asteroidJob.bulletChunks, bulletAgeType = asteroidJob.bulletAgeType, positionType = asteroidJob.positionType, sphereType = asteroidJob.sphereType, playerIdType = GetArchetypeChunkComponentType <PlayerIdComponentData>(), entityType = asteroidJob.entityType, serverSettings = settingsGroup.ToComponentDataArray <ServerSettings>(Allocator.TempJob, out settingsHandle), playerClearQueue = playerClearQueue.ToConcurrent(), 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, playerState = GetComponentDataFromEntity <PlayerStateComponentData>() }; var cleanupChunkJob = new ChunkCleanupJob { bulletChunks = shipJob.bulletChunks, asteroidChunks = shipJob.asteroidChunks, level = shipJob.level }; return(JobHandle.CombineDependencies(cleanupShipJob.Schedule(h2), cleanupChunkJob.Schedule(handle))); }
protected override void OnUpdate() { var componentData = m_TestGroup.ToComponentDataArray <EcsTestData>(Allocator.TempJob); var cd0 = componentData[0].value; var index = StoredData[0] + cd0 + 1; StoredData.Dispose(); componentData.Dispose(); StoredData = new NativeArray <int>(1, Allocator.Temp); StoredData[0] = index; }
void TestSourceOddValues(int version, ComponentGroup group) { var testData = group.ToComponentDataArray <EcsTestData>(Allocator.TempJob); Assert.AreEqual(50, testData.Length); for (int i = 0; i < 50; i++) { Assert.AreEqual(1 + (i * 2), testData[i].value); } testData.Dispose(); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { var colliders = m_AABBGroup.ToComponentDataArray <AABB>(Allocator.TempJob); var aabbCollisionJob = new AABBCollisionJob { Colliders = colliders, }; var collisionJobHandle = aabbCollisionJob.Schedule(colliders.Length, 32); collisionJobHandle.Complete(); colliders.Dispose(); return(collisionJobHandle); }
protected override unsafe void OnUpdate() { if (socket.AcceptNewConnection()) { socket.SendText(ghostList); } if (!socket.HasConnection) { return; } var connection = connectionGroup.ToComponentDataArray <NetworkSnapshotAck>(Allocator.TempJob); if (connection.Length == 0) { connection.Dispose(); return; } var stats = m_ReceiveSys.NetStats; var frame = connection[0].LastReceivedSnapshotByLocal; connection.Dispose(); if (frame <= lastFrame) { return; } if (lastFrame == 0) { lastFrame = frame - 1; } for (lastFrame = lastFrame + 1; lastFrame < frame; ++lastFrame) { for (int i = 0; i < ghostStatData.Length; ++i) { ghostStatData[i] = 0; } socket.SendBinary(ghostStatData, ghostStatData.Length); } var statBytes = (byte *)stats.GetUnsafeReadOnlyPtr(); for (int i = 0; i < ghostStatData.Length; ++i) { ghostStatData[i] = statBytes[i]; } socket.SendBinary(ghostStatData, ghostStatData.Length); }
private bool TryGetFirstPhaseConfig(ref PhaseConfig phaseConfig) { NativeArray <PhaseConfig> phaseConfigs = m_PhaseConfigGroup.ToComponentDataArray <PhaseConfig>( Allocator.TempJob); if (phaseConfigs.Length < 1) { phaseConfigs.Dispose(); return(false); } phaseConfig = phaseConfigs[0]; phaseConfigs.Dispose(); return(true); }
void UpdateRemoveParents() { var childEntities = m_RemovedParentsGroup.ToEntityArray(Allocator.TempJob); var previousParents = m_RemovedParentsGroup.ToComponentDataArray <PreviousParent>(Allocator.TempJob); for (int i = 0; i < childEntities.Length; i++) { var childEntity = childEntities[i]; var previousParentEntity = previousParents[i].Value; RemoveChildFromParent(childEntity, previousParentEntity); } EntityManager.RemoveComponent(m_RemovedParentsGroup, typeof(PreviousParent)); childEntities.Dispose(); previousParents.Dispose(); }
void UpdateNewParents() { var childEntities = m_NewParentsGroup.ToEntityArray(Allocator.TempJob); var parents = m_NewParentsGroup.ToComponentDataArray <Parent>(Allocator.TempJob); EntityManager.AddComponent(m_NewParentsGroup, typeof(PreviousParent)); for (int i = 0; i < childEntities.Length; i++) { var childEntity = childEntities[i]; var parentEntity = parents[i].Value; AddChildToParent(childEntity, parentEntity); } childEntities.Dispose(); parents.Dispose(); }
override protected JobHandle OnUpdate(JobHandle inputDeps) { if (shipGroup.IsEmptyIgnoreFilter) { return(inputDeps); } var trackJob = new ChunkTrackJob(); JobHandle gatherJob, levelHandle; trackJob.shipChunks = shipGroup.CreateArchetypeChunkArray(Allocator.TempJob, out gatherJob); trackJob.positionType = GetArchetypeChunkComponentType <Translation>(true); trackJob.stateType = GetArchetypeChunkComponentType <ShipStateComponentData>(true); trackJob.screenWidth = Screen.width; trackJob.screenHeight = Screen.height; trackJob.level = m_LevelGroup.ToComponentDataArray <LevelComponent>(Allocator.TempJob, out levelHandle); trackJob.teleport = teleport; return(trackJob.ScheduleSingle(this, JobHandle.CombineDependencies(inputDeps, gatherJob, levelHandle))); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { var mapEntityArray = mapGroup.ToEntityArray(Allocator.TempJob); Map map = EntityManager.GetSharedComponentData <Map>(mapEntityArray[0]); var mapArray = new NativeArray <int>(map.mapArray, Allocator.TempJob); var objArray = objGroup.ToComponentDataArray <PhysicsObject>(Allocator.TempJob); var job = new CollisionJob { rows = map.rows, cols = map.cols, mapArray = mapArray, objArray = objArray }; mapEntityArray.Dispose(); return(job.Schedule(this, inputDeps)); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { var settings = GetSingleton <ServerSettings>(); JobHandle levelHandle; var spawnJob = new SpawnJob { commandBuffer = barrier.CreateCommandBuffer(), playerStateFromEntity = GetComponentDataFromEntity <PlayerStateComponentData>(), networkIdFromEntity = GetComponentDataFromEntity <NetworkIdComponent>(), shipArchetype = settings.shipArchetype, playerRadius = settings.playerRadius, 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) { if (m_connectionGroup.IsEmptyIgnoreFilter) { // No connected players, just destroy all asteroids to save CPU inputDeps.Complete(); World.GetExistingManager <EntityManager>().DestroyEntity(asteroidGroup); return(default(JobHandle)); } var settings = GetSingleton <ServerSettings>(); var maxAsteroids = settings.numAsteroids; JobHandle gatherJob; var countJob = new CountJob { chunks = asteroidGroup.CreateArchetypeChunkArray(Allocator.TempJob, out gatherJob), count = count, entityType = GetArchetypeChunkEntityType() }; inputDeps = countJob.Schedule(JobHandle.CombineDependencies(inputDeps, gatherJob)); JobHandle levelHandle; var spawnJob = new SpawnJob { commandBuffer = barrier.CreateCommandBuffer(), count = count, targetCount = maxAsteroids, asteroidArchetype = settings.asteroidArchetype, asteroidRadius = settings.asteroidRadius, asteroidVelocity = settings.asteroidVelocity, level = m_LevelGroup.ToComponentDataArray <LevelComponent>(Allocator.TempJob, out levelHandle), rand = new Unity.Mathematics.Random((uint)Stopwatch.GetTimestamp()) }; var handle = spawnJob.Schedule(JobHandle.CombineDependencies(inputDeps, levelHandle)); barrier.AddJobHandleForProducer(handle); return(handle); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { var lineList = m_LineList; Camera.main.RemoveCommandBuffers(CameraEvent.AfterEverything); Camera.main.AddCommandBuffer(CameraEvent.AfterEverything, m_CommandBuffer); if (lineList.Length > MaxLines) { Debug.LogWarning("Trying to render " + lineList.Length + " but limit is " + MaxLines); lineList.ResizeUninitialized(MaxLines); } var renderOffset = m_RenderOffset[0]; NativeArray <Line> lines = lineList; m_Material.SetFloat("offsetX", renderOffset.x); m_Material.SetFloat("offsetY", renderOffset.y); m_Material.SetFloat("screenWidth", Screen.width); m_Material.SetFloat("screenHeight", Screen.height); m_Material.SetBuffer("lines", m_ComputeBuffer); m_ComputeBuffer.SetData(lines); m_CommandBuffer.Clear(); m_CommandBuffer.DrawProcedural(Matrix4x4.identity, m_Material, -1, MeshTopology.Triangles, lineList.Length * 6); lineList.Clear(); JobHandle levelHandle; var copyToListJob = new CopyToListJob(); copyToListJob.list = m_LineList; copyToListJob.queue = m_LineQueue; copyToListJob.renderOffset = m_RenderOffset; copyToListJob.deltaTime = Time.deltaTime; copyToListJob.level = m_LevelGroup.ToComponentDataArray <LevelComponent>(Allocator.TempJob, out levelHandle); return(copyToListJob.ScheduleSingle(this, JobHandle.CombineDependencies(inputDeps, levelHandle))); }
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 }); return(inputDeps); } JobHandle levelDep; var job = new RequestLoadJob { commandBuffer = m_Barrier.CreateCommandBuffer(), rpcQueue = m_RpcQueue, rpcBuffer = GetBufferFromEntity <OutgoingRpcDataStreamBufferComponent>(), level = m_LevelGroup.ToComponentDataArray <LevelComponent>(Allocator.TempJob, out levelDep) }; var handle = job.ScheduleSingle(this, JobHandle.CombineDependencies(inputDeps, levelDep)); m_Barrier.AddJobHandleForProducer(handle); return(handle); }
public void CreateEntitiesChainedJob() { var job = new CreateEntityAddToListJob(); job.entities = m_Manager.BeginExclusiveEntityTransaction(); job.createdEntities = new NativeList <Entity>(0, Allocator.TempJob); m_Manager.ExclusiveEntityTransactionDependency = job.Schedule(m_Manager.ExclusiveEntityTransactionDependency); m_Manager.ExclusiveEntityTransactionDependency = job.Schedule(m_Manager.ExclusiveEntityTransactionDependency); m_Manager.EndExclusiveEntityTransaction(); var data = m_Group.ToComponentDataArray <EcsTestData>(Allocator.TempJob); Assert.AreEqual(2, m_Group.CalculateLength()); Assert.AreEqual(42, data[0].value); Assert.AreEqual(42, data[1].value); Assert.IsTrue(m_Manager.Exists(job.createdEntities[0])); Assert.IsTrue(m_Manager.Exists(job.createdEntities[1])); job.createdEntities.Dispose(); data.Dispose(); }
protected override void OnUpdate() { var uniqueTypes = new List <SpawnRandomInSphere>(10); EntityManager.GetAllUniqueSharedComponentData(uniqueTypes); int spawnInstanceCount = 0; for (int sharedIndex = 0; sharedIndex != uniqueTypes.Count; sharedIndex++) { var spawner = uniqueTypes[sharedIndex]; m_MainGroup.SetFilter(spawner); var entityCount = m_MainGroup.CalculateLength(); spawnInstanceCount += entityCount; } if (spawnInstanceCount == 0) { return; } var spawnInstances = new NativeArray <SpawnRandomInSphereInstance>(spawnInstanceCount, Allocator.Temp); { int spawnIndex = 0; for (int sharedIndex = 0; sharedIndex != uniqueTypes.Count; sharedIndex++) { var spawner = uniqueTypes[sharedIndex]; m_MainGroup.SetFilter(spawner); if (m_MainGroup.CalculateLength() == 0) { continue; } var entities = m_MainGroup.ToEntityArray(Allocator.TempJob); var localToWorld = m_MainGroup.ToComponentDataArray <LocalToWorld>(Allocator.TempJob); for (int entityIndex = 0; entityIndex < entities.Length; entityIndex++) { var spawnInstance = new SpawnRandomInSphereInstance(); spawnInstance.sourceEntity = entities[entityIndex]; spawnInstance.spawnerIndex = sharedIndex; spawnInstance.position = localToWorld[entityIndex].Position; spawnInstances[spawnIndex] = spawnInstance; spawnIndex++; } entities.Dispose(); localToWorld.Dispose(); } } for (int spawnIndex = 0; spawnIndex < spawnInstances.Length; spawnIndex++) { int spawnerIndex = spawnInstances[spawnIndex].spawnerIndex; var spawner = uniqueTypes[spawnerIndex]; int count = spawner.count; var entities = new NativeArray <Entity>(count, Allocator.Temp); var prefab = spawner.prefab; float radius = spawner.radius; var spawnPositions = new NativeArray <float3>(count, Allocator.TempJob); float3 center = spawnInstances[spawnIndex].position; var sourceEntity = spawnInstances[spawnIndex].sourceEntity; GeneratePoints.RandomPointsInUnitSphere(spawnPositions); EntityManager.Instantiate(prefab, entities); for (int i = 0; i < count; i++) { EntityManager.SetComponentData(entities[i], new LocalToWorld { Value = float4x4.TRS( center + (spawnPositions[i] * radius), quaternion.LookRotationSafe(spawnPositions[i], math.up()), new float3(1.0f, 1.0f, 1.0f)) }); } EntityManager.RemoveComponent <SpawnRandomInSphere>(sourceEntity); spawnPositions.Dispose(); entities.Dispose(); } spawnInstances.Dispose(); }
protected override void OnUpdate() { var uniqueTypes = new List <SpawnRandomInSphere>(10); EntityManager.GetAllUniqueSharedComponentData(uniqueTypes); int spawnInstanceCount = 0; for (int sharedIndex = 0; sharedIndex != uniqueTypes.Count; sharedIndex++) { var spawner = uniqueTypes[sharedIndex]; m_MainGroup.SetFilter(spawner); var entityCount = m_MainGroup.CalculateLength(); spawnInstanceCount += entityCount; } if (spawnInstanceCount == 0) { return; } var spawnInstances = new NativeArray <SpawnRandomInSphereInstance>(spawnInstanceCount, Allocator.Temp); { int spawnIndex = 0; for (int sharedIndex = 0; sharedIndex != uniqueTypes.Count; sharedIndex++) { var spawner = uniqueTypes[sharedIndex]; m_MainGroup.SetFilter(spawner); if (m_MainGroup.CalculateLength() == 0) { continue; } var entities = m_MainGroup.ToEntityArray(Allocator.TempJob); var positions = m_MainGroup.ToComponentDataArray <Position>(Allocator.TempJob); for (int entityIndex = 0; entityIndex < entities.Length; entityIndex++) { var spawnInstance = new SpawnRandomInSphereInstance(); spawnInstance.sourceEntity = entities[entityIndex]; spawnInstance.spawnerIndex = sharedIndex; spawnInstance.position = positions[entityIndex].Value; spawnInstances[spawnIndex] = spawnInstance; spawnIndex++; } entities.Dispose(); positions.Dispose(); } } for (int spawnIndex = 0; spawnIndex < spawnInstances.Length; spawnIndex++) { int spawnerIndex = spawnInstances[spawnIndex].spawnerIndex; var spawner = uniqueTypes[spawnerIndex]; int count = spawner.count; var entities = new NativeArray <Entity>(count, Allocator.Temp); var prefab = spawner.prefab; float radius = spawner.radius; var spawnPositions = new NativeArray <float3>(count, Allocator.Temp); float3 center = spawnInstances[spawnIndex].position; var sourceEntity = spawnInstances[spawnIndex].sourceEntity; GeneratePoints.RandomPointsInSphere(center, radius, ref spawnPositions); EntityManager.Instantiate(prefab, entities); for (int i = 0; i < count; i++) { var position = new Position { Value = spawnPositions[i] }; EntityManager.SetComponentData(entities[i], position); } EntityManager.RemoveComponent <SpawnRandomInSphere>(sourceEntity); spawnPositions.Dispose(); entities.Dispose(); } spawnInstances.Dispose(); }
// This is (most times) a trigger: see https://forum.unity.com/threads/onupdate-method-in-componentsystems.541647/ for when it's called protected override void OnUpdate() { var uniqueTypes = new List <SpawnRandomInSphere>(10); // We have (by default) 2 BoidFishSpawners in the scene (if not modified). These have 3 attributes. If both spawners have EXACTLY the same values (whether its reference or value type) // they will be "fused" in uniqueTypes.Count, so uniqueTypes.Count will be 2, otherwise it'll be 3. The reason is that the first seems to be a default one (see link below) EntityManager.GetAllUniqueSharedComponentData(uniqueTypes); int spawnInstanceCount = 0; // https://forum.unity.com/threads/question-about-getalluniquesharedcomponentdata.545945/ // Since the 0 is the default, why not start at 1, does not make any difference since when filtering by the 0 uniqueType, it's being ignored for (int sharedIndex = 0 /* 1 */; sharedIndex != uniqueTypes.Count; sharedIndex++) { var spawner = uniqueTypes[sharedIndex]; // this is filtering the "groups of instances" that have the same values m_MainGroup.SetFilter(spawner); // we're counting them var entityCount = m_MainGroup.CalculateLength(); // so this is the overall number of instances wether or not they have the same values spawnInstanceCount += entityCount; } if (spawnInstanceCount == 0) { return; } var spawnInstances = new NativeArray <SpawnRandomInSphereInstance>(spawnInstanceCount, Allocator.Temp); { int spawnIndex = 0; for (int sharedIndex = 0; sharedIndex != uniqueTypes.Count; sharedIndex++) { var spawner = uniqueTypes[sharedIndex]; m_MainGroup.SetFilter(spawner); // this would never be 0 if the previous loop started at 1 I guess if (m_MainGroup.CalculateLength() == 0) { continue; } // 1+1 entities (if any value differs, and it is the default scene, 2 spawners overall) var entities = m_MainGroup.ToEntityArray(Allocator.TempJob); var localToWorld = m_MainGroup.ToComponentDataArray <LocalToWorld>(Allocator.TempJob); // convenient way of storing the 2 (if default) spawners info for (int entityIndex = 0; entityIndex < entities.Length; entityIndex++) { var spawnInstance = new SpawnRandomInSphereInstance(); spawnInstance.sourceEntity = entities[entityIndex]; spawnInstance.spawnerIndex = sharedIndex; spawnInstance.position = localToWorld[entityIndex].Position; spawnInstances[spawnIndex] = spawnInstance; spawnIndex++; } entities.Dispose(); localToWorld.Dispose(); } // for more info about ISharedComponentData see: https://docs.unity3d.com/Packages/[email protected]/manual/shared_component_data.html } // now for every spawner for (int spawnIndex = 0; spawnIndex < spawnInstances.Length; spawnIndex++) { int spawnerIndex = spawnInstances[spawnIndex].spawnerIndex; var spawner = uniqueTypes[spawnerIndex]; int count = spawner.count; var prefab = spawner.prefab; float radius = spawner.radius; float3 center = spawnInstances[spawnIndex].position; var sourceEntity = spawnInstances[spawnIndex].sourceEntity; var spawnPositions = new NativeArray <float3>(count, Allocator.TempJob); var entities = new NativeArray <Entity>(count, Allocator.Temp); // prepare the positions to spawn the fishes and instantiate them GeneratePoints.RandomPointsInUnitSphere(spawnPositions); EntityManager.Instantiate(prefab, entities); for (int i = 0; i < count; i++) { // set the fishes entities data EntityManager.SetComponentData(entities[i], new LocalToWorld { // the center is the spawner GameObject center // radius is the sphere radius Value = float4x4.TRS( center + (spawnPositions[i] * radius), quaternion.LookRotationSafe(spawnPositions[i], math.up()), new float3(1.0f, 1.0f, 1.0f)) }); } // the system does not need it anymore, get rid of it EntityManager.RemoveComponent <SpawnRandomInSphere>(sourceEntity); spawnPositions.Dispose(); entities.Dispose(); } spawnInstances.Dispose(); }
protected override void OnUpdate() { var entities = m_ComponentGroup.ToEntityArray(Allocator.TempJob); List <SpriteSkin> spriteSkinComponents = new List <SpriteSkin>(); List <SpriteComponent> spriteComponents = new List <SpriteComponent>(); Entities.ForEach((SpriteSkin spriteSkin) => { spriteSkinComponents.Add(spriteSkin); }); Entities.ForEach((SpriteComponent sprite) => { spriteComponents.Add(sprite); }); var worldToLocalComponents = m_ComponentGroup.ToComponentDataArray <WorldToLocal>(Allocator.TempJob); for (var i = 0; i < entities.Length; ++i) { var vertexBuffer = EntityManager.GetBuffer <Vertex>(entities[i]); var boneTransformBuffer = EntityManager.GetBuffer <BoneTransform>(entities[i]); var currentSprite = spriteComponents[i].Value; var currentWorldToLocal = worldToLocalComponents[i]; Sprite sprite = null; var entity = entities[i]; var spriteSkin = spriteSkinComponents[i]; if (spriteSkin == null) { continue; } var spriteRenderer = spriteSkin.spriteRenderer; var isValid = spriteRenderer.enabled && spriteSkin.isValid; var isVisible = spriteRenderer.isVisible || spriteSkin.ForceSkinning; if (!isValid) { SpriteRendererDataAccessExtensions.DeactivateDeformableBuffer(spriteRenderer); } else if (isVisible) { spriteSkin.ForceSkinning = false; sprite = spriteRenderer.sprite; float4x4 worldToLocal = spriteSkin.transform.worldToLocalMatrix; if (vertexBuffer.Length != sprite.GetVertexCount()) { vertexBuffer = PostUpdateCommands.SetBuffer <Vertex>(entity); vertexBuffer.ResizeUninitialized(sprite.GetVertexCount()); } InternalEngineBridge.SetDeformableBuffer(spriteRenderer, vertexBuffer.Reinterpret <Vector3>().AsNativeArray()); if (boneTransformBuffer.Length != spriteSkin.boneTransforms.Length) { boneTransformBuffer = PostUpdateCommands.SetBuffer <BoneTransform>(entity); boneTransformBuffer.ResizeUninitialized(spriteSkin.boneTransforms.Length); } for (var j = 0; j < boneTransformBuffer.Length; ++j) { boneTransformBuffer[j] = new BoneTransform() { Value = spriteSkin.boneTransforms[j].localToWorldMatrix } } ; PostUpdateCommands.SetComponent <WorldToLocal>(entity, new WorldToLocal() { Value = worldToLocal }); } if (currentSprite != sprite) { PostUpdateCommands.SetSharedComponent <SpriteComponent>(entity, new SpriteComponent() { Value = sprite }); } if (!spriteRenderer.enabled) { spriteSkin.ForceSkinning = true; } } entities.Dispose(); worldToLocalComponents.Dispose(); } }
protected override JobHandle OnUpdate(JobHandle inputDeps) { EntityManager.GetAllUniqueSharedComponentData(m_UniqueTypes); var obstacleCount = m_ObstacleGroup.CalculateLength(); var targetCount = m_TargetGroup.CalculateLength(); // Ingore typeIndex 0, can't use the default for anything meaningful. for (int typeIndex = 1; typeIndex < m_UniqueTypes.Count; typeIndex++) { var settings = m_UniqueTypes[typeIndex]; m_BoidGroup.SetFilter(settings); var boidCount = m_BoidGroup.CalculateLength(); var cacheIndex = typeIndex - 1; var cellIndices = new NativeArray <int>(boidCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var hashMap = new NativeMultiHashMap <int, int>(boidCount, Allocator.TempJob); var cellObstacleDistance = new NativeArray <float>(boidCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var cellObstaclePositionIndex = new NativeArray <int>(boidCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var cellTargetPositionIndex = new NativeArray <int>(boidCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var cellCount = new NativeArray <int>(boidCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); var cellAlignment = m_BoidGroup.ToComponentDataArray <Heading>(Allocator.TempJob, out var initialCellAlignmentJobHandle); var cellSeparation = m_BoidGroup.ToComponentDataArray <Position>(Allocator.TempJob, out var initialCellSeparationJobHandle); var copyTargetPositions = m_TargetGroup.ToComponentDataArray <Position>(Allocator.TempJob, out var copyTargetPositionsJobHandle); var copyObstaclePositions = m_ObstacleGroup.ToComponentDataArray <Position>(Allocator.TempJob, out var copyObstaclePositionsJobHandle); var nextCells = new PrevCells { cellIndices = cellIndices, hashMap = hashMap, copyObstaclePositions = copyObstaclePositions, copyTargetPositions = copyTargetPositions, cellAlignment = cellAlignment, cellSeparation = cellSeparation, cellObstacleDistance = cellObstacleDistance, cellObstaclePositionIndex = cellObstaclePositionIndex, cellTargetPistionIndex = cellTargetPositionIndex, cellCount = cellCount }; if (cacheIndex > (m_PrevCells.Count - 1)) { m_PrevCells.Add(nextCells); } else { m_PrevCells[cacheIndex].hashMap.Dispose(); m_PrevCells[cacheIndex].cellIndices.Dispose(); m_PrevCells[cacheIndex].cellObstaclePositionIndex.Dispose(); m_PrevCells[cacheIndex].cellTargetPistionIndex.Dispose(); m_PrevCells[cacheIndex].copyTargetPositions.Dispose(); m_PrevCells[cacheIndex].copyObstaclePositions.Dispose(); m_PrevCells[cacheIndex].cellAlignment.Dispose(); m_PrevCells[cacheIndex].cellSeparation.Dispose(); m_PrevCells[cacheIndex].cellObstacleDistance.Dispose(); m_PrevCells[cacheIndex].cellCount.Dispose(); } m_PrevCells[cacheIndex] = nextCells; var hashPositionsJob = new HashPositions { hashMap = hashMap.ToConcurrent(), cellRadius = settings.cellRadius }; var hashPositionsJobHandle = hashPositionsJob.ScheduleGroup(m_BoidGroup, inputDeps); var initialCellCountJob = new MemsetNativeArray <int> { Source = cellCount, Value = 1 }; var initialCellCountJobHandle = initialCellCountJob.Schedule(boidCount, 64, inputDeps); var initialCellBarrierJobHandle = JobHandle.CombineDependencies(initialCellAlignmentJobHandle, initialCellSeparationJobHandle, initialCellCountJobHandle); var copyTargetObstacleBarrierJobHandle = JobHandle.CombineDependencies(copyTargetPositionsJobHandle, copyObstaclePositionsJobHandle); var mergeCellsBarrierJobHandle = JobHandle.CombineDependencies(hashPositionsJobHandle, initialCellBarrierJobHandle, copyTargetObstacleBarrierJobHandle); var mergeCellsJob = new MergeCells { cellIndices = cellIndices, cellAlignment = cellAlignment, cellSeparation = cellSeparation, cellObstacleDistance = cellObstacleDistance, cellObstaclePositionIndex = cellObstaclePositionIndex, cellTargetPistionIndex = cellTargetPositionIndex, cellCount = cellCount, targetPositions = copyTargetPositions, obstaclePositions = copyObstaclePositions }; var mergeCellsJobHandle = mergeCellsJob.Schedule(hashMap, 64, mergeCellsBarrierJobHandle); var steerJob = new Steer { cellIndices = nextCells.cellIndices, settings = settings, cellAlignment = cellAlignment, cellSeparation = cellSeparation, cellObstacleDistance = cellObstacleDistance, cellObstaclePositionIndex = cellObstaclePositionIndex, cellTargetPistionIndex = cellTargetPositionIndex, cellCount = cellCount, targetPositions = copyTargetPositions, obstaclePositions = copyObstaclePositions, dt = Time.deltaTime, }; var steerJobHandle = steerJob.ScheduleGroup(m_BoidGroup, mergeCellsJobHandle); inputDeps = steerJobHandle; m_BoidGroup.AddDependency(inputDeps); } m_UniqueTypes.Clear(); return(inputDeps); }
protected override void OnUpdate() { if (connectionGroup.IsEmptyIgnoreFilter) { return; } var connections = connectionGroup.ToComponentDataArray <NetworkSnapshotAck>(Allocator.TempJob); var ack = connections[0]; connections.Dispose(); // What we expect to have this frame based on what was the most recent received previous frames if (resetHistory) { if (ack.LastReceivedSnapshotByLocal == 0) { return; } for (int i = 0; i < receiveHistory.Length; ++i) { receiveHistory[i] = ack.LastReceivedSnapshotByLocal; } for (int i = 0; i < rttHistory.Length; ++i) { rttHistory[i] = ack.LastReceivedRTT; } } else { for (int i = 0; i < receiveHistory.Length; ++i) { receiveHistory[i] = receiveHistory[i] + 1; } if (receiveHistory[receiveHistoryPos] != ack.LastReceivedSnapshotByLocal) { receiveHistoryPos = (receiveHistoryPos + 1) % receiveHistory.Length; receiveHistory[receiveHistoryPos] = ack.LastReceivedSnapshotByLocal; rttHistoryPos = (rttHistoryPos + 1) % rttHistory.Length; rttHistory[rttHistoryPos] = ack.LastReceivedRTT; } } uint averageRTT = AverageWithoutExtremes(rttHistory, KRTTHistoryMedianDiscard); uint expected = AverageWithoutExtremes(receiveHistory, KSnapshotHistoryMedianDiscard); // Interpolation time is network tick rate times 2, round up to even number of sim ticks uint interpolationTimeMS = KInterpolationTimeMS; if (interpolationTimeMS == 0) { interpolationTimeMS = (1000 * KInterpolationTimeNetTicks + KNetTickRate - 1) / KNetTickRate; } uint interpolationFrames = (interpolationTimeMS * KSimTickRate + 999) / 1000; var curInterpolateTargetTick = expected - interpolationFrames; predictTargetTick = expected + 1 + (averageRTT * KSimTickRate + 999) / 1000; ++interpolateTargetTick; interpolateDelta += (int)(curInterpolateTargetTick - interpolateTargetTick); int absDelta = math.abs(interpolateDelta); if (absDelta > 10) { // Drifted too far away, do a force sync interpolateTargetTick = curInterpolateTargetTick; interpolateDelta = 0; } else if (absDelta > 3) { // Starting to drift a bit, adjust to keep up interpolateTargetTick += (uint)(interpolateDelta / absDelta); interpolateDelta = 0; } }
protected override JobHandle OnUpdate(JobHandle inputDep) { var commandBuffer = m_Barrier.CreateCommandBuffer(); // Destroy drivers if the PingDriverComponents were removed if (!m_DestroyedDriverGroup.IsEmptyIgnoreFilter) { inputDep.Complete(); var destroyedDriverEntity = m_DestroyedDriverGroup.ToEntityArray(Allocator.TempJob); var destroyedDriverList = m_DestroyedDriverGroup.ToComponentDataArray <PingDriverComponentData>(Allocator.TempJob); for (int i = 0; i < destroyedDriverList.Length; ++i) { if (destroyedDriverList[i].isServer != 0) { var serverConnectionList = m_ServerConnectionGroup.ToEntityArray(Allocator.TempJob); // Also destroy all active connections when the driver dies for (int con = 0; con < serverConnectionList.Length; ++con) { commandBuffer.DestroyEntity(serverConnectionList[con]); } serverConnectionList.Dispose(); ServerDriver.Dispose(); } else { ClientDriver.Dispose(); } commandBuffer.RemoveComponent <PingDriverStateComponent>(destroyedDriverEntity[i]); } destroyedDriverList.Dispose(); destroyedDriverEntity.Dispose(); } // Create drivers if new PingDriverComponents were added if (!m_NewDriverGroup.IsEmptyIgnoreFilter) { inputDep.Complete(); var newDriverEntity = m_NewDriverGroup.ToEntityArray(Allocator.TempJob); var newDriverList = m_NewDriverGroup.ToComponentDataArray <PingDriverComponentData>(Allocator.TempJob); for (int i = 0; i < newDriverList.Length; ++i) { if (newDriverList[i].isServer != 0) { if (ServerDriver.IsCreated) { throw new InvalidOperationException("Cannot create multiple server drivers"); } var drv = new UdpNetworkDriver(new INetworkParameter[0]); var addr = NetworkEndPoint.AnyIpv4; addr.Port = 9000; if (drv.Bind(addr) != 0) { throw new Exception("Failed to bind to port 9000"); } else { drv.Listen(); } ServerDriver = drv; ConcurrentServerDriver = ServerDriver.ToConcurrent(); } else { if (ClientDriver.IsCreated) { throw new InvalidOperationException("Cannot create multiple client drivers"); } ClientDriver = new UdpNetworkDriver(new INetworkParameter[0]); ConcurrentClientDriver = ClientDriver.ToConcurrent(); } commandBuffer.AddComponent(newDriverEntity[i], new PingDriverStateComponent { isServer = newDriverList[i].isServer }); } newDriverList.Dispose(); newDriverEntity.Dispose(); } JobHandle clientDep = default(JobHandle); JobHandle serverDep = default(JobHandle); // Go through and update all drivers, also accept all incoming connections for server drivers if (ServerDriver.IsCreated) { // Schedule a chain with driver update, a job to accept all connections and finally a job to delete all invalid connections serverDep = ServerDriver.ScheduleUpdate(inputDep); var acceptJob = new DriverAcceptJob { driver = ServerDriver, commandBuffer = commandBuffer }; serverDep = acceptJob.Schedule(serverDep); var cleanupJob = new DriverCleanupJob { commandBuffer = m_Barrier.CreateCommandBuffer().ToConcurrent() }; serverDep = cleanupJob.Schedule(this, serverDep); m_Barrier.AddJobHandleForProducer(serverDep); } if (ClientDriver.IsCreated) { clientDep = ClientDriver.ScheduleUpdate(inputDep); } return(JobHandle.CombineDependencies(clientDep, serverDep)); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { m_Jobs.Clear(); m_UniqueSpriteComponents.Clear(); EntityManager.GetAllUniqueSharedComponentData(m_UniqueSpriteComponents); var spriteComponentCount = m_UniqueSpriteComponents.Count; var entitiesPerSprite = new NativeArray <int>(spriteComponentCount, Allocator.Temp); m_Jobs.Capacity = spriteComponentCount; for (var i = 0; i < spriteComponentCount; i++) { var spriteComponent = m_UniqueSpriteComponents[i]; var sprite = spriteComponent.Value; var job = default(SkinJob); var entityCount = 0; if (sprite != null) { m_ComponentGroup.SetFilter(spriteComponent); var filteredEntities = m_ComponentGroup.ToEntityArray(Allocator.TempJob); entityCount = filteredEntities.Length; entitiesPerSprite[i] = entityCount; if (entityCount > 0) { job = new SkinJob { entities = filteredEntities, vertices = sprite.GetVertexAttribute <Vector3>(UnityEngine.Rendering.VertexAttribute.Position).SliceWithStride <float3>(), boneWeights = sprite.GetVertexAttribute <BoneWeight>(UnityEngine.Rendering.VertexAttribute.BlendWeight), bindPoses = new NativeSlice <Matrix4x4>(sprite.GetBindPoses()).SliceWithStride <float4x4>(), localToWorldArray = m_ComponentGroup.ToComponentDataArray <WorldToLocal>(Allocator.TempJob), boneTransformArray = GetBufferFromEntity <BoneTransform>(), deformedArray = GetBufferFromEntity <Vertex>() }; m_Jobs.Add(job); } else { filteredEntities.Dispose(); } } } if (m_Jobs.Count > 0) { var jobHandles = new NativeArray <JobHandle>(m_Jobs.Count, Allocator.Temp); var prevHandle = inputDeps; var jobIndex = 0; for (var i = 0; i < entitiesPerSprite.Length; ++i) { if (entitiesPerSprite[i] > 0) { jobHandles[jobIndex] = m_Jobs[jobIndex].Schedule(entitiesPerSprite[i], 4, prevHandle); prevHandle = jobHandles[jobIndex]; ++jobIndex; } } var combinedHandle = JobHandle.CombineDependencies(jobHandles); jobHandles.Dispose(); entitiesPerSprite.Dispose(); return(combinedHandle); } return(inputDeps); }
protected override JobHandle OnUpdate(JobHandle inputDeps) { if (!_voxelWorldSystem.IsInitialized) { return(inputDeps); } if (_isInitialized) { return(inputDeps); } var xzSize = _voxelWorldSystem.VoxelWorld.ChunkSize * _voxelWorldSystem.VoxelWorld.MaxChunks; VoxelsMap = new NativeArray3D <Entity>(xzSize.x, _voxelWorldSystem.VoxelWorld.ChunkSize.y, xzSize.z, Allocator.Persistent); _isInitialized = true; var worldPosition = GetComponentDataFromEntity <Translation>(true)[_voxelWorldSystem.VoxelWorld.Entity].Value; var World = _voxelWorldSystem.VoxelWorld; var et = _chunkGroup.ToEntityArray(Allocator.Persistent); var tmp = _chunkGroup.ToComponentDataArray <VoxelChunk>(Allocator.Persistent); var pos = _chunkGroup.ToComponentDataArray <Translation>(Allocator.Persistent); for (int i = 0; i < tmp.Length; i++) { var chunkEntity = et[i]; var voxelChunk = tmp[i]; var translation = pos[i]; if (voxelChunk.NeedsUpdate == 1) { int3 offset = World.MaxChunks * World.ChunkSize / 2; float x = worldPosition.x + voxelChunk.X * World.ChunkSize.x - offset.x; float z = worldPosition.z + voxelChunk.Z * World.ChunkSize.z - offset.z; float y = worldPosition.y; translation.Value = new Vector3(x, y, z); EntityManager.SetComponentData(chunkEntity, translation); voxelChunk.NeedsUpdate = 0; voxelChunk.IsInitialized = 1; EntityManager.SetComponentData(chunkEntity, voxelChunk); } if (voxelChunk.IsInitialized == 1 && voxelChunk.IsPopulated == 0) { var terrainHeight = GenerateTerrainHeight(voxelChunk, translation, _voxelWorldSystem.VoxelWorld.ChunkSize); for (int x = 0; x < World.ChunkSize.x; x++) { for (int y = 0; y < World.ChunkSize.y; y++) { for (int z = 0; z < World.ChunkSize.z; z++) { Vector3 position = new float3(translation.Value.x + x, translation.Value.y + y, translation.Value.z + z); Entity voxelEntity; switch (terrainHeight[x, y, z]) { case 1: voxelEntity = EntityManager.Instantiate(voxelChunk.VoxelPrefab1); break; case 2: voxelEntity = EntityManager.Instantiate(voxelChunk.VoxelPrefab2); break; default: continue; } EntityManager.SetComponentData(voxelEntity, new Voxel { Entity = voxelEntity, VoxelChunkEntity = chunkEntity, X = x, Y = y, Z = z, Initialized = 1 }); EntityManager.SetComponentData(voxelEntity, new Translation { Value = position }); VoxelsMap[x, y, z] = voxelEntity; } } } voxelChunk.IsPopulated = 1; } } et.Dispose(); tmp.Dispose(); pos.Dispose(); return(inputDeps); }