public void OutputStat() { _waitHandle.Complete(); StringBuilder bld = new StringBuilder(); var cnt = _queue.Count; for (int i = 0; i < cnt; ++i) { var x = _queue.Dequeue(); bld.AppendLine($"{x.chunkIndex} {x.chunkLen} {x.firstEntIdx}"); } Debug.Log(bld.ToString()); }
public void Execute() { int count = TriQueue.Count; int index = 0; for (int i = 0; i < count; i++) { int3 tri = TriQueue.Dequeue(); Triangles[index++] = tri.x; Triangles[index++] = tri.y; Triangles[index++] = tri.z; } }
public void NativeQueueAddPeekRemove() { for (int i = 0; i < COUNT; i++) { nq.Enqueue(i); } var peek = nq.Peek(); for (int i = 0; i < COUNT; i++) { var res = nq.Dequeue(); } }
/// <summary> /// Will build a tree with N subnodes per node = actionsPerState * resultsPerAction; /// A depth of 1 will result in a single root node /// </summary> internal static PlanGraph <int, StateInfo, int, ActionInfo, StateTransitionInfo> BuildTree(int actionsPerState = 2, int resultsPerAction = 2, int depth = 10) { Debug.Assert(depth > 0); // tree float probabilityPerResult = 1f / resultsPerAction; int nextStateIndex = 0; var subNodesPerNode = actionsPerState * resultsPerAction; int totalStates = GetTotalNodeCountForTreeDepth(subNodesPerNode, depth); var planGraph = new PlanGraph <int, StateInfo, int, ActionInfo, StateTransitionInfo>(totalStates, totalStates, totalStates); var builder = new PlanGraphBuilder <int, int> { planGraph = planGraph }; var queue = new NativeQueue <int>(Allocator.TempJob); // Add root int rootStateIndex = nextStateIndex; nextStateIndex++; builder.AddState(rootStateIndex); queue.Enqueue(rootStateIndex); for (int horizon = 0; horizon < depth - 1; horizon++) { var statesInHorizon = Math.Pow(actionsPerState * resultsPerAction, horizon); for (int i = 0; i < statesInHorizon; i++) { var state = queue.Dequeue(); var stateContext = builder.WithState(state); for (int actionIndex = 0; actionIndex < actionsPerState; actionIndex++) { var actionContext = stateContext.AddAction(actionIndex); for (int j = 0; j < resultsPerAction; j++) { var newStateIndex = nextStateIndex; nextStateIndex++; actionContext.AddResultingState(newStateIndex, probability: probabilityPerResult); queue.Enqueue(newStateIndex); } } } } queue.Dispose(); return(planGraph); }
protected override void OnUpdate() { if (_systemStateGroup.IsEmptyIgnoreFilter || _emptyCellsGroup.IsEmptyIgnoreFilter) { return; } var systemState = _systemStateGroup.GetSingletonEntity(); EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.TempJob); var gravity = GetComponentDataFromEntity <Gravity>(true)[systemState]; ComponentDataFromEntity <GridPosition> gridPositions = GetComponentDataFromEntity <GridPosition>(true); ComponentDataFromEntity <BallLink> ballLinks = GetComponentDataFromEntity <BallLink>(true); var startY = gravity.Value.y > 0 ? _field.Height - 1 : 0; NativeQueue <Entity> cellsToFallIn = new NativeQueue <Entity>(Allocator.TempJob); for (int x = 0; x < _field.Width; x++) { cellsToFallIn.Clear(); for (var y = startY; y < _field.Height && y >= 0; y -= gravity.Value.y) { var cell = _field.GetCell(x, y); if (!ballLinks.Exists(cell)) { cellsToFallIn.Enqueue(cell); } else if (cellsToFallIn.Count > 0) { ecb.RemoveComponent <BallLink>(cell); var ball = ballLinks[cell].Value; var cellToFall = cellsToFallIn.Dequeue(); ecb.SetComponent(ball, new CellLink { Value = cellToFall }); ecb.AddComponent(ball, new Destination { Value = _field.GetWorldPosition(gridPositions[cellToFall].Value) }); ecb.AddComponent(cellToFall, new BallLink { Value = ball }); ecb.RemoveComponent <Interactable>(systemState); } } } cellsToFallIn.Dispose(); ecb.Playback(EntityManager); ecb.Dispose(); }
protected override void OnUpdate() { Dependency.Complete(); if (commands.Count > 0) { var accessor = des.GetAccessor(); do { var cmd = commands.Dequeue(); cmd.PlayBack(EntityManager, accessor); }while (commands.Count > 0); } Dependency = default; }
// -- // public void Execute() { if (patternMatchRequest.Count == 0) { return; } blockMatched = 0; var patternMatchCount = patternMatchRequest.Count; var requests = new NativeArray <int2>(patternMatchCount, Allocator.Temp); for (int i = 0; i < patternMatchCount; ++i) { requests[i] = patternMatchRequest.Dequeue(); } for (int i = 0; i < requests.Length; ++i) { var request = requests[i]; var match = false; for (int j = 0; j < patternsInfo.Length; ++j) { var patternInfo = patternsInfo[j]; var pattern = patternsBufferLookup[patternInfo.entity]; var matchedBlocks = new NativeArray <int>(pattern.Length, Allocator.Temp); match = Match(pattern, ref patternInfo, request, matchedBlocks); if (match) { AddMatchedBlockToDelete(matchedBlocks); } matchedBlocks.Dispose(); if (match) { break; } } if (!match) { unswap.TryAdd(request.GetHashCode(), true); } } requests.Dispose(); }
public void Execute() { while (interpolatedDespawnQueue.Count > 0 && !SequenceHelpers.IsNewer(interpolatedDespawnQueue.Peek().tick, interpolatedTick)) { commandBuffer.RemoveComponent(interpolatedDespawnQueue.Dequeue().ghost, ghostType); } while (predictedDespawnQueue.Count > 0 && !SequenceHelpers.IsNewer(predictedDespawnQueue.Peek().tick, predictedTick)) { commandBuffer.RemoveComponent(predictedDespawnQueue.Dequeue().ghost, ghostType); } }
public void Execute() { LitVoxels.Clear(); //Enqueue lit voxels for processing //TODO: parallel job filter or store litvoxels already in calculate light ray job for (var x = GeometryConsts.LIGHTS_CLUSTER_MIN; x < GeometryConsts.LIGHTS_CLUSTER_MAX; x++) { for (var z = GeometryConsts.LIGHTS_CLUSTER_MIN; z < GeometryConsts.LIGHTS_CLUSTER_MAX; z++) { for (var y = GeometryConsts.CHUNK_HEIGHT - 1; y >= 0; y--) { var index = ArrayHelper.ToCluster1D(x, y, z); if (LightLevels[index] > GeometryConsts.LIGHT_FALL_OFF) { LitVoxels.Enqueue(new int3(x, y, z)); } } } } //Iterate trough lit voxels and project light to neighbours while (LitVoxels.Count > 0) { var litVoxel = LitVoxels.Dequeue(); var litVoxelId = ArrayHelper.ToCluster1D(litVoxel.x, litVoxel.y, litVoxel.z); var neighbourLightValue = LightLevels[litVoxelId] - GeometryConsts.LIGHT_FALL_OFF; //iterate trough neighbours for (int iF = 0; iF < GeometryConsts.FACES_PER_VOXEL; iF++) { var neighbour = litVoxel + Neighbours[iF]; if (CheckVoxelBounds(neighbour.x, neighbour.y, neighbour.z)) { var neighbourId = ArrayHelper.ToCluster1D(neighbour.x, neighbour.y, neighbour.z); var neighbourType = MapData[neighbourId]; if (!BlockDataLookup[neighbourType].IsSolid && LightLevels[neighbourId] < neighbourLightValue) { LightLevels[neighbourId] = neighbourLightValue; if (neighbourLightValue > GeometryConsts.LIGHT_FALL_OFF) { LitVoxels.Enqueue(neighbour); } } } } } }
public void Execute() { while (attackCommands.Count > 0) { var command = attackCommands.Dequeue(); if (minions.Exists(command.DefenderEntity)) { var minion = minions[command.DefenderEntity]; minion.Health -= command.Damage; minions[command.DefenderEntity] = minion; } } }
public void Execute() { while (entityQueue.Count > 0) { Entity entityToDestroy = entityQueue.Dequeue(); if (entityTransaction.Exists(entityToDestroy)) { //Get the EntityTypeData component to figure out what type of entity we are deleting EntityTypeData entityToDestroyTypeData = entityTransaction.GetSharedComponentData <EntityTypeData>(entityToDestroy); switch (entityToDestroyTypeData.entityType) { case EntityTypeData.EntityType.Asteroid: case EntityTypeData.EntityType.EnemyShip: case EntityTypeData.EntityType.AllyShip: case EntityTypeData.EntityType.PlayerShip: { //Those type of entity will require some additional logic after destruction, //create the info needed and add it to the list EntityInstanceRenderData entityToDestroyRenderData = entityTransaction.GetComponentData <EntityInstanceRenderData>(entityToDestroy); InfoForLogicAfterDestroy newInfo = new InfoForLogicAfterDestroy { entityTypeData = entityToDestroyTypeData, renderData = entityToDestroyRenderData, }; infoForLogic.Add(newInfo); } break; case EntityTypeData.EntityType.Bolt: { //Player bolts are only destroyed when they collided with enemies or obstacle, // add to the score in that case BoltTypeData boltTypeData = entityTransaction.GetSharedComponentData <BoltTypeData>(entityToDestroy); if (boltTypeData.boltType == BoltTypeData.BoltType.PlayerBolt) { UIData uiData = uiDataArray[0]; uiData.score += scoreValue; uiDataArray[0] = uiData; } } break; } //This will remove the entity from the entity manager entityTransaction.DestroyEntity(entityToDestroy); } } }
private void UpdateDroneInfo() { _droneInfo.Clear(); foreach (var dataSource in SimManager.AllDrones.Values) { var drone = (Drone)dataSource; drone.UpdateMovement(ref _droneInfo); } while (_dronesToDrop.Count > 0) { if (SimManager.AllDrones.TryGet(_dronesToDrop.Dequeue(), out var d)) { ((Drone)d).Drop(); } } }
//We need to make sure when deleting our queues that we delete the entities they contain void DisposeOfEntityQueue(NativeQueue <Entity> queueToDispose) { if (queueToDispose.IsCreated) { while (queueToDispose.Count > 0) { Entity entityToDestroy = queueToDispose.Dequeue(); if (EntityManager.IsCreated && EntityManager.Exists(entityToDestroy)) { EntityManager.DestroyEntity(entityToDestroy); } } queueToDispose.Dispose(); } }
/// <summary> /// Checks if chunk building jobs are ready /// </summary> private void ChunkLoading() { if (pendingJobs.Count > 0) { for (int i = 0; i < maxChunksToBuildAtOnce; i++) { if (pendingJobs.Peek().IsCompleted) { pendingJobs.Dequeue().Complete(); Chunk tc = terrainChunks.Dequeue(); tc.gameObject.SetActive(true); tc.CreateBiomeTexture(); tc.Animation(); tc.ApplyMesh(); LoadedChunks++; if (pendingJobs.Count == 0) { break; } // TODO: check if player is close // ChunkLoading(); } else { break; } } } while (meshBakingJobs.Count > 0) { if (meshBakingJobs.Peek().IsCompleted) { meshBakingJobs.Dequeue().Complete(); Chunk chunk = terrainCollisionMeshes.Dequeue(); chunk.BlockMeshCollider.sharedMesh = chunk.BlockMeshFilter.mesh; } } TimeToBuild.Invoke(); }
public void FloodFillCell() { NativeQueue <WorleyNoise.PointData> dataToCheck = new NativeQueue <WorleyNoise.PointData>(Allocator.Temp); WorleyNoise.PointData initialPointData = GetPointData(startCell.position); dataToCheck.Enqueue(initialPointData); float startCellGrouping = GetOrGenerateCellGrouping(startCell.index); initialPointData.cellGrouping = startCellGrouping; pointMatrix.AddItem(initialPointData, initialPointData.pointWorldPosition); while (dataToCheck.Count > 0) { DebugSystem.Count("Points flood filled"); WorleyNoise.PointData data = dataToCheck.Dequeue(); bool currentIsOutsideCell = GetOrGenerateCellGrouping(data.currentCellIndex) != startCellGrouping; for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { float3 adjacentPosition = new float3(x, 0, z) + data.pointWorldPosition; WorleyNoise.PointData adjacentData = GetPointData(adjacentPosition); float grouping = GetOrGenerateCellGrouping(adjacentData.currentCellIndex); bool adjacentIsOutsideCell = grouping != startCellGrouping; if (pointMatrix.ItemIsSet(adjacentPosition) || (currentIsOutsideCell && adjacentIsOutsideCell)) { continue; } adjacentData.cellGrouping = grouping; dataToCheck.Enqueue(adjacentData); pointMatrix.AddItem(adjacentData, adjacentData.pointWorldPosition); } } } dataToCheck.Dispose(); }
static unsafe NativeArray <int> FindFunctionsByName(string functionName, NativeArray <FunctionData> functions) { using (var tmpWhiteList = new NativeQueue <int>(Allocator.TempJob)) { new FindFunctionsByName { Functions = (FunctionData *)functions.GetUnsafeReadOnlyPtr(), Search = new FixedString128(functionName), OutFunctions = tmpWhiteList.AsParallelWriter() }.Schedule(functions.Length, 32).Complete(); var arr = new NativeArray <int>(tmpWhiteList.Count, Allocator.TempJob); for (int i = 0; i < arr.Length; i++) { arr[i] = tmpWhiteList.Dequeue(); } return(arr); } }
public void Execute(ParticleSystemJobData particles) { var positions = particles.positions; var velocities = particles.velocities; int count = collisions.Count; for (int i = 0; i < count; i++) { var collision = collisions.Dequeue(); positions[collision.Index] += (Vector3)collision.DeltaPosition; velocities[collision.Index] += (Vector3)collision.DeltaVelocity; positions[collision.Index2] += (Vector3)collision.DeltaPosition2; velocities[collision.Index2] += (Vector3)collision.DeltaVelocity2; } }
public void Execute() { while (movingColliders.Count > 0) { MovingCollider movingCollider = movingColliders.Dequeue(); // remove from old cells: grid.RemoveFromCells(movingCollider.oldSpan, movingCollider.entity); // insert in new cells, as long as the index is below the amount of colliders. // otherwise, the collider is at the "tail" and there's no need to add it back. if (movingCollider.entity < colliderCount) grid.AddToCells(movingCollider.newSpan, movingCollider.entity); } // remove all empty cells from the grid: grid.RemoveEmpty(); }
public void Execute() { var space = Completed.Count * 20; // 20 is approximate queue length while (Completed.Count > 0) { var idx = Completed.Dequeue(); if (AllQueues.TryGetFirstValue(idx, out _, out _)) { AllQueues.Remove(idx); } } while (AllQueues.Capacity - AllQueues.Length < space) { AllQueues.Capacity *= 2; } }
public void EnqueueScalability() { var queue = new NativeQueue <int> (Allocator.Persistent); for (int i = 0; i != 1000 * 100; i++) { queue.Enqueue(i); } Assert.AreEqual(1000 * 100, queue.Count); for (int i = 0; i != 1000 * 100; i++) { Assert.AreEqual(i, queue.Dequeue()); } Assert.AreEqual(0, queue.Count); queue.Dispose(); }
public void TestQueue() { using (var q = new NativeQueue <int>(5, Allocator.Temp)) { q.Enqueue(5); q.Enqueue(4); q.Enqueue(3); q.Enqueue(2); q.Enqueue(1); int count = 5; while (q.Length > 0) { Assert.True(q.Length == count); Assert.True(q.Dequeue() == count); count--; } } }
public void Execute() { int2 mapSize = field.Dimensions; int dirLength = directions.Length; state[dest] = 1; search.Enqueue(new SearchNode(dest, 1)); //create the costs all valid tile will be >=1 //this probably can't be parallel while (search.Count > 0) { SearchNode node = search.Dequeue(); for (int i = 0; i < dirLength; i++) { int2 searchPos = node.root + directions[i]; if (math.all(searchPos >= 0 & searchPos < mapSize)) { int index = state.GetIndexFromPos(searchPos); uint currentCost = state[index]; //if a cheaper parent is already written skip if (currentCost <= node.cost) { //keep in map bounds FlowTile tile = field[index]; uint tileCost = node.cost + 1; //a blocked tile don't search it if (tile.state != 0) { state[index] = uint.MaxValue; continue; } //not searched or cheaper add to search if (state[index] == 0 || state[index] > tileCost) { state[index] = tileCost; search.Enqueue(new SearchNode(searchPos, tileCost)); } } } } } }
public int NewItem() { if (_idle.Count > 0) { var index = _idle.Dequeue(); UnsafeUtility.MemClear(data + head.Size * index, head.Size); return(index); } Count += 1; if (Capacity < Count) { var newData = (byte *)UnsafeUtility.Malloc(head.Size * (Count + Capacity), 4, Allocator.Persistent); UnsafeUtility.MemCpy(newData, data, Capacity * head.Size); Capacity = Count + Capacity; UnsafeUtility.Free(data, Allocator.Persistent); data = newData; } return(Count - 1); }
protected override void OnUpdate() { Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GrenadeRpc msg, ref ReceiveRpcCommandRequestComponent reqSrc) => { PostUpdateCommands.DestroyEntity(reqEnt); m_Queue.Enqueue(msg); }); uint renderTick = m_NetworkTime.interpolateTargetTick; while (m_Queue.Count > 0) { var msg = m_Queue.Peek(); if (msg.Tick > renderTick) { break; } m_Queue.Dequeue(); if (!m_GhostUpdateSystemGroup.GhostMap.TryGetValue(msg.OwnerGId, out GhostEntity item)) { return; } int localGhostId = EntityManager .GetComponentData <GhostComponent>(GetSingleton <CommandTargetComponent>().Target).Id; // 开枪人收到确认消息 if (localGhostId == msg.OwnerGId) { return; } Transform mcc = EntityManager.GetComponentObject <Transform>(item.Entity); LinkedPlayerView linkedView = mcc.GetComponent <GameObjectLinked>().Target .GetComponent <LinkedPlayerView>(); linkedView.GenGrenade(World, msg.Pos, msg.Dir, false); } }
public void Execute(int i) { CollisionPair pair = CollisionPairsQueue.Dequeue(); var boxA = entityManager.HasComponent <Box2DColliderComponent>(pair.ColliderEntityA); var circleA = entityManager.HasComponent <CircleColliderComponent>(pair.ColliderEntityA); var boxB = entityManager.HasComponent <Box2DColliderComponent>(pair.ColliderEntityB); var circleB = entityManager.HasComponent <CircleColliderComponent>(pair.ColliderEntityB); if (boxA && boxB) { BoxBoxCollisionPairs.Enqueue(pair); } else if (circleA && circleB) { CircleCircleCollisionPairs.Enqueue(pair); } else { CircleBoxCollisionPairs.Enqueue(pair); } }
public void NativeQueue_ParallelWriter() { const int queueSize = 100 * 1024; var queue = new NativeQueue <int>(Allocator.TempJob); var writeStatus = new NativeArray <int>(queueSize, Allocator.TempJob); var jobHandle = new ConcurrentEnqueue() { queue = queue.AsParallelWriter(), result = writeStatus, StartIndex = 0, }.Schedule(queueSize / 2, 1); jobHandle = new ConcurrentEnqueue() { queue = queue.AsParallelWriter(), result = writeStatus, StartIndex = queueSize / 2, }.Schedule(queueSize / 2, 1, jobHandle); jobHandle.Complete(); Assert.AreEqual(queueSize, queue.Count, "Job enqueued the wrong number of values"); var allValues = new NativeHashSet <int>(queueSize, Allocator.Persistent); for (int i = 0; i < queueSize; ++i) { Assert.AreEqual(1, writeStatus[i], "Job failed to enqueue value"); int enqueued = queue.Dequeue(); Assert.IsTrue(enqueued >= 0 && enqueued < queueSize, "Job enqueued invalid value"); Assert.IsTrue(allValues.Add(enqueued), "Job enqueued same value multiple times"); } var disposeJob = queue.Dispose(jobHandle); disposeJob.Complete(); writeStatus.Dispose(); allValues.Dispose(); }
void Update() { if (_quadTree.IsCreated == false) { return; } NodeCount = _quadTree.Length; if (_startPos != null && _lastStartPos != _startPos.gameObject.transform.position) { _lastStartPos = _startPos.gameObject.transform.position; _player.transform.position = _lastStartPos; var date = DateTime.UtcNow; path = NativeQuadTreePathFinding.RunAStar(_quadTree, new float2(_lastStartPos.x, _lastStartPos.z), new float2(_lastEndPos.x, _lastEndPos.z), Allocator.Persistent); UnityEngine.Debug.Log((DateTime.UtcNow - date).TotalSeconds); } if (_endPos != null && _lastEndPos != _endPos.gameObject.transform.position) { _lastEndPos = _endPos.gameObject.transform.position; _player.transform.position = _lastStartPos; path = NativeQuadTreePathFinding.RunAStar(_quadTree, new float2(_lastStartPos.x, _lastStartPos.z), new float2(_lastEndPos.x, _lastEndPos.z), Allocator.Persistent); } if (path.IsCreated && path.Count > 0) { var pos = path.Peek(); var v = new float2(pos.x - _player.transform.position.x, pos.y - _player.transform.position.z); if (math.lengthsq(v) < 0.5f) { path.Dequeue(); } else { v = math.normalizesafe(v); _player.transform.position = new Vector3(_player.transform.position.x + v.x * 0.5f, 0, _player.transform.position.z + v.y * 0.5f); } } }
public static void UpdateJobs() { int dirtyCount = ms_dirtyNodes.Count; int workCount = ms_workingCells.Count; for (int i = 0; i < dirtyCount; ++i) { var nodeID = ms_dirtyNodes.Dequeue(); var node = ms_pool[nodeID]; bool started = node.m_leaf.Start(node.m_center, node.m_radius); ms_pool[nodeID] = node; if (started) { ms_workingCells.Enqueue(nodeID); } else { ms_dirtyNodes.Enqueue(nodeID); } } JobHandle.ScheduleBatchedJobs(); for (int i = 0; i < workCount; ++i) { var nodeID = ms_workingCells.Dequeue(); var node = ms_pool[nodeID]; bool finished = node.m_leaf.Finish(); ms_pool[nodeID] = node; if (!finished) { ms_workingCells.Enqueue(nodeID); } } }
void ConvertQueueToMesh(NativeQueue <Line> lineList) { int count = lineList.Count; var vertices = new Vector3[count * 2]; var indices = new int[count * 2]; for (int i = 0; i < count; i++) { var line = lineList.Dequeue(); var i1 = i * 2; var i2 = i1 + 1; vertices[i1] = line.Start; vertices[i2] = line.End; indices[i1] = i1; indices[i2] = i2; } m_Mesh.Clear(true); m_Mesh.SetVertices(vertices); m_Mesh.SetIndices(indices, MeshTopology.Lines, 0); }
public void SpawnParticle(bool priority, Vector3 position, Quaternion rotation) { List <ParticleSystemObject> tmpParticleListToUse = priority ? priorityParticleList : nonPriorityParticleList; NativeArray <float> tmpParticleTimeArray = priority ? priorityParticleTimeArray : nonPriorityParticleTimeArray; NativeQueue <int> tmpParticleAvailableQueue = priority ? priorityParticleAvailableQueue : nonPriorityParticleAvailableQueue; if (tmpParticleAvailableQueue.Count == 0) { return; } int nextAvailableParticle = tmpParticleAvailableQueue.Dequeue(); if (tmpParticleListToUse[nextAvailableParticle].runningTime > 0.0f) { tmpParticleListToUse[nextAvailableParticle].StartParticleSystem(position, rotation); tmpParticleTimeArray[nextAvailableParticle] = tmpParticleListToUse[nextAvailableParticle].runningTime; } else { tmpParticleAvailableQueue.Enqueue(nextAvailableParticle); } }