public static void Initialize(BlockCollection blockCollection) { if (isInitialized) { Debug.LogWarning("Block provider is already initialized."); return; } blocks = new NativeHashMap <int, Block>(0, Allocator.Persistent); blockIds = new Dictionary <string, int>(); blockNames = new Dictionary <string, string>(); palette = new Dictionary <int, string>(); emptyBlocks = new NativeArray <int>(Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE, Allocator.Persistent); blocks.Add(AIR_TYPE_ID, new Block(AIR_TYPE_ID) { canCollide = false }); blockNames.Add(AIR_TYPE, "Air"); blockIds.Add(AIR_TYPE, AIR_TYPE_ID); palette.Add(AIR_TYPE_ID, AIR_TYPE); for (ushort i = 0; i < blockCollection.Blocks.Length; i++) { if (blockCollection.Blocks[i] == null) { #if DEBUG Debug.LogWarning("Element " + i + " in your block collection is null. Skipping it."); #endif continue; } ushort id = (ushort)(i + 1); #if DEBUG if (blockNames.ContainsKey(blockCollection.Blocks[i].BlockID)) { Debug.LogError("Found multiple blocks with the ID '" + blockCollection.Blocks[i].BlockID + "'."); } #endif blockIds.Add(blockCollection.Blocks[i].BlockID, id); blockNames.Add(blockCollection.Blocks[i].BlockID, blockCollection.Blocks[i].BlockName); palette.Add(id, blockCollection.Blocks[i].BlockID); if (blockCollection.Blocks[i] is CubeConfig cube) { Block block = new Block(id, cube); blocks.Add(id, block); } else { Block block = new Block(id); blocks.Add(id, block); } } isInitialized = true; }
// Static and dynamic rigid bodies public unsafe void CreateRigidBodies() { NativeArray <RigidBody> dynamicBodies = PhysicsWorld.DynamicBodies; NativeArray <RigidBody> staticBodies = PhysicsWorld.StaticBodies; // Creating dynamic bodies { NativeArray <CustomCollider> colliders = CustomDynamicEntityGroup.ToComponentDataArray <CustomCollider>(Allocator.TempJob); NativeArray <Translation> positions = CustomDynamicEntityGroup.ToComponentDataArray <Translation>(Allocator.TempJob); NativeArray <Rotation> rotations = CustomDynamicEntityGroup.ToComponentDataArray <Rotation>(Allocator.TempJob); NativeArray <PhysicsCustomTags> customTags = CustomDynamicEntityGroup.ToComponentDataArray <PhysicsCustomTags>(Allocator.TempJob); NativeArray <Entity> entities = CustomDynamicEntityGroup.ToEntityArray(Allocator.TempJob); for (int i = 0; i < entities.Length; i++) { dynamicBodies[i] = new RigidBody { WorldFromBody = new RigidTransform(rotations[i].Value, positions[i].Value), Collider = colliders[i].ColliderRef, Entity = entities[i], CustomTags = customTags[i].Value }; EntityToBodyIndexMap.Add(entities[i], i); } colliders.Dispose(); positions.Dispose(); rotations.Dispose(); customTags.Dispose(); entities.Dispose(); } // Creating static bodies { NativeArray <CustomCollider> colliders = CustomStaticEntityGroup.ToComponentDataArray <CustomCollider>(Allocator.TempJob); NativeArray <Translation> positions = CustomStaticEntityGroup.ToComponentDataArray <Translation>(Allocator.TempJob); NativeArray <Rotation> rotations = CustomStaticEntityGroup.ToComponentDataArray <Rotation>(Allocator.TempJob); NativeArray <PhysicsCustomTags> customTags = CustomStaticEntityGroup.ToComponentDataArray <PhysicsCustomTags>(Allocator.TempJob); NativeArray <Entity> entities = CustomStaticEntityGroup.ToEntityArray(Allocator.TempJob); for (int i = 0; i < entities.Length; i++) { staticBodies[i] = new RigidBody { WorldFromBody = new RigidTransform(rotations[i].Value, positions[i].Value), Collider = colliders[i].ColliderRef, Entity = entities[i], CustomTags = customTags[i].Value }; EntityToBodyIndexMap.Add(entities[i], i + dynamicBodies.Length); } // default static body staticBodies[entities.Length] = new RigidBody { WorldFromBody = new RigidTransform(quaternion.identity, float3.zero), Collider = default,
public void RegisterRpc(ComponentType type, PortableFunctionPointer <RpcExecutor.ExecuteDelegate> exec) { if (!m_CanRegister) { throw new InvalidOperationException("Cannot register new RPCs after the RpcSystem has started running"); } if (!exec.Ptr.IsCreated) { throw new InvalidOperationException($"Cannot register RPC for type {type.GetManagedType()}: Ptr property is not created (null)" + "Check CompileExecute() and verify you are initializing the PortableFunctionPointer with a valid static function delegate, decorated with [BurstCompile] attribute"); } var hash = TypeManager.GetTypeInfo(type.TypeIndex).StableTypeHash; if (hash == 0) { throw new InvalidOperationException(String.Format("Unexpected 0 hash for type {0}", type.GetManagedType())); } if (m_RpcTypeHashToIndex.TryGetValue(hash, out var index)) { var rpcData = m_RpcData[index]; if (rpcData.TypeHash != 0) { #if ENABLE_UNITY_COLLECTIONS_CHECKS if (rpcData.RpcType == type) { throw new InvalidOperationException( String.Format("Registering RPC {0} multiple times is not allowed", type.GetManagedType())); } throw new InvalidOperationException( String.Format("Type hash collision between types {0} and {1}", type.GetManagedType(), rpcData.RpcType.GetManagedType())); #else throw new InvalidOperationException( String.Format("Hash collision or multiple registrations for {0}", type.GetManagedType())); #endif } rpcData.TypeHash = hash; rpcData.Execute = exec; m_RpcData[index] = rpcData; } else { m_RpcTypeHashToIndex.Add(hash, m_RpcData.Length); m_RpcData.Add(new RpcData { TypeHash = hash, Execute = exec, #if ENABLE_UNITY_COLLECTIONS_CHECKS RpcType = type #endif }); } }
protected override void OnUpdate() { var cameraPos = ((float3)mainCam.transform.position).xz; var tAmount = terrainAmount / 2 * tileAmount; var cameraPosTile = (int2)math.round(cameraPos / tAmount); cameraPosTile *= terrainAmount / 2 * tileAmount; // Debug.DrawLine(mainCam.transform.position, new float3(cameraPosTile.x, 0, cameraPosTile.y)); //Debug.Log(math.round(cameraPos / tAmount)); var t = terrainAmount.x * terrainAmount.y; var c = terrainAmount / 2; for (var i = 0; i < t; i++) { var pos2D = (i.To2D(terrainAmount) - c) * tileAmount + cameraPosTile; var pos3D = (new int3(pos2D.x, 0, pos2D.y)); if (tilesA.ContainsKey(pos3D)) { tilesB.Add(pos3D, tilesA[pos3D]); tilesA.Remove(pos3D); } else { // Create new tile tilesB.Add(pos3D, CreateTerracedTile(pos3D)); } } var keys = tilesA.GetKeyArray(Allocator.Temp); // Destroy tiles... for (var i = 0; i < keys.Length; i++) { EntityManager.DestroyEntity(tilesA[keys[i]]); tilesA.Remove(keys[i]); } var keyValueArray = tilesB.GetKeyValueArrays(Allocator.Temp); // Swap hash map for (var i = 0; i < keyValueArray.Keys.Length; i++) { tilesA.Add(keyValueArray.Keys[i], keyValueArray.Values[i]); tilesB.Remove(keyValueArray.Keys[i]); } }
public void NativeHashMap_HashMapSameKey() { using (var hashMap = new NativeHashMap <int, int>(0, Allocator.Persistent)) { Assert.DoesNotThrow(() => hashMap.Add(0, 0)); Assert.Throws <ArgumentException>(() => hashMap.Add(0, 0)); } using (var hashMap = new NativeHashMap <int, int>(0, Allocator.Persistent)) { Assert.IsTrue(hashMap.TryAdd(0, 0)); Assert.IsFalse(hashMap.TryAdd(0, 0)); } }
internal void RegisterComponentTypeForDependencyTracking(int typeIndex) { if (!_componentDependenciesByTypeIndex.ContainsKey(typeIndex)) { _componentDependenciesByTypeIndex.Add(typeIndex, new DependencyTracker(Allocator.Persistent)); } }
// ** keep this block in sync ** (end) int GetOrAddHeadIdIndex(int objectInstanceId) { if (!m_HeadIdIndices.TryGetValue(objectInstanceId, out var headIdIndex)) { if (!m_FreeHeadIds.IsEmpty) { int end = m_FreeHeadIds.Length - 1; headIdIndex = m_FreeHeadIds[end]; m_FreeHeadIds.Length -= 1; } else { headIdIndex = m_HeadIdCount++; }; m_HeadIdIndices.Add(objectInstanceId, headIdIndex); var headIdsCapacity = headIdIndex + 1; if (MultiList.CalcExpandCapacity(m_Entities.HeadIds.Length, ref headIdsCapacity)) { m_Entities.SetHeadIdsCapacity(headIdsCapacity); m_LogEvents.SetHeadIdsCapacity(headIdsCapacity); } } return(headIdIndex); }
private void UpdateMap(NativeHashMap <int, Entity> map) { Entities.ForEach((Entity entity, in RoomDefinition roomDefinition) => { map.Add(roomDefinition.NameHash, entity); }).Run(); }
protected override void OnUpdate() { var ecb = ecbs.CreateCommandBuffer(); Entities.WithAll <FontAssetEntity>().ForEach( (Entity e, in FontAssetHolder holder, in DynamicBuffer <GlyphPrefabBuffer> buffer) => { var nativeHashMap = new NativeHashMap <char, Entity>(buffer.Length, Allocator.Persistent); var nativeHashMapWithScale = new NativeHashMap <char, Entity>(buffer.Length, Allocator.Persistent); forDispose.Add(nativeHashMap); forDispose.Add(nativeHashMapWithScale); for (int i = 0; i < buffer.Length; i++) { nativeHashMap.Add(buffer[i].character.ToString()[0], buffer[i].prefab); nativeHashMapWithScale.Add(buffer[i].character.ToString()[0], buffer[i].prefabWithScale); } EntityManager.AddSharedComponentData(e, new GlyphPrefabLookup { characterToPrefabEntity = nativeHashMap, characterToPrefabEntityWithScale = nativeHashMapWithScale }); })
private static int getMiddlePoint(int p1, int p2, NativeList <float3> vertices, NativeHashMap <long, int> cache, float radius) { // first check if we have it already bool firstIsSmaller = p1 < p2; long smallerIndex = firstIsSmaller ? p1 : p2; long greaterIndex = firstIsSmaller ? p2 : p1; long key = ((smallerIndex & 0xFFFF0000) << 48) + ((greaterIndex & 0xFFFF0000) << 32) + ((smallerIndex & 0x0000FFFF) << 16) + (greaterIndex & 0x0000FFFF); int ret; if (cache.TryGetValue(key, out ret)) { return(ret); } // not in cache, calculate it float3 point1 = vertices[p1]; float3 point2 = vertices[p2]; float3 middle = math.lerp(point1, point2, 0.5f); // add vertex makes sure point is on unit sphere int i = vertices.Length; vertices.Add(math.normalize(middle) * radius); // store it, return index cache.Add(key, i); return(i); }
public unsafe UnsafeAppendBuffer *outputTriangles; // Element Type int public void Execute() { unsafe { outputVertices->Reset(); outputTriangles->Reset(); var firstVerts = new NativeHashMap <Int3, int>(vertices.Length, Allocator.Temp); // Remove duplicate vertices var compressedPointers = new NativeArray <int>(vertices.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory); int count = 0; for (int i = 0; i < vertices.Length; i++) { if (!firstVerts.ContainsKey(vertices[i])) { firstVerts.Add(vertices[i], count); compressedPointers[i] = count; outputVertices->Add(vertices[i]); count++; } else { // There are some cases, rare but still there, that vertices are identical compressedPointers[i] = firstVerts[vertices[i]]; } } for (int i = 0; i < triangles.Length; i++) { outputTriangles->Add(compressedPointers[triangles[i]]); } } }
public static unsafe void BuildFromTrace(NativeList <Entry> samplesPerFunction, NativeArray <SampleData> samples, int threadIdx) { samplesPerFunction.Clear(); var functionIndex = new NativeHashMap <int, int>(samplesPerFunction.Length, Allocator.Temp); var samplePtr = (SampleData *)samples.GetUnsafeReadOnlyPtr(); for (int i = 0, n = samples.Length; i < n; i++) { if (samplePtr[i].ThreadIdx != threadIdx) { continue; } if (!functionIndex.TryGetValue(samplePtr[i].Function, out int funcIdx)) { funcIdx = samplesPerFunction.Length; functionIndex.Add(samplePtr[i].Function, funcIdx); samplesPerFunction.Add(new Entry { Function = samplePtr[i].Function }); } var samplesPerFunctionPtr = (Entry *)samplesPerFunction.GetUnsafePtr(); samplesPerFunctionPtr[funcIdx].Samples += 1; } var output = (Entry *)samplesPerFunction.GetUnsafePtr(); NativeSortExtension.Sort(output, samplesPerFunction.Length); }
private static int GetVertId(ref DynamicBuffer <float3> vertices, ref DynamicBuffer <float3> normals, NativeHashMap <float3, int> oldLayerPosIdDict, NativeHashMap <float3, int> newLayerPosIdDict, VertexNormal vertex, float3 topPoint, ref int len) { int vertId; if (oldLayerPosIdDict.TryGetValue(vertex.position, out vertId)) { //vertId = positionIdDict.TryGetValue; } else { vertices.Add(vertex.position); normals.Add(vertex.normal); vertId = len; if (math.any(vertex.position == topPoint)) { oldLayerPosIdDict.Add(vertex.position, vertId); } if (vertex.position.z == topPoint.z) { newLayerPosIdDict.Add(vertex.position, vertId); } len++; } return(vertId); }
//return success or failure public static bool AddPlantItem(PlantItem p, MapType mapType) { int index = GridSystem.GETIndex(p.Pos, mapType); if (mapType == MapType.main) { if (MainMapPlantItems.ContainsKey(index)) { return(false); } MainMapPlantItems.Add(index, p); } else { if (SecondaryMapPlantIems.ContainsKey(index)) { return(false); } SecondaryMapPlantIems.Add(index, p); } GridSystem.UpdateCell(p.Pos, mapType); PlantManager.Instance.AddPlant(p, mapType); return(true); }
protected override void OnCreate() { GraphicsSettings.useScriptableRenderPipelineBatching = true; // Get the main camera mainCam = GameObject.FindObjectOfType <Camera>(); // Load the material terracedTileMaterial = Resources.Load <Material>("TerracedTerrainMaterial"); // The two hashmap that contains tiles entity by their position. tilesA = new NativeHashMap <int3, Entity>(4, Allocator.Persistent); tilesB = new NativeHashMap <int3, Entity>(4, Allocator.Persistent); var t = terrainAmount.x * terrainAmount.y; var c = terrainAmount / 2; // Create terraced tiles for (var i = 0; i < t; i++) { var pos2D = (i.To2D(terrainAmount) - c) * tileAmount; var pos3D = new int3(pos2D.x, 0, pos2D.y); tilesA.Add(pos3D, CreateTerracedTile(pos3D)); } }
private void UpdateConnections() { // Clean up Connections. for (int i = 0; i < connections.Length; i++) { if (!connections[i].IsCreated) { playerInfoByID.Remove(connections[i].InternalId); connections.RemoveAt(i); i--; } } // Accept new Connections. NetworkConnection connection; while ((connection = driver.Accept()) != default) { if (connectionsLength >= maxConnections) { driver.Disconnect(connection); } else { // Send PlayerMessages and a WelcomeMessage to the new connection. var playerInfo = new PlayerInfo { color = Random.ColorHSV(), name = "", }; playerInfoByID.Add(connection.InternalId, playerInfo); for (int i = 0; i < connectionsLength; i++) { var otherConnection = connections[i]; var otherPlayerInfo = playerInfoByID[otherConnection.InternalId]; var newPlayerMessage = new NewPlayerMessage(MessageID.nextID, otherConnection.InternalId, otherPlayerInfo.color, otherPlayerInfo._name); Send(connection, newPlayerMessage); } var welcomeMessage = new WelcomeMessage(MessageID.nextID, connection.InternalId, playerInfo.color); Send(connection, welcomeMessage); connections.AddNoResize(connection); } } }
public void Execute() { var knownChunks = ShadowChunksBySequenceNumber.GetKeyArray(Allocator.Temp); var processedChunks = new NativeHashMap <ulong, byte>(Chunks.Length, Allocator.Temp); for (var index = 0; index < Chunks.Length; index++) { var chunk = Chunks[index].m_Chunk; var archetype = chunk->Archetype; if (!archetype->CompareMask(QueryMask)) // Archetype doesn't match query { continue; } var version = chunk->GetChangeVersion(0); var sequenceNumber = chunk->SequenceNumber; processedChunks[sequenceNumber] = 0; var entityDataPtr = chunk->Buffer + archetype->Offsets[0]; if (ShadowChunksBySequenceNumber.TryGetValue(sequenceNumber, out var shadow)) { if (!ChangeVersionUtility.DidChange(version, shadow.Version)) { continue; } UnsafeUtility.MemCpy(shadow.EntityBuffer, entityDataPtr, chunk->Count * sizeof(Entity)); shadow.Count = chunk->Count; shadow.Version = version; ShadowChunksBySequenceNumber[sequenceNumber] = shadow; } else { ShadowChunksBySequenceNumber.Add(sequenceNumber, AllocatedShadowChunks[index]); } } for (var i = 0; i < knownChunks.Length; i++) { var chunkSequenceNumber = knownChunks[i]; if (!processedChunks.ContainsKey(chunkSequenceNumber)) { // This is a missing chunk var shadowChunk = ShadowChunksBySequenceNumber[chunkSequenceNumber]; // REMOVED COMPONENT DATA! RemovedChunkEntities.AddRange(shadowChunk.EntityBuffer, shadowChunk.Count); UnsafeUtility.Free(shadowChunk.EntityBuffer, Allocator.Persistent); ShadowChunksBySequenceNumber.Remove(chunkSequenceNumber); } } knownChunks.Dispose(); processedChunks.Dispose(); }
public void Execute() { for (int i = 0; i < loaders.Length; i++) { VoxelLoaderData loader = loaders[i]; int3 targetPosition = WorldToChunk(loader.position); int xMin = (loader.singleChunk ? 0 : -loader.chunkDistanceX) + targetPosition.x - 1; int zMin = (loader.singleChunk ? 0 : -loader.chunkDistanceZ) + targetPosition.z - 1; int xMax = (loader.singleChunk ? 1 : loader.chunkDistanceX) + targetPosition.x + 1; int zMax = (loader.singleChunk ? 1 : loader.chunkDistanceZ) + targetPosition.z + 1; for (int x = xMin; x < xMax; x++) { for (int z = zMin; z < zMax; z++) { for (int y = 0; y < maxY; y++) { if ((!infiniteX && (x < worldSizeX.x || x > worldSizeX.y)) || (!infiniteZ && (z < worldSizeZ.x || z > worldSizeZ.y))) { continue; } int3 chunkPosition = new int3(x * chunkSize, y * chunkSize, z * chunkSize); bool shouldRender = false; if (x != xMin && z != zMin && x != xMax - 1 && z != zMax - 1) { shouldRender = true; } if (renderChunks.ContainsKey(chunkPosition)) { if (shouldRender) { ChunkData data = renderChunks[chunkPosition]; data.render = shouldRender; renderChunks[chunkPosition] = data; } continue; } float priority = math.distancesq(chunkPosition, targetPosition); renderChunks.Add(chunkPosition, new ChunkData() { priority = priority, render = shouldRender }); } } } } for (int i = 0; i < loadedChunks.Length; i++) { if (!renderChunks.ContainsKey(loadedChunks[i])) { chunksToRemove.Add(loadedChunks[i]); } } }
public void MarkParentChanged(int instanceId, int parentInstanceId) { if (!ParentChangeInstanceIds.TryAdd(instanceId, parentInstanceId)) { ParentChangeInstanceIds.Remove(instanceId); ParentChangeInstanceIds.Add(instanceId, parentInstanceId); } }
Main(IReadOnlyDictionary <int, int> idIndex, NativeHashMap <int, int> stateLookup, IReadOnlyDictionary <int, Entity> provEntityLookup) { var slicedText = File.ReadLines(Path.Combine(Application.streamingAssetsPath, "map", "region.txt"), Encoding.GetEncoding(1252)); var stateIdNames = new List <string>(); var stateLookupArray = new List <List <int> >(); foreach (var rawLine in slicedText) { if (CommentDetector(rawLine, out var line)) { continue; } var stateProvinces = new List <int>(); var choppedLine = line.Split(new[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries); // 0. StateId = | 1. Prov 1 Prov 2 Prov 3... | 2. #StateName var innerChopped = choppedLine[1].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var colorNum in innerChopped) { if (!int.TryParse(colorNum, out var lookupNum)) { throw new Exception("Invalid province ID. Must be int number."); } var provId = idIndex[lookupNum]; stateLookup.Add(provId, stateIdNames.Count); stateProvinces.Add(provId); } stateLookupArray.Add(stateProvinces); stateIdNames.Add(Regex.Match(choppedLine[0], @"^.+?(?=\=)").Value.Trim()); } // Creating state to prov blob lookup nested array BlobAssetReference <StateToProv> stateToProvReference; using (var stateToProv = new BlobBuilder(Allocator.Temp)) { ref var lookupStruct = ref stateToProv.ConstructRoot <StateToProv>(); var stateArray = stateToProv.Allocate(ref lookupStruct.Lookup, stateLookupArray.Count); for (var state = 0; state < stateLookupArray.Count; state++) { var provArray = stateToProv.Allocate(ref stateArray[state], stateLookupArray[state].Count); for (var i = 0; i < stateLookupArray[state].Count; i++) { provArray[i] = provEntityLookup[stateLookupArray[state][i]]; } } stateToProvReference = stateToProv.CreateBlobAssetReference <StateToProv>(Allocator.Persistent); }
public void TryRemoveComponentsFromTriggers(EntityManager em, Entity detector, int trigger) { var remainTriggersEffects = new NativeHashMap <ComponentType, bool>(); var triggerToRemoveEffects = new NativeList <ComponentType>(Allocator.Temp); if (_detectorTriggers.TryGetValue(detector, out var triggerIds)) { foreach (var triggerId in triggerIds) { if (_triggerInitSystem.ColliderToTriggerEntity.TryGetValue(triggerId, out var entity)) { var components = em.GetComponentTypes(entity); if (trigger == triggerId) { for (var i = 0; i < components.Length; i++) { if (_conversion.ContainsKey(components[i])) { triggerToRemoveEffects.Add(components[i]); } } } else { for (var i = 0; i < components.Length; i++) { if (_conversion.ContainsKey(components[i])) { remainTriggersEffects.Add(components[i], false); } } } components.Dispose(); } } } for (var i = 0; i < triggerToRemoveEffects.Length; i++) { var componentType = triggerToRemoveEffects[i]; if (!remainTriggersEffects.IsCreated || !remainTriggersEffects.ContainsKey(componentType)) { PostUpdateCommands.RemoveComponent(detector, componentType); _entityEffects[detector].Remove(componentType); } } if (remainTriggersEffects.IsCreated) { remainTriggersEffects.Dispose(); } triggerToRemoveEffects.Dispose(); }
public void RegisterRpc(ComponentType type, PortableFunctionPointer <RpcExecutor.ExecuteDelegate> exec) { if (!exec.Ptr.IsCreated) { throw new InvalidOperationException( $"不能注册Rpc类型 {type.GetManagedType()}: Ptr 属性没有创建 (null)" + "Check CompileExecute() and verify you are initializing the PortableFunctionPointer with a valid static function delegate, decorated with [BurstCompile] attribute"); } var hash = TypeManager.GetTypeInfo(type.TypeIndex).StableTypeHash; if (hash == 0) { throw new InvalidOperationException($"Unexpected 0 hash for type {type.GetManagedType()}"); } if (_rpcTypeHashToIndex.TryGetValue(hash, out var index)) { var rpcData = _rpcData[index]; if (rpcData.TypeHash != 0) { #if ENABLE_UNITY_COLLECTIONS_CHECKS if (rpcData.RpcType == type) { throw new InvalidOperationException( String.Format("Registering RPC {0} multiple times is not allowed", type.GetManagedType())); } throw new InvalidOperationException( String.Format("Type hash collision between types {0} and {1}", type.GetManagedType(), rpcData.RpcType.GetManagedType())); #else throw new InvalidOperationException( String.Format("Hash collision or multiple registrations for {0}", type.GetManagedType())); #endif } rpcData.TypeHash = hash; rpcData.Execute = exec; _rpcData[index] = rpcData; } else { _rpcTypeHashToIndex.Add(hash, _rpcData.Length); _rpcData.Add(new RpcData { TypeHash = hash, Execute = exec, #if ENABLE_UNITY_COLLECTIONS_CHECKS RpcType = type #endif }); } // Debug.Log("注册Rpc:" + index + " " + World.Name); }
private void Start() { _map = new NativeHashMap <int3, Hexagon.Hex>(mapSize.x * mapSize.y, Allocator.Persistent); var vertices = new NativeList <float3>(Allocator.Temp); var indices = new NativeList <int>(Allocator.Temp); var uvs = new NativeList <float2>(Allocator.Temp); for (var i = 0; i < mapSize.x * mapSize.y; i++) { var x = i % mapSize.x; var z = i / mapSize.x; var hex = new Hexagon.Hex { Size = size, OffsetCoord = new int2(x, z), }; var vLength = vertices.Length; vertices.Add(hex.WorldCoord); uvs.Add(new float2(0f)); for (var j = 6; j >= 0; j--) { vertices.Add(Hexagon.HexCorner(hex.WorldCoord, hex.Size, j)); uvs.Add(new float2(0f)); } for (var j = 0; j < 6; j++) { var a = (1 + j) % 7; var b = (2 + j) % 7; b = b < 1 ? 1 : b; indices.Add(vLength); indices.Add(vLength + a); indices.Add(vLength + b); } Debug.Log($"Offset : {hex.OffsetCoord}\nCubeCoord : {hex.CubeCoord}\nWorldPosition : {hex.WorldCoord}"); _map.Add(hex.CubeCoord, hex); } _mesh.Clear(); _mesh.SetVertices <float3>(vertices); _mesh.SetIndices <int>(indices, MeshTopology.Triangles, 0); _mesh.SetUVs <float2>(0, uvs); _mesh.RecalculateNormals(); }
/// <summary> /// Invoked for each <see cref="Entity"/> member encountered. /// </summary> /// <param name="property">The property being visited.</param> /// <param name="container">The source container.</param> /// <param name="value">The entity value.</param> /// <typeparam name="TContainer">The container type.</typeparam> /// <returns>The status of the adapter visit.</returns> VisitStatus IVisit <BlobAssetReferenceData> .Visit <TContainer>(Property <TContainer, BlobAssetReferenceData> property, ref TContainer container, ref BlobAssetReferenceData value) { var blobAssetPtr = new SerializeUtility.BlobAssetPtr(value.Header); if (!m_BlobAssetMap.TryGetValue(blobAssetPtr, out _)) { var index = m_BlobAssets.Length; m_BlobAssets.Add(blobAssetPtr); m_BlobAssetMap.Add(blobAssetPtr, index); } return(VisitStatus.Stop); }
public void Execute() { var knownChunks = ShadowChunksBySequenceNumber.GetKeyArray(Allocator.Temp); var processedChunks = new NativeHashMap <ulong, byte>(Chunks.Length, Allocator.Temp); for (var index = 0; index < Chunks.Length; index++) { var chunk = Chunks[index].m_Chunk; var archetype = chunk->Archetype; var indexInTypeArray = ChunkDataUtility.GetIndexInTypeArray(archetype, TypeIndex); if (indexInTypeArray == -1) // Archetype doesn't match required component { continue; } var version = chunk->GetChangeVersion(0); var sequenceNumber = chunk->SequenceNumber; processedChunks[sequenceNumber] = 0; var entityDataPtr = chunk->Buffer + archetype->Offsets[0]; if (ShadowChunksBySequenceNumber.TryGetValue(sequenceNumber, out var shadow)) { if (!ChangeVersionUtility.DidChange(version, shadow.Version)) { continue; } UnsafeUtility.MemCpy(shadow.EntityDataBuffer, entityDataPtr, chunk->Count * sizeof(Entity)); shadow.EntityCount = chunk->Count; shadow.Version = version; ShadowChunksBySequenceNumber[sequenceNumber] = shadow; } else { ShadowChunksBySequenceNumber.Add(sequenceNumber, *(AllocatedShadowChunks + index)); } } for (var i = 0; i < knownChunks.Length; i++) { var chunkSequenceNumber = knownChunks[i]; if (!processedChunks.ContainsKey(chunkSequenceNumber)) { // This is a missing chunk RemovedChunks.Add(chunkSequenceNumber); } } knownChunks.Dispose(); processedChunks.Dispose(); }
public void Execute() { if (RoadEntities.Length == 0) { return; } var visited = new NativeHashMap <IntersectionRoadConnection, bool>(RoadEntities.Length * 2, Allocator.Temp); // Mark all road sides as unvisited for (var i = 0; i < RoadEntities.Length; i++) { var roadEntity = RoadEntities[i]; visited.Add(new IntersectionRoadConnection { Road = roadEntity, Direction = IntersectionRoadDirection.Incoming }, false); visited.Add(new IntersectionRoadConnection { Road = roadEntity, Direction = IntersectionRoadDirection.Outgoing }, false); } // Calculate dead-end road edges first with a depth-first traversal for (var i = 0; i < RoadEntities.Length; i++) { var roadEntity = RoadEntities[i]; var connection = new IntersectionRoadConnection { Road = roadEntity, Direction = IntersectionRoadDirection.Outgoing }; TraverseRoadEdge(connection, visited); connection.Direction = IntersectionRoadDirection.Incoming; TraverseRoadEdge(connection, visited); } }
void NativeHashmapTest() { NativeHashMap <int, float> HashmapData = new NativeHashMap <int, float>(5, Allocator.TempJob); HashmapData.Add(0, 0.1f); HashmapData.Add(1, 0.2f); HashmapData.Add(2, 0.3f); HashmapData.Add(3, 0.4f); HashmapData.Add(4, 0.5f); HashmapData.Add(5, 0.6f); NativeArray <int> HashmapKey = HashmapData.GetKeyArray(Allocator.TempJob); /*for(int i = 0; i < HashmapKey.Length; i++) * { * int Key = HashmapKey[i]; * print(Hashmap[Key]); * }*/ ParallelHashmapJob ParallelJob = new ParallelHashmapJob(); ParallelJob.HashmapKey = HashmapKey; ParallelJob.HashmapData = HashmapData; ParallelJob.Schedule(HashmapKey.Length, 1).Complete(); HashmapData.Dispose(); HashmapKey.Dispose(); }
/// <summary> /// Key: new elements, Value: removed elements /// </summary> public static Vector2Int[] GetNewTilesSafe(List <Vector2Int> originals, Vector2Int[] updaters) { NativeHashMap <int2, int> o = new NativeHashMap <int2, int>(originals.Count, Allocator.TempJob); for (int i = 0; i < originals.Count; i++) { o.Add(new int2(originals[i].x, originals[i].y), 0); } NativeArray <int2> u = new NativeArray <int2>(updaters.Length, Allocator.TempJob); for (int i = 0; i < updaters.Length; i++) { u[i] = new int2(updaters[i].x, updaters[i].y); } NativeArray <int> cindex = new NativeArray <int>(updaters.Length, Allocator.TempJob); NativeArray <int2> na = new NativeArray <int2>(updaters.Length, Allocator.TempJob); SafeDistinctNoRemove j = new SafeDistinctNoRemove { cindex = cindex, original = o, updated = u, newupdated = na }; JobHandle jobhandle = j.Schedule(updaters.Length, updaters.Length / 16); jobhandle.Complete(); List <Vector2Int> newtiles = new List <Vector2Int>(); int2 current; for (int i = 0; i < cindex.Length; i++) { if (cindex[i] == 1) { current = na[i]; newtiles.Add(new Vector2Int(current.x, current.y)); } } cindex.Dispose(jobhandle); o.Dispose(jobhandle); u.Dispose(jobhandle); na.Dispose(jobhandle); //j.newupdated.Dispose(); //j.original.Dispose(); //j.updated.Dispose(); return(newtiles.ToArray()); }
protected override void OnUpdate( ) { NativeArray <Entity> na_netNodes = group_netNodes.ToEntityArray(Allocator.TempJob); if (!isSystemInitialized) { if (na_netNodes.Length == 0) { return; // Early exit. } isSystemInitialized = true; // nhm_entityIndex.Dispose () ; nhm_entityIndex = new NativeHashMap <Entity, int> (na_netNodes.Length, Allocator.Persistent); // Map node entities to hash map. for (int i = 0; i < na_netNodes.Length; i++) { Entity nodeEntity = na_netNodes [i]; nhm_entityIndex.Add(nodeEntity, i); } // for // na_netNodes.Dispose () ; } EntityCommandBuffer.ParallelWriter ecbp = eecb.CreateCommandBuffer().AsParallelWriter(); Dependency = new PathFindingJob() { na_netNodes = na_netNodes, nhm_entityIndex = nhm_entityIndex, a_pathNodesPosition = GetComponentDataFromEntity <Translation> (true), pathNodeLinksBuffer = GetBufferFromEntity <PathNodeLinksBuffer> (true), pathPlannersHandle = GetComponentTypeHandle <PathPlannerComponent> (false), pathNodesBufferHandle = GetBufferTypeHandle <PathNodesBuffer> (false), }.ScheduleParallel(group_pathPlanners, 1, Dependency); Entities .WithName("PathSearchedJob") .WithAll <IsAliveTag, PathPlannerComponent, CanFindPathTag> () .ForEach((Entity entity, int entityInQueryIndex) => { ecbp.RemoveComponent <CanFindPathTag> (entityInQueryIndex, entity); }).Schedule(); eecb.AddJobHandleForProducer(Dependency); na_netNodes.Dispose(Dependency); }
public CapaNativo <T> AgregarAzulejo(T azulejo, Vector3Int posicion) { int p = FuncionesJCC.ObtenerPosicionUnica(mapa.mapaTam.x, mapa.mapaTam.z, posicion); Debug.Log("Posicion Unica:" + p); Debug.Log("Posicion Tile:" + posicion); if (!contenedorAzulejos.ContainsKey(p)) { contenedorAzulejos.Add(p, azulejo); return(this); } return(null); }