public void Commit([CallerMemberName] string member = "", [CallerLineNumber] int line = 0, [CallerFilePath] string file = "") { var profiler = ThreadProfiler; profiler.Stopwatch.Restart(); if (!Paused) { profiler.CommitFrame(); } else { profiler.ClearFrame(); } profiler.ProfileCustomValue("Profiler.Commit", member, line, file, 0, MyTimeSpan.FromMiliseconds(profiler.Stopwatch.ElapsedMilliseconds), null, null); }
private void UnmarkEntityBreakable(bool checkTime) { if (m_markedBreakImpulse != MyTimeSpan.Zero && (!checkTime || MySandboxGame.Static.UpdateTime - m_markedBreakImpulse > MyTimeSpan.FromSeconds(1.5))) { m_markedBreakImpulse = MyTimeSpan.Zero; if (Physics != null && Physics.HavokWorld != null) { Physics.HavokWorld.BreakOffPartsUtil.UnmarkEntityBreakable(Physics.RigidBody); if (checkTime) { CreateEasyPenetrationAction(1f); } } } }
public void ApplyDeltaLinearVelocity(MyTimeSpan timestamp, Vector3 linearVelocityDelta) { int i = 0; while (i < m_history.Count) { if (timestamp <= m_history[i].Timestamp) { var item = m_history[i]; item.Snapshot.LinearVelocity += linearVelocityDelta; m_history[i] = item; } i++; } }
internal void StopShooting(float hitDelaySec) { if (!IsShooting) { return; } m_lastHit = MySandboxGame.Static.UpdateTime; m_hitDelay = MyTimeSpan.FromSeconds(hitDelaySec); m_owner.PlayCharacterAnimation(m_shotHitCondition.Animation, MyBlendOption.Immediate, MyFrameOption.JustFirstFrame, 0.2f, m_shotHitCondition.AnimationTimeScale, false, null, true); m_shotToolAction = null; m_wasShooting = false; }
public void ApplyDeltaPosition(MyTimeSpan timestamp, Vector3D positionDelta) { int i = 0; while (i < m_history.Count) { if (timestamp <= m_history[i].Timestamp) { var item = m_history[i]; item.Snapshot.Position += positionDelta; m_history[i] = item; } i++; } }
public void Read(BitStream stream, MyTimeSpan timeStamp) { var snapshot = new MySnapshot(stream); if (m_entity.Parent == null && m_entity.Physics != null) { if (m_entity.Physics.IsInWorld && m_entity.Physics.RigidBody != null && !m_entity.Physics.RigidBody.IsActive && snapshot.Active) { m_entity.Physics.RigidBody.Activate(); } if (m_entity.Physics.RigidBody == null || m_entity.Physics.RigidBody.IsActive) { m_receivedQueue.Add(snapshot, timeStamp); } } }
unsafe void ControlMessageReceived(byte[] data, int dataSize, ulong sender, MyTimeSpan timestamp, MyTimeSpan receivedTime) { ProfilerShort.Begin("Process control message"); m_controlReceiveStream.Reset(data, dataSize); MyControlMessageEnum msgId = (MyControlMessageEnum)m_controlReceiveStream.ReadUShort(); ITransportCallback handler; if (m_controlMessageHandlers.TryGetValue((int)msgId, out handler)) { handler.Receive(m_controlReceiveStream, sender, MyTimeSpan.Zero); } ProfilerShort.End(); }
protected MyBehaviorTreeState TryReserveAreaAroundEntity([BTParam] string areaName, [BTParam] float radius, [BTParam] int timeMs) { var logic = Bot.HumanoidLogic; MyBehaviorTreeState retStatus = MyBehaviorTreeState.FAILURE; if (logic != null) { switch (logic.ReservationStatus) { case Logic.MyReservationStatus.NONE: logic.ReservationStatus = Logic.MyReservationStatus.WAITING; logic.ReservationAreaData = new MyAiTargetManager.ReservedAreaData() { WorldPosition = Bot.HumanoidEntity.WorldMatrix.Translation, Radius = radius, ReservationTimer = MyTimeSpan.FromMiliseconds(timeMs), ReserverId = new World.MyPlayer.PlayerId(Bot.Player.Id.SteamId, Bot.Player.Id.SerialId) }; MyAiTargetManager.OnAreaReservationResult += AreaReservationHandler; MyAiTargetManager.Static.RequestAreaReservation(areaName, Bot.HumanoidEntity.WorldMatrix.Translation, radius, timeMs, Bot.Player.Id.SerialId); m_reservationTimeOut = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromSeconds(RESERVATION_WAIT_TIMEOUT_SECONDS); logic.ReservationStatus = Logic.MyReservationStatus.WAITING; retStatus = MyBehaviorTreeState.RUNNING; break; case Logic.MyReservationStatus.SUCCESS: retStatus = MyBehaviorTreeState.SUCCESS; break; case Logic.MyReservationStatus.FAILURE: retStatus = MyBehaviorTreeState.FAILURE; break; case Logic.MyReservationStatus.WAITING: if (m_reservationTimeOut < MySandboxGame.Static.UpdateTime) { retStatus = MyBehaviorTreeState.FAILURE; } else { retStatus = MyBehaviorTreeState.RUNNING; } break; } } return(retStatus); }
static void GatherFrame(MyFrameProfiling frame) { QueryDataTimestampDisjoint disjoint = MyImmediateRC.RC.Context.GetData <QueryDataTimestampDisjoint>(frame.m_disjoint.m_query, AsynchronousFlags.DoNotFlush); if (!disjoint.Disjoint) { var freq = disjoint.Frequency; double invFreq = 1.0 / (double)freq; m_timestampStack.Clear(); int stackDepth = 0; while (frame.m_issued.Count > 0) { var q = frame.m_issued.Dequeue(); ulong timestamp; MyImmediateRC.RC.Context.GetData <ulong>(q.m_query, AsynchronousFlags.DoNotFlush, out timestamp); if (q.m_info == MyIssuedQueryEnum.BlockStart) { stackDepth++; MyRender11.GetRenderProfiler().GPU_StartProfilingBlock(q.m_tag); m_timestampStack.Push(timestamp); } else if (q.m_info == MyIssuedQueryEnum.BlockEnd) { stackDepth--; var start = m_timestampStack.Pop(); var time = (timestamp - start) * invFreq; // tick is 100 nanoseconds = 10^-7 second MyRender11.GetRenderProfiler().GPU_EndProfilingBlock(0, MyTimeSpan.FromSeconds(time)); } Debug.Assert(stackDepth >= 0); MyQueryFactory.RelaseTimestampQuery(q.m_query); } Debug.Assert(stackDepth == 0); } frame.Clear(); }
public void TickSync() { if (MyRenderProxy.EnableAppEventsCall) { if ((m_timer.Elapsed - m_appEventsTime).Milliseconds > 10) { #if !XB1 Application.DoEvents(); #endif m_appEventsTime = m_timer.Elapsed; } #if !XB1 Application.DoEvents(); #endif } RenderCallback(); }
public override void SendUpdate() { ProfilerShort.Begin("ClientState.WriteAcks"); // Client ACK Packet - reliable SendStream.ResetWrite(); // ACK Header // Write last state sync packet id SendStream.WriteByte(m_lastStateSyncPacketId); // Write ACKs byte num = (byte)m_acks.Count; SendStream.WriteByte(num); for (int i = 0; i < num; i++) { SendStream.WriteByte(m_acks[i]); } SendStream.Terminate(); m_acks.Clear(); ProfilerShort.End(); m_callback.SendClientAcks(SendStream); // Client Update Packet SendStream.ResetWrite(); m_clientPacketId++; SendStream.WriteByte(m_clientPacketId); SendStream.WriteDouble(MyTimeSpan.FromTicks(Stopwatch.GetTimestamp()).Milliseconds); ProfilerShort.Begin("ClientState.Serialize"); if (VRage.MyCompilationSymbols.EnableNetworkPacketTracking) { Trace.MyTrace.Send(Trace.TraceWindow.MPackets, "Send client update: "); } // Write Client state ClientState.Serialize(SendStream, false); ProfilerShort.End(); SendStream.Terminate(); ProfilerShort.Begin("SendClientUpdate"); m_callback.SendClientUpdate(SendStream); ProfilerShort.End(); //Client.SendMessageToServer(m_sendStream, PacketReliabilityEnum.UNRELIABLE, PacketPriorityEnum.IMMEDIATE_PRIORITY, MyChannelEnum.StateDataSync); }
private void HandleMessage(byte[] data, int dataSize, ulong sender, MyTimeSpan timestamp, MyTimeSpan receivedTime) { if (dataSize < sizeof(byte)) // This would cause crash, message has to contain at least MyMessageId { return; } ProfilerShort.Begin("Handle message"); if (sender != Sync.MyId) { ByteCountReceived += dataSize; } MyMessageId id = (MyMessageId)data[0]; LogStats(ReceiveStats, "", dataSize, 1, P2PMessageEnum.Reliable); m_thisFrameTraffic[(int)id] += dataSize; if (id == MyMessageId.OLD_GAME_EVENT_FLUSH) // Flush buffer { if (m_buffer != null) { m_buffer.Clear(); } } else if (IsBuffering && id != MyMessageId.JOIN_RESULT && id != MyMessageId.WORLD_DATA && id != MyMessageId.WORLD_BATTLE_DATA) // Buffer event { var buff = new Buffer(); buff.Sender = sender; buff.Data = new byte[dataSize]; Array.Copy(data, buff.Data, dataSize); buff.ReceivedTime = MyTimeSpan.FromTicks(Stopwatch.GetTimestamp()); m_buffer.Add(buff); } else // Process event { NetProfiler.Begin("Live data", 0); ProcessMessage(data, dataSize, sender, timestamp, receivedTime); NetProfiler.End(); } ProfilerShort.End(); }
public void ProcessRpc(BitReaderWriter reader) { reader.ReadData(m_sender, false); MyPacket packet; packet.Data = m_sender.ReceiveStream.Data; packet.Sender = MyEventContext.Current.Sender; if (packet.Sender.IsNull) { packet.Sender = new EndpointId(Sync.MyId); } packet.Timestamp = MyTimeSpan.Zero; packet.PayloadOffset = 0; packet.PayloadLength = (int)m_sender.ReceiveStream.Position; packet.ReceivedTime = MyTimeSpan.FromTicks(Stopwatch.GetTimestamp()); TransportLayer.HandleOldGameEvent(packet); }
MyTimeSpan GetPieceAgeLength(MyFracturedPiece piece) { if (piece.Physics == null || piece.Physics.BreakableBody == null) { return(MyTimeSpan.Zero); } if (piece.Physics.RigidBody.Layer == FakePieceLayer) { return(MyTimeSpan.FromSeconds(8 + MyRandom.Instance.NextFloat(0, 4))); } float volume = piece.Physics.BreakableBody.BreakableShape.Volume; float proposedAgeInSecs = volume * LIFE_OF_CUBIC_PIECE; return(MyTimeSpan.FromSeconds(proposedAgeInSecs)); }
void MyEntities_OnEntityAdd(MyEntity obj) { var fp = obj as MyFracturedPiece; if (fp != null) { MyTimeSpan age = GetPieceAgeLength(obj as MyFracturedPiece); m_piecesTimesOfDeath[fp] = MySandboxGame.Static.UpdateTime + age; m_addedThisFrame++; if (!fp.Physics.RigidBody.IsActive) { m_inactivePieces.Add(fp); } fp.Physics.RigidBody.Activated += RigidBody_Activated; fp.Physics.RigidBody.Deactivated += RigidBody_Deactivated; } }
private void ProcessMessage(byte[] data, int dataSize, ulong sender, MyTimeSpan timestamp, MyTimeSpan receivedTime) { Debug.Assert(data.Length >= dataSize, "Wrong size"); MyMessageId id = (MyMessageId)data[0]; if (id == MyMessageId.CLIENT_CONNNECTED) { MyNetworkClient player; if (Sync.Layer != null && Sync.Layer.Clients != null) { bool playerFound = Sync.Layer.Clients.TryGetClient(sender, out player); if (!playerFound) { Sync.Layer.Clients.AddClient(sender); } } } MyPacket p = new MyPacket { Data = data, // First byte is message id PayloadOffset = 1, PayloadLength = dataSize - 1, Sender = new VRage.Network.EndpointId(sender), Timestamp = timestamp, ReceivedTime = receivedTime }; Action <MyPacket> handler; if (m_handlers.TryGetValue(id, out handler)) { ProfilerShort.Begin(MyEnum <MyMessageId> .GetName(id)); NetProfiler.Begin(MyEnum <MyMessageId> .GetName(id)); handler(p); NetProfiler.End(p.PayloadLength); ProfilerShort.End(); } else { Debug.Fail("No handler for message type: " + id); } }
public void Clear() { Lock.Enter(); try { ClearUnsafe(); if (Count > 0) { Count = 0; } LastRefresh = MyTimeSpan.Zero; } finally { Lock.Exit(); } }
protected MyBehaviorTreeState TryReserveAreaAroundEntity([BTParam] string areaName, [BTParam] float radius, [BTParam] int timeMs) { MyHumanoidBotLogic humanoidLogic = this.Bot.HumanoidLogic; MyBehaviorTreeState fAILURE = MyBehaviorTreeState.FAILURE; if (humanoidLogic != null) { switch (humanoidLogic.ReservationStatus) { case MyReservationStatus.NONE: { humanoidLogic.ReservationStatus = MyReservationStatus.WAITING; MyAiTargetManager.ReservedAreaData data = new MyAiTargetManager.ReservedAreaData { WorldPosition = this.Bot.HumanoidEntity.WorldMatrix.Translation, Radius = radius, ReservationTimer = MyTimeSpan.FromMilliseconds((double)timeMs), ReserverId = new MyPlayer.PlayerId(this.Bot.Player.Id.SteamId, this.Bot.Player.Id.SerialId) }; humanoidLogic.ReservationAreaData = data; MyAiTargetManager.OnAreaReservationResult += new Sandbox.Game.AI.MyAiTargetManager.AreaReservationHandler(this.AreaReservationHandler); MyAiTargetManager.Static.RequestAreaReservation(areaName, this.Bot.HumanoidEntity.WorldMatrix.Translation, radius, (long)timeMs, this.Bot.Player.Id.SerialId); this.m_reservationTimeOut = MySandboxGame.Static.TotalTime + MyTimeSpan.FromSeconds(3.0); humanoidLogic.ReservationStatus = MyReservationStatus.WAITING; fAILURE = MyBehaviorTreeState.RUNNING; break; } case MyReservationStatus.WAITING: fAILURE = (this.m_reservationTimeOut >= MySandboxGame.Static.TotalTime) ? MyBehaviorTreeState.RUNNING : MyBehaviorTreeState.FAILURE; break; case MyReservationStatus.SUCCESS: fAILURE = MyBehaviorTreeState.SUCCESS; break; case MyReservationStatus.FAILURE: fAILURE = MyBehaviorTreeState.FAILURE; break; default: break; } } return(fAILURE); }
public void End(bool memoryProfiling, MyTimeSpan?customTime = null) { EndManagedMB = System.GC.GetTotalMemory(false); DeltaManagedB += EndManagedMB - StartManagedMB; if (memoryProfiling) { // TODO: OP! Use better non-alloc call EndProcessMB = System.Environment.WorkingSet; // WorkingSet is allocating memory in each call, also its expensive (about 7ms per 2000 calls). DeltaProcessB += EndProcessMB - StartProcessMB; } // Time stamp at the end, include own overhead long endTimestamp = Stopwatch.GetTimestamp(); ElapsedTimestamp = endTimestamp - MeasureStartTimestamp; Elapsed += customTime ?? new MyTimeSpan(ElapsedTimestamp); }
private void SetHealth(float health) { if (health <= 0) { CurrentState = State.NoBreath; } else if (health < 20) { //play heavy breath indefinitely m_healthOverride = MyTimeSpan.MaxValue; } else if (health < 100) { m_healthOverride = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromSeconds(300 / (health - 19.99)); } Update(true); }
public void ClientUpdate(MyTimeSpan clientTimestamp) { const int ClientUpdateSleepFrames = 6; // Don't sync more often then once per 6 frames (~100 ms) if (m_dirtyProperties.Bits != 0 && MyMultiplayer.Static.FrameCounter - m_lastUpdateFrame >= ClientUpdateSleepFrames) { foreach (var property in m_properties) { if (m_dirtyProperties[property.Id]) { MyMultiplayer.RaiseEvent(this, x => x.SyncPropertyChanged_Implementation, (byte)property.Id, (BitReaderWriter)property); } } m_dirtyProperties.Reset(false); m_lastUpdateFrame = MyMultiplayer.Static.FrameCounter; } }
public bool ShouldPlayVoice(MyPlayer player, MyTimeSpan timestamp, out MySoundDimensions dimension, out float maxDistance) { MyTimeSpan now = MySandboxGame.Static.UpdateTime; double startPlaybackMs = VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * 30 * 1000; if ((now - timestamp).Milliseconds > startPlaybackMs) { dimension = MySoundDimensions.D3; maxDistance = float.MaxValue; return(true); } else { dimension = MySoundDimensions.D2; maxDistance = 0; return(false); } }
public override void ClientUpdate(MyTimeSpan clientTimestamp) { if (IsControlledLocally) { if (Entity.JetpackRunning) { SnapshotSync.Update(clientTimestamp, m_ControlledJetPackSettings); } else { SnapshotSync.Update(clientTimestamp, m_ControlledSettings); } } else { SnapshotSync.Update(clientTimestamp, m_Settings); } }
public void End(bool memoryProfiling, MyTimeSpan?customTime = null) { MyTimeSpan delta = customTime ?? (new MyTimeSpan(Stopwatch.GetTimestamp()) - MeasureStart); Elapsed += delta; if (memoryProfiling) { EndManagedMB = System.GC.GetTotalMemory(false); EndProcessMB = System.Environment.WorkingSet; } DeltaManagedB += EndManagedMB - StartManagedMB; if (memoryProfiling) { DeltaProcessB += EndProcessMB - StartProcessMB; } }
public virtual void Serialize(BitStream stream, EndpointId forClient, MyTimeSpan timeStamp, byte packetId, int maxBitPosition) { //System.Diagnostics.Debug.Assert((m_lastWrittenTimeStamps.ContainsKey(forClient) && m_lastWrittenTimeStamps[forClient] != timeStamp) || !m_lastWrittenTimeStamps.ContainsKey(forClient), "Sending same data twice"); if (stream.Writing) { SnapshotSync.Write(stream); } else { SnapshotSync.Read(stream, timeStamp); } if (stream.BitPosition <= maxBitPosition) { m_lastWrittenTimeStamps[forClient] = timeStamp; } }
public void Serialize(BitStream stream, MyClientInfo forClient, MyTimeSpan serverTimestamp, MyTimeSpan lastClientTimestamp, byte packetId, int maxBitPosition, HashSet <string> cachedData) { var endpoint = forClient.EndpointId; if (!stream.Writing) { return; } if (!_serverData.TryGetValue(endpoint, out var data)) { var bits = new SmallBitField(false); stream.WriteUInt64(bits.Bits, 0); return; } var dirtyProperties = data.DirtyProperties; if (!data.HasRights) { dirtyProperties[VOLUME_PROP_INDEX] = false; } stream.WriteUInt64(dirtyProperties.Bits, m_properties.Count); for (var i = 0; i < m_properties.Count; i++) { if (!dirtyProperties[i]) { continue; } var milliseconds = m_propertyTimestamps[i].Milliseconds; stream.WriteDouble(milliseconds); m_properties[i].Serialize(stream, false); } if (stream.BitPosition <= maxBitPosition) { var dataPerClient = _serverData[endpoint]; dataPerClient.SentProperties[packetId].Bits = dataPerClient.DirtyProperties.Bits; dataPerClient.DirtyProperties.Bits = 0UL; } }
public override void Serialize(BitStream stream, EndpointId forClient, MyTimeSpan timeStamp, byte packetId, int maxBitPosition) { base.Serialize(stream, forClient, timeStamp, packetId, maxBitPosition); if (stream.Writing) { MyCharacterNetState charNetState; Entity.GetNetState(out charNetState); charNetState.Serialize(stream); } else { var charNetState = new MyCharacterNetState(stream); if (!IsControlledLocally) { Entity.SetNetState(ref charNetState, true); } } }
public static void Process(MyTimeSpan lag) { try { foreach (var item in m_channels) { m_tmpList.Add(item.Value); } foreach (var chan in m_tmpList) { chan.Queue.Process(chan.Handler, lag); } } finally { m_tmpList.Clear(); } }
void ITransportCallback.Receive(ByteStream source, ulong sender, MyTimeSpan timestamp) { // TODO: msg pool as member in this class? TMsg msg; try { Serializer.Deserialize(source, out msg); MyTrace.Send(TraceWindow.Multiplayer, "Received: " + msg.ToString(), sender + ", " + source.Position + " B"); } catch (Exception e) { // Catch, add more info (what message) and write to log MySandboxGame.Log.WriteLine(new Exception(String.Format("Error deserializing '{0}', message size '{1}'", typeof(TMsg).Name, source.Length), e)); return; } Handle(ref msg, sender, timestamp); }
public void Update(MyTimeSpan clientTimestamp, MySnapshotSyncSetup setup) { // skip entities with parent if (m_entity.Parent != null) { return; } if (m_entity.Physics == null) //trees { return; } if (m_entity.Physics.RigidBody != null && !m_entity.Physics.RigidBody.IsActive) { return; } VRage.Profiler.ProfilerShort.Begin("Sync Predicted" + m_entity.DisplayName); UpdatePrediction(clientTimestamp, setup); VRage.Profiler.ProfilerShort.End(); }