示例#1
0
        protected override JobHandle OnUpdate(JobHandle inputDeps)
        {
            BoidHashMap.cellSize = Settings.Instance.Boid.surroundingsViewRange;
            //EntityArchetype archetype = EntityManager.CreateArchetype(typeof(BoidComponent), typeof(Translation), typeof(PhysicsVelocity));
            EntityQuery query = EntityManager.CreateEntityQuery(typeof(BoidComponent), typeof(Translation), typeof(PhysicsVelocity));

            BoidMap.Clear();
            int queryCount = query.CalculateEntityCount();

            if (queryCount > BoidMap.Capacity)
            {
                BoidMap.Capacity = queryCount;
            }

            NativeMultiHashMap <int, BoidData> .ParallelWriter parallelWriter = BoidMap.AsParallelWriter();
            float cellSize = BoidHashMap.cellSize;

            inputDeps = Entities.WithAny <BoidComponent>().ForEach((Entity entity, ref Translation translation, ref PhysicsVelocity velocity) =>
            {
                parallelWriter.Add(Utils.GetHash(translation.Value, cellSize), new BoidData {
                    entity = entity, position = translation.Value, velocity = velocity.Linear
                });
            }).Schedule(inputDeps);


            return(inputDeps);
        }
    private void CutTrees(EntityCommandBuffer.ParallelWriter ecb, int sortKey, Environment env)
    {
        /* Burst requires conversion to locals */

        NativeMultiHashMap <uint2, TreeHashNode> hashTable = this.hashTable;

        Entities.ForEach((Entity entity, int entityInQueryIndex, in RoadSegment roadSegment) =>
        {
            NativeList <uint2> nodes = new NativeList <uint2>(Allocator.Temp);

            float3 mid   = (roadSegment.initial + roadSegment.final) / 2;
            float length = math.distance(roadSegment.initial, roadSegment.final) / 2;

            float2 center = (mid.xz - Environment.TerrainBoundaries.Min.xz) /
                            env.gridSize;
            float radius = (length + env.roadWidth) / env.gridSize;

            Circle influenceZone = new Circle(center, radius);

            GridIntersection.Circle(influenceZone, nodes);

            for (int i = 0; i < nodes.Length; i++)
            {
                RemoveTreeFromSegment(hashTable, nodes[i], roadSegment, ecb, sortKey, env);
            }

            ecb.DestroyEntity(entityInQueryIndex, entity);
            nodes.Dispose();
        })
        .WithReadOnly(hashTable)
        .ScheduleParallel(Dependency).Complete();
    }
        protected override void OnUpdate()
        {
            VehiclesSegmentsHashMap.Clear();
            EntityQuery entityQuery = GetEntityQuery(typeof(VehiclePositionComponent));

            if (entityQuery.CalculateEntityCount() > VehiclesSegmentsHashMap.Capacity)
            {
                VehiclesSegmentsHashMap.Capacity = entityQuery.CalculateEntityCount();
            }

            NativeMultiHashMap <Entity, VehicleSegmentData> .ParallelWriter multiHashMap = VehiclesSegmentsHashMap.AsParallelWriter();
            Dependency = Entities.ForEach((Entity entity, int entityInQueryIndex,
                                           in VehicleSegmentInfoComponent vehicleSegmentInfoComponent,
                                           in VehiclePositionComponent vehiclePositionComponent,
                                           in VehicleConfigComponent vehicleConfigComponent) =>
            {
                Entity segmentEntity = vehicleSegmentInfoComponent.IsBackInPreviousSegment
                    ? vehicleSegmentInfoComponent.PreviousSegment
                    : vehicleSegmentInfoComponent.HeadSegment;
                multiHashMap.Add(segmentEntity, new VehicleSegmentData
                {
                    Entity          = entity,
                    BackSegPosition = vehiclePositionComponent.BackSegPos,
                    VehicleSize     = vehicleConfigComponent.Length
                });
            }).ScheduleParallel(Dependency);
        protected override void OnCreate()
        {
            base.OnCreate();

            // Allocate the map only on create to avoid allocating every frame.
            _effects = new NativeMultiHashMap <Entity, EFFECT_CTX>(0, Allocator.Persistent);
        }
    public void MultiHashMapValueIterator()
    {
        var hashMap = new NativeMultiHashMap <int, int> (1, Allocator.Temp);

        hashMap.Add(5, 0);
        hashMap.Add(5, 1);
        hashMap.Add(5, 2);

        var list = new NativeList <int>(Allocator.TempJob);

        GCAllocRecorder.ValidateNoGCAllocs(() =>
        {
            list.Clear();
            foreach (var value in hashMap.GetValuesForKey(5))
            {
                list.Add(value);
            }
        });

        list.Sort();
        Assert.AreEqual(list.ToArray(), new int[] { 0, 1, 2 });

        foreach (var value in hashMap.GetValuesForKey(6))
        {
            Assert.Fail();
        }

        list.Dispose();
        hashMap.Dispose();
    }
    public void NativeMultiHashMap_RemoveKeyValueThrowsInvalidParam()
    {
        var hashMap = new NativeMultiHashMap <int, long>(1, Allocator.Temp);

        Assert.Throws <ArgumentException>(() => hashMap.Remove(5, 5));
        hashMap.Dispose();
    }
示例#7
0
    protected override void OnUpdate()
    {
        var unitCount = query.CalculateEntityCount();
        var nextGridPositionHashMap = new NativeMultiHashMap <int, int>(unitCount, Allocator.TempJob);
        var parallelWriter          = nextGridPositionHashMap.AsParallelWriter();

        Entities
        .WithName("HashNextGridPositions")
        .WithStoreEntityQueryInField(ref query)
        .WithBurst()
        .ForEach((int entityInQueryIndex, in NextGridPosition nextGridPosition) =>
        {
            var hash = (int)math.hash(nextGridPosition.Value);
            parallelWriter.Add(hash, entityInQueryIndex);
        })
        .ScheduleParallel();

        Entities
        .WithName("FinalizeMovement")
        .WithReadOnly(nextGridPositionHashMap)
        .WithDisposeOnCompletion(nextGridPositionHashMap)
        .WithBurst()
        .ForEach((ref NextGridPosition nextGridPosition, in GridPosition gridPosition) =>
        {
            int hash = (int)math.hash(nextGridPosition.Value);
            if (nextGridPositionHashMap.TryGetFirstValue(hash, out _, out var iter))
            {
                if (nextGridPositionHashMap.TryGetNextValue(out _, ref iter))
                {
                    nextGridPosition.Value = gridPosition.Value;
                }
            }
        })
        .ScheduleParallel();
    }
        public void EvaluateCumulativeRewardEstimatorMultipleStates()
        {
            const int kStateCount     = 10;
            var       states          = new NativeList <int>(kStateCount, Allocator.TempJob);
            var       stateInfoLookup = new NativeHashMap <int, StateInfo>(kStateCount, Allocator.TempJob);
            var       binnedStateKeys = new NativeMultiHashMap <int, int>(kStateCount, Allocator.TempJob);

            for (int i = 0; i < kStateCount; i++)
            {
                states.Add(i);
            }

            var stateEvaluationJob = new EvaluateNewStatesJob <int, int, TestStateDataContext, StateValueAsCumulativeRewardEstimatorValue, DefaultTerminalStateEvaluator <int> >
            {
                StateDataContext = new TestStateDataContext(),
                StateInfoLookup  = stateInfoLookup.AsParallelWriter(),
                States           = states.AsDeferredJobArray(),
                BinnedStateKeys  = binnedStateKeys.AsParallelWriter(),
            };

            stateEvaluationJob.Schedule(states, default).Complete();

            for (int i = 0; i < states.Length; i++)
            {
                stateInfoLookup.TryGetValue(i, out var stateInfo);

                Assert.AreEqual(new BoundedValue(i, i, i), stateInfo.CumulativeRewardEstimate);
            }

            states.Dispose();
            stateInfoLookup.Dispose();
            binnedStateKeys.Dispose();
        }
示例#9
0
 public static NativeMultiHashMapEnumerator <TKey, TValue> GetEnumerator <TKey, TValue>(
     this NativeMultiHashMap <TKey, TValue> nativeMultiHashMap)
     where TKey : struct, IEquatable <TKey>
     where TValue : struct
 {
     return(new NativeMultiHashMapEnumerator <TKey, TValue>(in nativeMultiHashMap));
 }
    public void NativeHashMapMergeCountShared()
    {
        var count            = 1024;
        var sharedKeyCount   = 16;
        var sharedCount      = new NativeArray <int>(count, Allocator.TempJob);
        var sharedIndices    = new NativeArray <int>(count, Allocator.TempJob);
        var totalSharedCount = new NativeArray <int>(1, Allocator.TempJob);
        var hashMap          = new NativeMultiHashMap <int, int>(count, Allocator.TempJob);

        for (int i = 0; i < count; i++)
        {
            hashMap.Add(i & (sharedKeyCount - 1), i);
            sharedCount[i] = 1;
        }

        var mergeSharedValuesJob = new MergeSharedValues
        {
            sharedCount   = sharedCount,
            sharedIndices = sharedIndices,
        };
        var mergetedSharedValuesJobHandle = mergeSharedValuesJob.Schedule(hashMap, 64);

        mergetedSharedValuesJobHandle.Complete();

        for (int i = 0; i < count; i++)
        {
            Assert.AreEqual(count / sharedKeyCount, sharedCount[sharedIndices[i]]);
        }

        sharedCount.Dispose();
        sharedIndices.Dispose();
        totalSharedCount.Dispose();
        hashMap.Dispose();
    }
        protected override void OnUpdate()
        {
            if (m_AttributeModifiers.CalculateEntityCount() == 0)
            {
                Dependency = new ResetAttributeModificationsForPlayer()
                {
                    AttributeModifierValuesHandle = GetComponentTypeHandle <TAttributeModifier>(false),
                    EntitiesHandle = GetEntityTypeHandle()
                }.ScheduleParallel(m_AttributesGroup, Dependency);
                return;
            }

            NativeMultiHashMap <Entity, TGameplayAttributesModifier> AttributeModifiersNMHM = new NativeMultiHashMap <Entity, TGameplayAttributesModifier>(m_AttributeModifiers.CalculateEntityCount(), Allocator.TempJob);

            Dependency = new CollectAllAttributeModifiers()
            {
                AttributeModifiersNMHMWriter    = AttributeModifiersNMHM.AsParallelWriter(),
                GameplayAttributeModifierHandle = GetComponentTypeHandle <TGameplayAttributesModifier>(true),
                GameplayEffectContextHandle     = GetComponentTypeHandle <GameplayEffectContextComponent>(true)
            }.ScheduleParallel(m_AttributeModifiers, Dependency);
            Dependency = new MapAttributeModificationsToPlayer()
            {
                AttributeModifierValuesHandle = GetComponentTypeHandle <TAttributeModifier>(false),
                AttributeModifierCollection   = AttributeModifiersNMHM,
                EntitiesHandle = GetEntityTypeHandle()
            }.ScheduleParallel(m_AttributesGroup, Dependency);
            // Now write to the attributes
            AttributeModifiersNMHM.Dispose(Dependency);
        }
        public static void SetupCollisionTriggerData(EntityManager entityManager, ref NativeMultiHashMap <Entity, CollisionTriggerData> nativeMultiHashMap, EntityQuery q, EventType collisionMode)
        {
            var calculateEntityCount = q.CalculateEntityCount();

            if (nativeMultiHashMap.Capacity < calculateEntityCount)
            {
                nativeMultiHashMap.Capacity = calculateEntityCount;
            }
            var frame = UnityEngine.Time.frameCount;
            var job   = new CollectCollisionsJob
            {
                Frame     = frame,
                CollInfos = nativeMultiHashMap,
                ThisMask  = entityManager.GetEntityQueryMask(q),
                OtherMask = entityManager.GetEntityQueryMask(entityManager.UniversalQuery),
            };

            var buildPhysicsWorldSystem = entityManager.World.GetOrCreateSystem <BuildPhysicsWorld>();
            var stepPhysicsWorldSystem  = entityManager.World.GetOrCreateSystem <StepPhysicsWorld>();

            if (collisionMode == EventType.Collision)
            {
                job.EventType = EventType.Collision;
                ICollisionEventJobExtensions
                .Schedule(job, stepPhysicsWorldSystem.Simulation, ref buildPhysicsWorldSystem.PhysicsWorld, new JobHandle())
                .Complete();
            }
            else if (collisionMode == EventType.Trigger)
            {
                job.EventType = EventType.Trigger;
                ITriggerEventJobExtensions
                .Schedule(job, stepPhysicsWorldSystem.Simulation, ref buildPhysicsWorldSystem.PhysicsWorld, new JobHandle())
                .Complete();
            }
        }
        public static NativeArray <CollisionTriggerData>?CollectCollisionTriggerData(ref NativeMultiHashMap <Entity, CollisionTriggerData> nativeMultiHashMap, Entity e)
        {
            int frame = UnityEngine.Time.frameCount;
            var count = nativeMultiHashMap.CountValuesForKey(e);
            NativeArray <CollisionTriggerData> collisions = new NativeArray <CollisionTriggerData>(count, Allocator.Temp);
            int idx = 0;

            if (nativeMultiHashMap.TryGetFirstValue(e, out var collInfo1, out var it))
            {
                do
                {
                    if (collInfo1.Frame < frame)
                    {
                        collInfo1.State = CollisionState.Exit;
                        nativeMultiHashMap.Remove(it);
                    }
                    else if (collInfo1.Frame == frame)
                    {
                        // MBRIAU: What are we trying to clean up here?
                        collInfo1.State = collInfo1.State == CollisionState.Stay ? CollisionState.Stay : CollisionState.Enter;
                    }
                    collisions[idx++] = collInfo1;
                }while (nativeMultiHashMap.TryGetNextValue(out collInfo1, ref it));
            }

            return(collisions);
        }
示例#14
0
 protected override void OnCreate()
 {
     commandBuffer   = World.GetOrCreateSystem <EndSimulationEntityCommandBufferSystem>();
     DamageMap       = new NativeMultiHashMap <Entity, float>(0, Allocator.Persistent);
     damageableUnits = GetEntityQuery(ComponentType.ReadOnly <HealthComponent>());
     base.OnCreate();
 }
示例#15
0
    private void FindValidPoints(int index, NativeList <float> freePointList,
                                 NativeList <float> blockedPointList,
                                 NativeMultiHashMap <int, RaycastHit> hits)
    {
        if (hits.ContainsKey(index))
        {
            NativeMultiHashMap <int, RaycastHit> .Enumerator tempHits = hits.GetValuesForKey(index);
            tempHits.MoveNext();

            //The Top most point is always free
            freePointList.Add(tempHits.Current.point.y);
            Vector3 prevPoint = tempHits.Current.point;

            while (tempHits.MoveNext())
            {
                RaycastHit currentHit = tempHits.Current;

                if (currentHit.point.y + playerHeight > prevPoint.y)
                {
                    blockedPointList.Add(currentHit.point.y);
                }
                else
                {
                    freePointList.Add(currentHit.point.y);
                }

                prevPoint = currentHit.point;
            }
        }
    }
示例#16
0
        protected override void OnUpdate()
        {
            int targetNumber    = TargetQuery.CalculateEntityCount();
            var targetMap       = new NativeMultiHashMap <int, Target>(targetNumber, Allocator.TempJob);
            var targetMapWriter = targetMap.AsParallelWriter();

            // Store target information in hash map.
            Entities
            .WithAll <Targetable>()
            .WithStoreEntityQueryInField(ref TargetQuery)
            .ForEach((
                         Entity targetEntity,
                         in LocalToWorld localToWorld,
                         in Team team,
                         in AgentCategory category,
                         in Health health,
                         in MaxHealth maxHealth
                         ) =>
            {
                var healthFraction = health.Value / maxHealth.Value;
                var pos            = localToWorld.Position;
                targetMapWriter.Add(
                    HashPosition(pos), new Target
                {
                    Entity        = targetEntity,
                    Category      = category,
                    HealthPercent = healthFraction,
                    Position      = pos,
                    Team          = team.ID
                });
            })
    public void NativeMultiHashMap_Double_Deallocate_Throws()
    {
        var hashMap = new NativeMultiHashMap <int, int>(16, Allocator.TempJob);

        hashMap.Dispose();
        Assert.Throws <InvalidOperationException>(() => { hashMap.Dispose(); });
    }
            /// <summary>
            /// Ensure a <see cref="NativeMultiHashMap{TKey,TValue}" /> has the capacity to be filled with all events of a specific type.
            /// If the hash map already has elements, it will increase the size so that all events and existing elements can fit.
            /// </summary>
            /// <param name="handle"> Input dependencies. </param>
            /// <param name="hashMap"> The <see cref="NativeHashMap{TKey,TValue}"/> to ensure capacity of. </param>
            /// <typeparam name="TKey"> The key type of the <see cref="NativeHashMap{TKey,TValue}"/> . </typeparam>
            /// <typeparam name="TValue"> The value type of the <see cref="NativeHashMap{TKey,TValue}"/> . </typeparam>
            /// <returns> The dependency handle. </returns>
            public JobHandle EnsureHashMapCapacity <TKey, TValue>(
                JobHandle handle,
                NativeMultiHashMap <TKey, TValue> hashMap)
                where TKey : struct, IEquatable <TKey>
                where TValue : struct
            {
                var readerCount = this._eventSystem.GetEventReadersCount <T>();

                if (readerCount != 0)
                {
                    var counter = new NativeArray <int>(readerCount, Allocator.TempJob);

                    handle = new CountJob {
                        Counter = counter
                    }
                    .ScheduleSimultaneous <CountJob, T>(this._eventSystem, handle);

                    handle = new EnsureMultiHashMapCapacityJob <TKey, TValue>
                    {
                        Counter = counter,
                        HashMap = hashMap,
                    }
                    .Schedule(handle);

                    handle = counter.Dispose(handle);
                }

                return(handle);
            }
    protected override void OnCreate()
    {
        // End simulation is at end of Update(). Not end of frame.
        _ecbBarrier = World.GetOrCreateSystem <EndSimulationEntityCommandBufferSystem>();

        // GOAL: 605 * Factory count!
        _tradeAsks      = new NativeMultiHashMap <int, Offer>(100000, Allocator.Persistent);
        _tradeBids      = new NativeMultiHashMap <int, Offer>(100000, Allocator.Persistent);
        _deltaMoney     = new NativeMultiHashMap <Entity, float>(100000, Allocator.Persistent);
        _profitsByLogic = new NativeMultiHashMap <Entity, float>(100000, Allocator.Persistent);
        _bankrupt       = new NativeQueue <BankruptcyInfo>(Allocator.Persistent);

        _goodsCount = History.GoodsCount;
        _agentArch  = EntityManager.CreateArchetype(typeof(Agent), typeof(Wallet));

        AskHistory   = new NativeArray <float>(_goodsCount, Allocator.Persistent);
        BidHistory   = new NativeArray <float>(_goodsCount, Allocator.Persistent);
        TradeHistory = new NativeArray <float>(_goodsCount, Allocator.Persistent);
        PriceHistory = new NativeArray <float>(_goodsCount, Allocator.Persistent);
        RatioHistory = new NativeArray <float>(_goodsCount, Allocator.Persistent);

        _logicEntities = EntityManager.CreateEntityQuery(typeof(Logic))
                         .ToEntityArray(Allocator.Persistent);
        ProfitsHistory = new NativeArray <float>(_logicEntities.Length, Allocator.Persistent);
        FieldHistory   = new NativeArray <float>(_logicEntities.Length, Allocator.Persistent);
        new GatherAgentsPerEntityCount
        {
            FieldHistory = FieldHistory,
            LogicData    = GetComponentDataFromEntity <Logic>(true)
        }.ScheduleSingle(this).Complete(); // Single threaded intentionally

        _goodsMostLogic = new NativeArray <Entity>(InitializeMarket.GoodsMostLogic, Allocator.Persistent);
        InitializeMarket.GoodsMostLogic = null;
    }
    protected override void OnCreate()
    {
        base.OnCreate();

        Enabled = false;

        Addressables.LoadAssetAsync <BattleMapSettings>("Battle Map Settings")
        .Completed += handle =>
        {
            if (handle.Status == AsyncOperationStatus.Succeeded)
            {
                _battleMapSettings = handle.Result;
                _conversionFactor  = 1 / _battleMapSettings.CellSize;
                _cellWidth         = (uint)(_battleMapSettings.MapSize.x / _battleMapSettings.CellSize);

                var numBuckets = _battleMapSettings.MapSize.x * _battleMapSettings.MapSize.y;
                _buckets = new NativeMultiHashMap <uint, Entity>(numBuckets, Allocator.Persistent);
                World.GetOrCreateSystem <UnitMovementSystem>().SetBucketsBuffer(_buckets);
                Enabled = true;
            }
            else
            {
                Debug.LogError("Failed to load battle map settings");
            }
        };
    }
        protected sealed override void OnUpdate()
        {
            Dependency = JobHandle.CombineDependencies(Dependency, TriggerJobHandle);

            // If the producer did not actually write anything to the stream, the native stream will not be flaged as created.
            // In that case we don't need to do anything.
            // Not doing this checks actually result in a non authrorized access to the memory and crashes Unity.
            if (!_effectStream.IsCreated)
            {
                return;
            }
            NativeStream.Reader effectReader = GetEffectReader();
            SetupEffectMap      AllocateJob  = new SetupEffectMap()
            {
                EffectReader = effectReader,
                Effects      = _effects
            };

            Dependency = AllocateJob.Schedule(Dependency);


            NativeMultiHashMap <Entity, EFFECT_CTX> .ParallelWriter effectsWriter = _effects.AsParallelWriter();
            RemapEffects RemapEffectsJob = new RemapEffects()
            {
                EffectReader  = effectReader,
                EffectsWriter = _effects.AsParallelWriter()
            };

            Dependency = RemapEffectsJob.Schedule(_forEachCount, 1, Dependency);

            // Call the effect consumption logic defined in hte derived class.
            Consume();

            Dependency = _effectStream.Dispose(Dependency);
        }
示例#22
0
 public void Begin(PipelineSettings settings)
 {
     ClustersAABBs         = new NativeArray <AABB>(settings.NumClusters, Allocator.TempJob);
     ResultClusterNumItems = new NativeArray <clusternumlights_t>(settings.NumClusters, Allocator.TempJob);
     ResultItemsIDList     = new NativeArray <uint>(settings.MaxItemsPerCluster * settings.NumClusters, Allocator.TempJob);
     ResultItemsIDVec      = new NativeMultiHashMap <int, uint>(settings.NumClusters * settings.MaxItemsPerCluster, Allocator.TempJob);
 }
    public void RemoveKeyAndValue()
    {
        var hashMap = new NativeMultiHashMap <int, long> (1, Allocator.Temp);

        hashMap.Add(10, 0);
        hashMap.Add(10, 1);
        hashMap.Add(10, 2);

        hashMap.Add(20, 2);
        hashMap.Add(20, 2);
        hashMap.Add(20, 1);
        hashMap.Add(20, 2);
        hashMap.Add(20, 1);

        hashMap.Remove(10, 1L);
        ExpectValues(hashMap, 10, new [] { 0L, 2L });
        ExpectValues(hashMap, 20, new [] { 1L, 1L, 2L, 2L, 2L });

        hashMap.Remove(20, 2L);
        ExpectValues(hashMap, 10, new [] { 0L, 2L });
        ExpectValues(hashMap, 20, new [] { 1L, 1L });

        hashMap.Remove(20, 1L);
        ExpectValues(hashMap, 10, new [] { 0L, 2L });
        ExpectValues(hashMap, 20, new long [0]);

        hashMap.Dispose();
    }
 public BlobAssetComputationContext(BlobAssetStore blobAssetStore, int initialCapacity, Allocator allocator)
 {
     m_BlobAssetStore = blobAssetStore ?? throw new ArgumentNullException(nameof(blobAssetStore), "A valid BlobAssetStore must be passed to construct a BlobAssetComputationContext");
     m_ToCompute = new NativeHashMap<Hash128, TS>(initialCapacity, allocator);
     m_Computed = new NativeHashMap<Hash128, BlobAssetReference<TB>>(initialCapacity, allocator);
     m_BlobPerGameObject = new NativeMultiHashMap<int, Hash128>(initialCapacity, allocator);
 }
示例#25
0
        public SpatialHash(Bounds worldBounds, float3 cellSize, int startSize, Allocator label)
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            DisposeSentinel.Create(out _safety, out _disposeSentinel, 0, label);
#endif
            _allocatorLabel       = label;
            _data                 = (SpatialHashData *)UnsafeUtility.Malloc(sizeof(SpatialHashData), UnsafeUtility.AlignOf <SpatialHashData>(), label);
            _data->WorldBounds    = worldBounds;
            _data->WorldBoundsMin = worldBounds.Min;
            _data->CellSize       = cellSize;
            _data->CellCount      = worldBounds.GetCellCount(cellSize);
            _data->RayCastBound   = new Bounds();
            _data->HasHit         = false;
            _data->Counter        = 0;
            _data->RayOrigin      = float3.zero;
            _data->RayDirection   = float3.zero;

            _buckets            = new NativeMultiHashMap <uint, int>(startSize, label);
            _itemIDToBounds     = new NativeHashMap <int, Bounds>(startSize >> 1, label);
            _itemIDToItem       = new NativeHashMap <int, T>(startSize >> 1, label);
            _helpMoveHashMapOld = new NativeHashMap <int3, byte>(128, _allocatorLabel);
            _helpMoveHashMapNew = new NativeHashMap <int3, byte>(128, _allocatorLabel);

            _voxelRay    = new VoxelRay <SpatialHash <T> >();
            _rayHitValue = 0;
        }
 internal SceneHierarchy(IncrementalHierarchy hierarchy)
 {
     _instanceId          = hierarchy.InstanceId;
     _parentIndex         = hierarchy.ParentIndex;
     _indexByInstanceId   = hierarchy.IndexByInstanceId;
     _childIndicesByIndex = hierarchy.ChildIndicesByIndex;
 }
    public void Key_Collisions()
    {
        var hashMap     = new NativeMultiHashMap <int, int>(hashMapSize, Allocator.TempJob);
        var writeStatus = new NativeArray <int>(hashMapSize, Allocator.TempJob);
        var readValues  = new NativeArray <int>(hashMapSize, Allocator.TempJob);

        var writeData = new MultiHashMapWriteParallelForJob();

        writeData.hashMap = hashMap.AsParallelWriter();
        writeData.status  = writeStatus;
        writeData.keyMod  = 16;
        var readData = new MultiHashMapReadParallelForJob();

        readData.hashMap = hashMap;
        readData.values  = readValues;
        readData.keyMod  = writeData.keyMod;
        var writeJob = writeData.Schedule(hashMapSize, 1);
        var readJob  = readData.Schedule(hashMapSize, 1, writeJob);

        readJob.Complete();

        for (int i = 0; i < hashMapSize; ++i)
        {
            Assert.AreEqual(0, writeStatus[i], "Job failed to write value to hash map");
            Assert.AreEqual(hashMapSize / readData.keyMod, readValues[i], "Job failed to read from hash map");
        }

        hashMap.Dispose();
        writeStatus.Dispose();
        readValues.Dispose();
    }
    public void NativeMultiHashMap_Read_And_Write_Without_Fences()
    {
        var hashMap     = new NativeMultiHashMap <int, int>(hashMapSize, Allocator.TempJob);
        var writeStatus = new NativeArray <int>(hashMapSize, Allocator.TempJob);
        var readValues  = new NativeArray <int>(hashMapSize, Allocator.TempJob);

        var writeData = new MultiHashMapWriteParallelForJob()
        {
            hashMap = hashMap.AsParallelWriter(),
            status  = writeStatus,
            keyMod  = hashMapSize,
        };

        var readData = new MultiHashMapReadParallelForJob()
        {
            hashMap = hashMap,
            values  = readValues,
            keyMod  = writeData.keyMod,
        };

        var writeJob = writeData.Schedule(hashMapSize, 1);

        Assert.Throws <InvalidOperationException> (() => { readData.Schedule(hashMapSize, 1); });
        writeJob.Complete();

        hashMap.Dispose();
        writeStatus.Dispose();
        readValues.Dispose();
    }
            private GameplayEffectDurationComponent GetMaxFromNMHP(Entity entity, NativeMultiHashMap <Entity, GameplayEffectDurationComponent> values)
            {
                values.TryGetFirstValue(entity, out var longestCooldownComponent, out var multiplierIt);
                while (values.TryGetNextValue(out var tempLongestCooldownComponent, ref multiplierIt))
                {
                    var tDiff = tempLongestCooldownComponent.RemainingTime - longestCooldownComponent.RemainingTime;
                    var newPercentRemaining = tempLongestCooldownComponent.RemainingTime / tempLongestCooldownComponent.NominalDuration;
                    var oldPercentRemaining = longestCooldownComponent.RemainingTime / longestCooldownComponent.NominalDuration;

                    // If the duration currently being evaluated has more time remaining than the previous one,
                    // use this as the cooldown.
                    // If the durations are the same, then use the one which has the longer nominal time.
                    // E.g. if we have two abilities, one with a nominal duration of 10s and 2s respectively,
                    // but both have 1s remaining, then the "main" cooldown should be the 10s cooldown.
                    if (tDiff > 0)
                    {
                        longestCooldownComponent = tempLongestCooldownComponent;
                    }
                    else if (tDiff == 0 && tempLongestCooldownComponent.NominalDuration > longestCooldownComponent.NominalDuration)
                    {
                        longestCooldownComponent = tempLongestCooldownComponent;
                    }
                }
                return(longestCooldownComponent);
            }
示例#30
0
    protected sealed override void OnCreate()
    {
        base.OnCreate();

        chunkDataMap = new NativeMultiHashMap <int, RenderData>(0, Allocator.TempJob);

        manager = EntityManager;

        defaultQueryDesc = new EntityQueryDesc()
        {
            All  = AllDefaultQuery,
            None = AllNoneQuery
        };
        specialQueryDesc = new EntityQueryDesc()
        {
            All  = AllSpecialQuery,
            None = AllNoneQuery
        };

        var shadowQD = new[] { ComponentType.ReadOnly <CastSpritesShadowComponentData>() };

        defaultWithShadowsQueryDesc = new EntityQueryDesc()
        {
            All  = AllDefaultQuery.Concat(shadowQD).ToArray(),
            None = AllNoneQuery
        };
        specialWithShadowsQueryDesc = new EntityQueryDesc()
        {
            All  = AllSpecialQuery.Concat(shadowQD).ToArray(),
            None = AllNoneQuery
        };
    }