public void ExecuteNext(TKey key, TVal value) { keys.Enqueue(key); }
public unsafe void Execute(Entity entity, int index, ref NetworkStreamConnection connection, ref NetworkSnapshotAckComponent snapshotAck) { if (!connection.Value.IsCreated) { return; } DataStreamReader reader; NetworkEvent.Type evt; cmdBuffer[entity].Clear(); snapshotBuffer[entity].Clear(); while ((evt = driver.PopEventForConnection(connection.Value, out reader)) != NetworkEvent.Type.Empty) { switch (evt) { case NetworkEvent.Type.Connect: break; case NetworkEvent.Type.Disconnect: // Flag the connection as lost, it will be deleted in a separate system, giving user code one frame to detect and respond to lost connection commandBuffer.AddComponent(index, entity, new NetworkStreamDisconnected()); rpcBuffer[entity].Clear(); cmdBuffer[entity].Clear(); connection.Value = default(NetworkConnection); if (networkId.Exists(entity)) { freeNetworkIds.Enqueue(networkId[entity].Value); } return; case NetworkEvent.Type.Data: // FIXME: do something with the data var ctx = default(DataStreamReader.Context); switch ((NetworkStreamProtocol)reader.ReadByte(ref ctx)) { case NetworkStreamProtocol.Command: { var buffer = cmdBuffer[entity]; // FIXME: should be handle by a custom command stream system uint snapshot = reader.ReadUInt(ref ctx); uint snapshotMask = reader.ReadUInt(ref ctx); snapshotAck.UpdateReceivedByRemote(snapshot, snapshotMask); uint remoteTime = reader.ReadUInt(ref ctx); uint localTimeMinusRTT = reader.ReadUInt(ref ctx); snapshotAck.UpdateRemoteTime(remoteTime, localTimeMinusRTT, localTime); int headerSize = 1 + 4 * 4; buffer.ResizeUninitialized(reader.Length - headerSize); UnsafeUtility.MemCpy(buffer.GetUnsafePtr(), reader.GetUnsafeReadOnlyPtr() + headerSize, reader.Length - headerSize); break; } case NetworkStreamProtocol.Snapshot: { uint remoteTime = reader.ReadUInt(ref ctx); uint localTimeMinusRTT = reader.ReadUInt(ref ctx); snapshotAck.UpdateRemoteTime(remoteTime, localTimeMinusRTT, localTime); int headerSize = 1 + 4 * 2; var buffer = snapshotBuffer[entity]; buffer.ResizeUninitialized(reader.Length - headerSize); UnsafeUtility.MemCpy(buffer.GetUnsafePtr(), reader.GetUnsafeReadOnlyPtr() + headerSize, reader.Length - headerSize); break; } case NetworkStreamProtocol.Rpc: { var buffer = rpcBuffer[entity]; var oldLen = buffer.Length; buffer.ResizeUninitialized(oldLen + reader.Length - 1); UnsafeUtility.MemCpy(((byte *)buffer.GetUnsafePtr()) + oldLen, reader.GetUnsafeReadOnlyPtr() + 1, reader.Length - 1); break; } default: #if ENABLE_UNITY_COLLECTIONS_CHECKS throw new InvalidOperationException("Received unknown message type"); #else break; #endif } break; default: #if ENABLE_UNITY_COLLECTIONS_CHECKS throw new InvalidOperationException("Received unknown network event " + evt); #else break; #endif } } }
protected override void OnUpdate() { //Create parallel writer NativeQueue <WeaponInfo> .ParallelWriter weaponFiredEvents = weaponFired.AsParallelWriter(); //Create ECB EntityCommandBuffer.Concurrent ecb = entityCommandBuffer.CreateCommandBuffer().ToConcurrent(); //Get all StateData components ComponentDataContainer <StateComponent> states = new ComponentDataContainer <StateComponent> { Components = GetComponentDataFromEntity <StateComponent>() }; ComponentDataContainer <Translation> parentTranslations = new ComponentDataContainer <Translation> { Components = GetComponentDataFromEntity <Translation>() }; float deltaTime = Time.DeltaTime; int boost = GameVariables.Boost; JobHandle gunJob = Entities.ForEach( (Entity e, int entityInQueryIndex, ref GunComponent gun, in LocalToWorld transform, in Parent parent) => { //Make sure SwapDelay < 0 if (gun.SwapTimer > 0) { gun.SwapTimer -= deltaTime; return; } //Make sure gun has a parent if (!states.Components.HasComponent(parent.Value)) { return; } //Make sure parent has a Translation if (!parentTranslations.Components.HasComponent(parent.Value)) { return; } //Variables local to job StateComponent state = states.Components[parent.Value]; Translation position = parentTranslations.Components[parent.Value]; WeaponInfo.WeaponEventType?weaponEventType = null; if (gun.IsReloading) { //Decrease time gun.ReloadTime -= deltaTime; if (!gun.IsReloading) { Reload(ref gun); weaponEventType = WeaponInfo.WeaponEventType.ON_RELOAD; } } //Only if not reloading else if (gun.IsBetweenShot) { //Decrease time gun.BetweenShotTime -= deltaTime; } if (state.CurrentState == State.Reloading) { if (TryReload(ref gun)) { StartReload(ref gun); } } //Should weapon be reloading? //Deactivate this line to block auto reload if (TryStartReload(ref gun)) { StartReload(ref gun); } if (state.CurrentState == State.Attacking) { if (TryShoot(ref gun)) { weaponEventType = WeaponInfo.WeaponEventType.ON_SHOOT; Shoot(entityInQueryIndex, ecb, ref gun, transform, position.Value, boost); } } //Add event to NativeQueue if (weaponEventType != null) { weaponFiredEvents.Enqueue(new WeaponInfo { Parent = parent.Value, WeaponType = gun.WeaponType, EventType = (WeaponInfo.WeaponEventType)weaponEventType, Position = transform.Position, Rotation = transform.Rotation, AmountBulletsInMagazine = gun.CurrentAmountBulletInMagazine }); } }).ScheduleParallel(Dependency);
public void Execute(int index) { queue.Enqueue(array[index]); }
/// <summary> /// Build mesh without generating terrain data /// </summary> public void BuildMesh(NativeQueue <JobHandle> jobHandles) { JobHandle handle = CreateMeshDataJob().Schedule(); jobHandles.Enqueue(handle); }
public unsafe int AppendPacket(NetworkEndPoint address, UdpCHeader header, int dataLen) { int count = 0; switch ((UdpCProtocol)header.Type) { case UdpCProtocol.ConnectionRequest: { if (!Listening) { return(0); } Connection c; if ((c = GetNewConnection(address, header.SessionToken)) == Connection.Null || c.State == NetworkConnection.State.Disconnected) { int id; var sessionId = m_SessionIdCounter[0]; m_SessionIdCounter[0] = (ushort)(m_SessionIdCounter[0] + 1); if (!m_FreeList.TryDequeue(out id)) { id = m_ConnectionList.Length; m_ConnectionList.Add(new Connection { Id = id, Version = 1 }); } int ver = m_ConnectionList[id].Version; c = new Connection { Id = id, Version = ver, ReceiveToken = sessionId, SendToken = header.SessionToken, State = NetworkConnection.State.Connected, Address = address, Attempts = 1, LastAttempt = m_updateTime }; SetConnection(c); m_NetworkAcceptQueue.Enqueue(id); count++; } else { c.Attempts++; c.LastAttempt = m_updateTime; SetConnection(c); } SendPacket(UdpCProtocol.ConnectionAccept, new NetworkConnection { m_NetworkId = c.Id, m_NetworkVersion = c.Version }); } break; case UdpCProtocol.ConnectionReject: { // m_EventQ.Enqueue(Id, (int)NetworkEvent.Connect); } break; case UdpCProtocol.ConnectionAccept: { if (header.Flags != 1) { UnityEngine.Debug.LogError("Accept message received without flag set"); return(0); } Connection c = GetConnection(address, header.SessionToken); if (c != Connection.Null) { c.DidReceiveData = 1; if (c.State == NetworkConnection.State.Connected) { //DebugLog("Dropping connect request for an already connected endpoint [" + address + "]"); return(0); } if (c.State == NetworkConnection.State.Connecting) { var sliceOffset = m_DataStream.Length; m_DataStream.WriteBytesWithUnsafePointer(2); var dataStreamReader = new DataStreamReader(m_DataStream, sliceOffset, 2); var context = default(DataStreamReader.Context); c.SendToken = dataStreamReader.ReadUShort(ref context); m_DataStream.WriteBytesWithUnsafePointer(-2); c.State = NetworkConnection.State.Connected; UpdateConnection(c); AddConnection(c.Id); count++; } } } break; case UdpCProtocol.Disconnect: { Connection c = GetConnection(address, header.SessionToken); if (c != Connection.Null) { if (RemoveConnection(c)) { AddDisconnection(c.Id); } count++; } } break; case UdpCProtocol.Data: { Connection c = GetConnection(address, header.SessionToken); if (c == Connection.Null) { return(0); } c.DidReceiveData = 1; c.LastAttempt = m_updateTime; UpdateConnection(c); var length = dataLen - UdpCHeader.Length; if (c.State == NetworkConnection.State.Connecting) { if (header.Flags != 1) { UnityEngine.Debug.LogError("Received data without connection (no send token)"); return(0); } var tokenOffset = m_DataStream.Length + length - 2; m_DataStream.WriteBytesWithUnsafePointer(length); var dataStreamReader = new DataStreamReader(m_DataStream, tokenOffset, 2); var context = default(DataStreamReader.Context); c.SendToken = dataStreamReader.ReadUShort(ref context); m_DataStream.WriteBytesWithUnsafePointer(-length); c.State = NetworkConnection.State.Connected; UpdateConnection(c); Assert.IsTrue(!Listening); AddConnection(c.Id); count++; } if (header.Flags == 1) { length -= 2; } var sliceOffset = m_DataStream.Length; m_DataStream.WriteBytesWithUnsafePointer(length); m_EventQueue.PushEvent(new NetworkEvent { connectionId = c.Id, type = NetworkEvent.Type.Data, offset = sliceOffset, size = length }); count++; } break; } return(count); }
public JobHandle OnUpdate(JobHandle inputDeps) { if (CrowdController != null) { inputDeps = CrowdController.OnUpdate(AiNavSystem, inputDeps); } if (!Building) { if (TilesSavedStatus[0] == 1) { TilesSavedStatus[0] = 0; OnBuildCompleted?.Invoke(Config.SurfaceId); } if (Builder.HasTilesToBuild) { Watch = System.Diagnostics.Stopwatch.StartNew(); Building = true; Builder.GetDirtyTileBounds(TilesToBuild); Builder.ClearTilesToBuild(); RebuiltTiles.Clear(); UnityEngine.Debug.LogFormat("Building {0} tiles", TilesToBuild.Count); } if (!Building) { HandlesToWaitFor.Clear(); } return(inputDeps); } int status = CurrentTileStatus[0]; // No tiles building if (status == 0) { for (int i = 0; i < Config.BatchSize; i++) { if (TilesToBuild.TryDequeue(out NavMeshTileBounds tileBounds)) { tileBounds.Bounds.min.y = -1024f; tileBounds.Bounds.max.y = 1024f; tileBounds.Bounds.Expand(2f); NavMeshNativeInputBuilder inputBuilder = new NavMeshNativeInputBuilder(tileBounds); if (Config.IncludeUnityPhysicsGeometry) { CollectGeometryJob collectGeometryJob = new CollectGeometryJob { IncludeMask = Config.IncludeMask, BoxFilters = BoxFilters, TileBounds = tileBounds, InputBuilder = inputBuilder, GeometryFilter = Config.GeometryFilter }; inputDeps = collectGeometryJob.ScheduleSingle(AiNavSystem, inputDeps); } CollectFromMeshSourcesJob collectFromMeshSources = new CollectFromMeshSourcesJob { IncludeMask = Config.IncludeMask, MeshSourceMap = MeshSourceMap, TileBounds = tileBounds, InputBuilder = inputBuilder, SharedMeshSources = AiNavSystem.MeshDatas }; inputDeps = collectFromMeshSources.Schedule(inputDeps); CurrentInputBuilders.Add(inputBuilder); CurrentTileStatus[0] = 1; } } if (CurrentInputBuilders.Count == 0) { if (Building) { CurrentTileStatus[0] = 0; if (RebuiltTiles.Count > 0) { var handle = JobHandle.CombineDependencies(HandlesToWaitFor); handle.Complete(); foreach (NavMeshTile rebuiltTile in RebuiltTiles.Values) { Tiles[rebuiltTile.Coord] = rebuiltTile; NavMesh.AddOrReplaceTile(rebuiltTile.Data); } SaveTilesJob saveTilesJob = new SaveTilesJob { TilesSavedStatus = TilesSavedStatus, SurfaceId = Config.SurfaceId, TilesPtr = TilesPtr }; inputDeps = saveTilesJob.Schedule(inputDeps); } Watch.Stop(); UnityEngine.Debug.LogFormat("Build finished in {0} tilecount {1}", Watch.ElapsedMilliseconds, RebuiltTiles.Count); RebuiltTiles.Clear(); Building = false; } } return(inputDeps); } // collection done, build if (status == 1) { foreach (var inputBuilder in CurrentInputBuilders) { if (inputBuilder.Vertices.Length > 0) { BuildInputs.Enqueue(inputBuilder.ToBuildInput()); } } BuildTileJob buildTileJob = new BuildTileJob { AgentSettings = Builder.AgentSettings, BuildSettings = Builder.BuildSettings, BuildInputs = BuildInputs, RebuiltTilesPtr = RebuiltTilesPtr, SurfaceId = Config.SurfaceId }; inputDeps = buildTileJob.Schedule(inputDeps); CurrentTileStatus[0] = 2; return(inputDeps); } // Tile builds finished if (status == 2) { foreach (var inputBuilder in CurrentInputBuilders) { inputBuilder.Dispose(); } CurrentInputBuilders.Clear(); CurrentTileStatus[0] = 0; } return(inputDeps); }
public void TryAdd(Entity entity) { m_Writer.Enqueue(entity); }