public void Test() { const string categoryName = "TestCategory"; const string categoryHelp = "Test category help"; const PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.SingleInstance; const string counterName = "TestElapsedTime"; const string counterHelp = "Test elapsed time"; if (!PerformanceCounterCategory.Exists(categoryName)) { var counterCreationData = new CounterCreationDataCollection(ElapsedTime.CounterCreator.CreateCounterData(counterName, counterHelp)); var category = PerformanceCounterCategory.Create(categoryName, categoryHelp, categoryType, counterCreationData); } var elapsedTime = new ElapsedTime(PerformanceCounterFactory.Singleton, categoryName, "TestElapsedTime", false); elapsedTime.Reset(); var count = 0; while (++count < 10) { Thread.Sleep(1000); var value = elapsedTime.NextValue(); Debug.Print("Value = {0}", value); } elapsedTime.Dispose(); PerformanceCounterCategory.Delete(categoryName); }
/// <summary> /// Steps the specified elapsed time. /// </summary> /// <param name="elapsedTime">The elapsed time.</param> public void Step(ElapsedTime elapsedTime) { if (!IsProcessing) return; CurrentAction.Update(elapsedTime); if (!CurrentAction.Done) return; IsProcessing = ActionEnumerator.MoveNext(); if (IsProcessing) CurrentAction = ActionEnumerator.Current; }
public static void Main(string[] args) { // Using delegates write a class Timer that can execute // certain method at each t seconds. int ticksCount = 10; int interval = 1000; ElapsedTime timerElapsedDelegate = new ElapsedTime(PrintElapsedTime); Timer timer = new Timer(ticksCount, interval, timerElapsedDelegate); Console.WriteLine("Timer started for {0} ticks, a tick " + "occurring once every {1} second(s).", ticksCount, interval / 1000); Thread timerThread = new Thread(new ThreadStart(timer.Run)); timerThread.Start(); }
/// <summary> /// Updates the specified elapsed time. /// </summary> /// <param name="elapsedTime">The elapsed time.</param> public override void Update(ElapsedTime elapsedTime) { }
public void Update(ElapsedTime elapsedTime) { var crossings = Spawner.Crossings; // We skip any crossing that we have passed (Travelled + Length / 2) or are too close to stop at (+ Speed * BrakingMinFactor). // We skip any crossing that is part of the same group as the previous. while (NextCrossingIndex < crossings.Count && ((Travelled + Length / 2 + Speed * BrakingMinFactor > crossings[NextCrossingIndex].Distance) || (NextCrossingIndex > 0 && crossings[NextCrossingIndex].Item.CrossingGroup != null && crossings[NextCrossingIndex].Item.CrossingGroup == crossings[NextCrossingIndex - 1].Item.CrossingGroup))) { NextCrossingIndex++; } // Calculate all the distances to items we need to stop at (level crossings, other cars). var stopDistances = new List <float>(); for (var crossing = NextCrossingIndex; crossing < crossings.Count; crossing++) { if (crossings[crossing].Item.CrossingGroup != null && crossings[crossing].Item.CrossingGroup.HasTrain) { // TODO: Stopping distance for level crossings! stopDistances.Add(crossings[crossing].Distance - RoadCarSpawner.StopDistance); break; } } // TODO: Maybe optimise this? var cars = Spawner.Cars; var spawnerIndex = cars.IndexOf(this); if (spawnerIndex > 0) { if (!cars[spawnerIndex - 1].CarriesCamera) { stopDistances.Add(cars[spawnerIndex - 1].Travelled - cars[spawnerIndex - 1].Length / 2); } else { stopDistances.Add(cars[spawnerIndex - 1].Travelled - cars[spawnerIndex - 1].Length * 0.65f - 4 - cars[spawnerIndex - 1].Speed * 0.5f); } } // Calculate whether we're too close to the minimum stopping distance (and need to slow down) or going too slowly (and need to speed up). var stopDistance = stopDistances.Count > 0 ? stopDistances.Min() - Travelled - Length / 2 : float.MaxValue; var slowingDistance = BrakingFactor * Length; if (stopDistance < slowingDistance) { Speed = SpeedMax * (float)Math.Sin((Math.PI / 2) * (stopDistance / slowingDistance)); } else if (Speed < SpeedMax) { Speed = Math.Min(Speed + AccelerationFactor / Length * elapsedTime.ClockSeconds, SpeedMax); } else if (Speed > SpeedMax) { Speed = Math.Max(Speed - AccelerationFactor / Length * elapsedTime.ClockSeconds * 2, SpeedMax); } var distance = elapsedTime.ClockSeconds * Speed; Travelled += distance; FrontTraveller.Move(distance); RearTraveller.Move(distance); }
public void TestElapsedTimeToString() { ElapsedTime p = new ElapsedTime(130); Assert.AreEqual("2:10", p.ToString()); }
/// <summary> /// Updates the specified elapsed time. /// </summary> /// <param name="elapsedTime">The elapsed time.</param> public virtual void Update(ElapsedTime elapsedTime) { foreach (var component in Components) { component.Update(elapsedTime); } }
/// <summary> /// Updates the children. /// </summary> /// <param name="elapsedTime">The elapsed time.</param> protected virtual void UpdateChildren(ElapsedTime elapsedTime) { foreach (IGameComponent child in Children) { child.Update(elapsedTime); } }
public void Update(float currentTime, ElapsedTime elapsedTime) { windDisplacementX = viewer.Simulator.Weather.WindSpeedMpS.X * 0.25f; windDisplacementZ = viewer.Simulator.Weather.WindSpeedMpS.Y * 0.25f; var velocity = WorldPosition.Location - LastWorldPosition.Location; velocity.X += (WorldPosition.TileX - LastWorldPosition.TileX) * 2048; velocity.Z += (WorldPosition.TileZ - LastWorldPosition.TileZ) * 2048; velocity.Z *= -1; velocity /= elapsedTime.ClockSeconds; LastWorldPosition.Location = WorldPosition.Location; LastWorldPosition.TileX = WorldPosition.TileX; LastWorldPosition.TileZ = WorldPosition.TileZ; RetireActiveParticles(currentTime); FreeRetiredParticles(); if (ParticlesPerSecond < 0.1) { TimeParticlesLastEmitted = currentTime; } var numToBeEmitted = (int)((currentTime - TimeParticlesLastEmitted) * ParticlesPerSecond); var numCanBeEmitted = GetCountFreeParticles(); var numToEmit = Math.Min(numToBeEmitted, numCanBeEmitted); if (numToEmit > 0) { var rotation = WorldPosition.XNAMatrix; rotation.Translation = Vector3.Zero; var position = Vector3.Transform(EmitterData.XNALocation, rotation) + WorldPosition.XNAMatrix.Translation; var globalInitialVelocity = Vector3.Transform(XNAInitialVelocity, rotation) + velocity; // TODO: This should only be rotated about the Y axis and not get fully rotated. var globalTargetVelocity = Vector3.Transform(XNATargetVelocity, rotation); var time = TimeParticlesLastEmitted; for (var i = 0; i < numToEmit; i++) { time += 1 / ParticlesPerSecond; var particle = (FirstFreeParticle + 1) % MaxParticles; var vertex = particle * VerticiesPerParticle; var texture = Viewer.Random.Next(16); // Randomizes emissions. var color_Random = new Color(ParticleColor, (float)Viewer.Random.NextDouble()); // Initial velocity varies in X and Z only. var initialVelocity = globalInitialVelocity; initialVelocity.X += (float)(Viewer.Random.NextDouble() - 0.5f) * ParticleEmitterViewer.InitialSpreadRate; initialVelocity.Z += (float)(Viewer.Random.NextDouble() - 0.5f) * ParticleEmitterViewer.InitialSpreadRate; // Target/final velocity vaies in X, Y and Z. var targetVelocity = globalTargetVelocity; targetVelocity.X += Noise.Generate(time + PerlinStart[0]) * ParticleEmitterViewer.SpreadRate; targetVelocity.Y += Noise.Generate(time + PerlinStart[1]) * ParticleEmitterViewer.SpreadRate; targetVelocity.Z += Noise.Generate(time + PerlinStart[2]) * ParticleEmitterViewer.SpreadRate; // Add wind speed targetVelocity.X += windDisplacementX; targetVelocity.Z += windDisplacementZ; // ActionDuration is variable too. var duration = ParticleDuration * (1 + Noise.Generate(time + PerlinStart[3]) * ParticleEmitterViewer.DurationVariation); for (var j = 0; j < VerticiesPerParticle; j++) { Vertices[vertex + j].StartPosition_StartTime = new Vector4(position, time); Vertices[vertex + j].InitialVelocity_EndTime = new Vector4(initialVelocity, time + duration); Vertices[vertex + j].TargetVelocity_TargetTime = new Vector4(targetVelocity, ParticleEmitterViewer.DecelerationTime); Vertices[vertex + j].TileXY_Vertex_ID = new Short4(WorldPosition.TileX, WorldPosition.TileZ, j, texture); Vertices[vertex + j].Color_Random = color_Random; } FirstFreeParticle = particle; } TimeParticlesLastEmitted = time; } }
public override void PrepareFrame(ElapsedTime elapsedTime, bool updateFull) { base.PrepareFrame(elapsedTime, updateFull); if (updateFull) { var primitives = new List <DispatcherPrimitive>(Primitives.Count); foreach (var cache in Cache.Values) { cache.Age++; } foreach (var train in Owner.Viewer.Simulator.Trains) { var position = train.MUDirection != Direction.Reverse ? new Traveller(train.FrontTDBTraveller) : new Traveller(train.RearTDBTraveller, Traveller.TravellerDirection.Backward); var caches = new List <TrackSectionCacheEntry>(); // Work backwards until we end up on a different track section. var cacheNode = new Traveller(position); cacheNode.ReverseDirection(); var initialNodeOffsetCount = 0; while (cacheNode.TrackNodeIndex == position.TrackNodeIndex && cacheNode.NextSection()) { initialNodeOffsetCount++; } // Now do it again, but don't go the last track section (because it is from a different track node). cacheNode = new Traveller(position); cacheNode.ReverseDirection(); for (var i = 1; i < initialNodeOffsetCount; i++) { cacheNode.NextSection(); } // Push the location right up to the end of the section. cacheNode.MoveInSection(MaximumSectionDistance); // Now back facing the right way, calculate the distance to the train location. cacheNode.ReverseDirection(); var initialNodeOffset = cacheNode.DistanceTo(position.TileX, position.TileZ, position.X, position.Y, position.Z); // Go and collect all the cache entries for the visible range of vector nodes (straights, curves). var totalDistance = 0f; while (!cacheNode.IsEnd && totalDistance - initialNodeOffset < DisplayDistance) { if (cacheNode.IsTrack) { var cache = GetCacheEntry(cacheNode); cache.Age = 0; caches.Add(cache); totalDistance += cache.Length; } var nodeIndex = cacheNode.TrackNodeIndex; while (cacheNode.TrackNodeIndex == nodeIndex && cacheNode.NextSection()) { ; } } var switchErrorDistance = initialNodeOffset + DisplayDistance + SignalWarningDistance; var signalErrorDistance = initialNodeOffset + DisplayDistance + SignalWarningDistance; var currentDistance = 0f; foreach (var cache in caches) { foreach (var obj in cache.Objects) { var objDistance = currentDistance + obj.Distance; if (objDistance < initialNodeOffset) { continue; } var switchObj = obj as TrackSectionSwitch; var signalObj = obj as TrackSectionSignal; if (switchObj != null) { for (var pin = switchObj.TrackNode.Inpins; pin < switchObj.TrackNode.Inpins + switchObj.TrackNode.Outpins; pin++) { if (switchObj.TrackNode.TrPins[pin].Link == switchObj.NodeIndex) { if (pin - switchObj.TrackNode.Inpins != switchObj.TrackNode.TrJunctionNode.SelectedRoute) { switchErrorDistance = objDistance; } break; } } if (switchErrorDistance < DisplayDistance) { break; } } else if (signalObj != null) { if (GetAspect(signalObj.Signal) == DebugWindowSignalAspect.Stop) { signalErrorDistance = objDistance; break; } } } if (switchErrorDistance < DisplayDistance || signalErrorDistance < DisplayDistance) { break; } currentDistance += cache.Length; } var currentPosition = new Traveller(position); currentPosition.Move(-initialNodeOffset); currentDistance = 0; foreach (var cache in caches) { var lastObjDistance = 0f; foreach (var obj in cache.Objects) { var objDistance = currentDistance + obj.Distance; for (var step = lastObjDistance; step < obj.Distance; step += DisplaySegmentLength) { var stepDistance = currentDistance + step; var stepLength = DisplaySegmentLength > obj.Distance - step ? obj.Distance - step : DisplaySegmentLength; var previousLocation = currentPosition.WorldLocation; currentPosition.Move(stepLength); if (stepDistance + stepLength >= initialNodeOffset && stepDistance <= initialNodeOffset + DisplayDistance) { primitives.Add(new DispatcherLineSegment(previousLocation, currentPosition.WorldLocation, signalErrorDistance - stepDistance < SignalErrorDistance ? Color.Red : signalErrorDistance - stepDistance < SignalWarningDistance ? Color.Yellow : Color.White, 2)); } } lastObjDistance = obj.Distance; if (objDistance >= switchErrorDistance || objDistance >= signalErrorDistance) { break; } } currentDistance += cache.Length; if (currentDistance >= switchErrorDistance || currentDistance >= signalErrorDistance) { break; } } currentPosition = new Traveller(position); currentPosition.Move(-initialNodeOffset); currentDistance = 0; foreach (var cache in caches) { var lastObjDistance = 0f; foreach (var obj in cache.Objects) { currentPosition.Move(obj.Distance - lastObjDistance); lastObjDistance = obj.Distance; var objDistance = currentDistance + obj.Distance; if (objDistance < initialNodeOffset || objDistance > initialNodeOffset + DisplayDistance) { continue; } var eolObj = obj as TrackSectionEndOfLine; var switchObj = obj as TrackSectionSwitch; var signalObj = obj as TrackSectionSignal; if (eolObj != null) { primitives.Add(new DispatcherLabel(currentPosition.WorldLocation, Color.Red, "End of Line", Owner.TextFontDefaultOutlined)); } else if (switchObj != null) { primitives.Add(new DispatcherLabel(currentPosition.WorldLocation, objDistance >= switchErrorDistance ? Color.Red : Color.White, String.Format("Switch ({0}, {1}-way, {2} set)", switchObj.TrackNode.Index, switchObj.TrackNode.Outpins, switchObj.TrackNode.TrJunctionNode.SelectedRoute + 1), Owner.TextFontDefaultOutlined)); } else if (signalObj != null) { primitives.Add(new DispatcherLabel(currentPosition.WorldLocation, GetAspect(signalObj.Signal) == DebugWindowSignalAspect.Stop ? Color.Red : GetAspect(signalObj.Signal) == DebugWindowSignalAspect.Warning ? Color.Yellow : Color.Green, String.Format("Signal ({0})", signalObj.Signal.this_sig_lr(MstsSignalFunction.NORMAL)), Owner.TextFontDefaultOutlined)); } if (objDistance >= switchErrorDistance || objDistance >= signalErrorDistance) { break; } } currentDistance += cache.Length; if (currentDistance >= switchErrorDistance || currentDistance >= signalErrorDistance) { break; } } } Primitives = primitives; // Clean up any cache entries who haven't been using for 30 seconds. var oldCaches = Cache.Where(kvp => kvp.Value.Age > 30 * 4).ToArray(); foreach (var oldCache in oldCaches) { Cache.Remove(oldCache.Key); } } var labels = new List <Rectangle>(); foreach (var primitive in Primitives) { primitive.PrepareFrame(labels, Viewport, Owner.Viewer.Camera); } }
public override void PrepareFrame(ElapsedTime elapsedTime, bool updateFull) { base.PrepareFrame(elapsedTime, updateFull); if (updateFull) { var primitives = new List <DispatcherPrimitive>(Primitives.Count); var camera = Owner.Viewer.Camera; var tSectionDat = Owner.Viewer.Simulator.TSectionDat; var tdb = Owner.Viewer.Simulator.TDB; var rdb = Owner.Viewer.Simulator.RDB; foreach (var trackNode in tdb.TrackDB.TrackNodes.Where(tn => tn != null && tn.TrVectorNode != null && Math.Abs(tn.TrVectorNode.TrVectorSections[0].TileX - camera.TileX) <= 1 && Math.Abs(tn.TrVectorNode.TrVectorSections[0].TileZ - camera.TileZ) <= 1)) { var currentPosition = new Traveller(tSectionDat, tdb.TrackDB.TrackNodes, trackNode); while (true) { var previousLocation = currentPosition.WorldLocation; var remaining = currentPosition.MoveInSection(DisplaySegmentLength); if ((Math.Abs(remaining - DisplaySegmentLength) < Tolerance) && !currentPosition.NextVectorSection()) { break; } primitives.Add(new DispatcherLineSegment(previousLocation, currentPosition.WorldLocation, Color.LightBlue, 2)); } if (trackNode.TrVectorNode.TrItemRefs != null) { foreach (var trItemID in trackNode.TrVectorNode.TrItemRefs) { var trItem = tdb.TrackDB.TrItemTable[trItemID]; currentPosition = new Traveller(tSectionDat, tdb.TrackDB.TrackNodes, trackNode); currentPosition.Move(trItem.SData1); primitives.Add(new DispatcherLabel(currentPosition.WorldLocation, Color.LightBlue, String.Format("{0} {1} {2}", trItem.TrItemId, trItem.ItemType.ToString().Replace("tr", "").ToUpperInvariant(), trItem.ItemName), Owner.TextFontDefaultOutlined)); } } } if (rdb != null && rdb.RoadTrackDB.TrackNodes != null) { foreach (var trackNode in rdb.RoadTrackDB.TrackNodes.Where(tn => tn != null && tn.TrVectorNode != null && Math.Abs(tn.TrVectorNode.TrVectorSections[0].TileX - camera.TileX) <= 1 && Math.Abs(tn.TrVectorNode.TrVectorSections[0].TileZ - camera.TileZ) <= 1)) { var currentPosition = new Traveller(tSectionDat, rdb.RoadTrackDB.TrackNodes, trackNode); while (true) { var previousLocation = currentPosition.WorldLocation; var remaining = currentPosition.MoveInSection(DisplaySegmentLength); if ((Math.Abs(remaining - DisplaySegmentLength) < Tolerance) && !currentPosition.NextVectorSection()) { break; } primitives.Add(new DispatcherLineSegment(previousLocation, currentPosition.WorldLocation, Color.LightSalmon, 2)); } if (trackNode.TrVectorNode.TrItemRefs != null) { foreach (var trItemID in trackNode.TrVectorNode.TrItemRefs) { var trItem = rdb.RoadTrackDB.TrItemTable[trItemID]; currentPosition = new Traveller(tSectionDat, rdb.RoadTrackDB.TrackNodes, trackNode); currentPosition.Move(trItem.SData1); primitives.Add(new DispatcherLabel(currentPosition.WorldLocation, Color.LightSalmon, String.Format("{0} {1} {2}", trItem.TrItemId, trItem.ItemType.ToString().Replace("tr", "").ToUpperInvariant(), trItem.ItemName), Owner.TextFontDefaultOutlined)); } } } } Primitives = primitives; } var labels = new List <Rectangle>(); foreach (var primitive in Primitives) { primitive.PrepareFrame(labels, Viewport, Owner.Viewer.Camera); } }
public void TheElapsedTimeShouldBeALittleGreaterThanTheTimeout() { ElapsedTime.ShouldBeGreaterThanOrEqualTo(_timeout); ElapsedTime.ShouldBeLessThan(_acceptableTime); }
public virtual void PrepareFrame(ElapsedTime elapsedTime, bool updateFull) { }
public void Update(ElapsedTime elapsedTime) { if (PerformanceTune && Viewer.RenderProcess.IsActive) { // Work out how far we need to change the actual FPS to get to the target. // +ve = under-performing/too much detail // -ve = over-performing/not enough detail var fpsTarget = Viewer.Settings.PerformanceTunerTarget - Viewer.RenderProcess.FrameRate.SmoothedValue; // If vertical sync is on, we're capped to 60 FPS. This means we need to shift a target of 60FPS down to 57FPS. if (Viewer.Settings.VerticalSync && Viewer.Settings.PerformanceTunerTarget > 55) { fpsTarget -= 3; } // Summarise the FPS adjustment to: +1 (add detail), 0 (keep), -1 (remove detail). var fpsChange = fpsTarget <-2.5 ? +1 : fpsTarget> 2.5 ? -1 : 0; // If we're not vertical sync-limited, there's no point calculating the CPU change, just assume adding detail is okay. var cpuTarget = 0f; var cpuChange = 1; if (Viewer.Settings.VerticalSync) { // Work out how much spare CPU we have; the target is 90%. // +ve = under-performing/too much detail // -ve = over-performing/not enough detail var cpuTargetRender = Viewer.RenderProcess.Profiler.Wall.SmoothedValue - 90; var cpuTargetUpdater = Viewer.UpdaterProcess.Profiler.Wall.SmoothedValue - 90; cpuTarget = cpuTargetRender > cpuTargetUpdater ? cpuTargetRender : cpuTargetUpdater; // Summarise the CPS adjustment to: +1 (add detail), 0 (keep), -1 (remove detail). cpuChange = cpuTarget <-2.5 ? +1 : cpuTarget> 2.5 ? -1 : 0; } // Now we adjust the viewing distance to try and balance out the FPS. var oldViewingDistance = Viewer.Settings.ViewingDistance; if (fpsChange < 0) { Viewer.Settings.ViewingDistance -= (int)(fpsTarget - 1.5); } else if (cpuChange < 0) { Viewer.Settings.ViewingDistance -= (int)(cpuTarget - 1.5); } else if (fpsChange > 0 && cpuChange > 0) { Viewer.Settings.ViewingDistance += (int)(-fpsTarget - 1.5); } Viewer.Settings.ViewingDistance = (int)MathHelper.Clamp(Viewer.Settings.ViewingDistance, 500, 10000); Viewer.Settings.LODBias = (int)MathHelper.Clamp(PerformanceInitialLODBias + 100 * ((float)Viewer.Settings.ViewingDistance / PerformanceInitialViewingDistance - 1), -100, 100); // If we've changed the viewing distance, we need to update the camera matricies. if (oldViewingDistance != Viewer.Settings.ViewingDistance) { Viewer.Camera.ScreenChanged(); } // Flag as done, so the next load prep (every 250ms) can trigger us again. PerformanceTune = false; } WeatherControl.Update(elapsedTime); Scenery.Update(elapsedTime); }
public void PrepareFrame(RenderFrame frame, ElapsedTime elapsedTime) { // Adjust dome position so the bottom edge is not visible Vector3 ViewerXNAPosition = new Vector3(Viewer.Camera.Location.X, Viewer.Camera.Location.Y - 100, -Viewer.Camera.Location.Z); Matrix XNASkyWorldLocation = Matrix.CreateTranslation(ViewerXNAPosition); if (worldLoc == null) { // First time around, initialize the following items: worldLoc = new WorldLatLon(); oldClockTime = Viewer.Simulator.ClockTime % 86400; while (oldClockTime < 0) { oldClockTime += 86400; } step1 = step2 = (int)(oldClockTime / 1200); step2 = step2 < maxSteps - 1 ? step2 + 1 : 0; // limit to max. steps in case activity starts near midnight // Get the current latitude and longitude coordinates worldLoc.ConvertWTC(Viewer.Camera.TileX, Viewer.Camera.TileZ, Viewer.Camera.Location, ref latitude, ref longitude); if (seasonType != (int)Viewer.Simulator.Season) { seasonType = (int)Viewer.Simulator.Season; date.ordinalDate = latitude >= 0 ? 82 + seasonType * 91 : (82 + (seasonType + 2) * 91) % 365; // TODO: Set the following three externally from ORTS route files (future) date.month = 1 + date.ordinalDate / 30; date.day = 21; date.year = 2017; } // Fill in the sun- and moon-position lookup tables for (int i = 0; i < maxSteps; i++) { solarPosArray[i] = SunMoonPos.SolarAngle(latitude, longitude, ((float)i / maxSteps), date); lunarPosArray[i] = SunMoonPos.LunarAngle(latitude, longitude, ((float)i / maxSteps), date); } // Phase of the moon is generated at random moonPhase = Viewer.Random.Next(8); if (moonPhase == 6 && date.ordinalDate > 45 && date.ordinalDate < 330) { moonPhase = 3; // Moon dog only occurs in winter } } // Current solar and lunar position are calculated by interpolation in the lookup arrays. // Using the Lerp() function, so need to calculate the in-between differential float diff = (float)(Viewer.Simulator.ClockTime - oldClockTime) / 1200; // The rest of this increments/decrements the array indices and checks for overshoot/undershoot. while (Viewer.Simulator.ClockTime >= (oldClockTime + 1200)) // Plus key, or normal forward in time; <CSComment> better so in case of fast forward { step1++; step2++; oldClockTime = oldClockTime + 1200; diff = (float)(Viewer.Simulator.ClockTime - oldClockTime) / 1200; if (step2 >= maxSteps) // Midnight. { step2 = 0; } if (step1 >= maxSteps) // Midnight. { step1 = 0; } } if (Viewer.Simulator.ClockTime <= (oldClockTime - 1200)) // Minus key { step1--; step2--; oldClockTime = Viewer.Simulator.ClockTime; diff = 0; if (step1 < 0) // Midnight. { step1 = maxSteps - 1; } if (step2 < 0) // Midnight. { step2 = maxSteps - 1; } } solarDirection.X = MathHelper.Lerp(solarPosArray[step1].X, solarPosArray[step2].X, diff); solarDirection.Y = MathHelper.Lerp(solarPosArray[step1].Y, solarPosArray[step2].Y, diff); solarDirection.Z = MathHelper.Lerp(solarPosArray[step1].Z, solarPosArray[step2].Z, diff); lunarDirection.X = MathHelper.Lerp(lunarPosArray[step1].X, lunarPosArray[step2].X, diff); lunarDirection.Y = MathHelper.Lerp(lunarPosArray[step1].Y, lunarPosArray[step2].Y, diff); lunarDirection.Z = MathHelper.Lerp(lunarPosArray[step1].Z, lunarPosArray[step2].Z, diff); frame.AddPrimitive(Material, Primitive, RenderPrimitiveGroup.Sky, ref XNASkyWorldLocation); }
/// <summary> /// Updates the specified game time. /// </summary> /// <param name="elapsedTime">The game time.</param> public virtual void Update(ElapsedTime elapsedTime) { UpdateSelf(elapsedTime); UpdateChildren(elapsedTime); }
/// <summary> /// Updates the self. /// </summary> /// <param name="elapsedTime">The elapsed time.</param> protected virtual void UpdateSelf(ElapsedTime elapsedTime) { if (ActionProcessor == null) ActionProcessor = new ActionProcessor(UpdateBySteps()); ElapsedTime = elapsedTime; ActionProcessor.Step(elapsedTime); if (ActionProcessor.IsProcessing) return; if (RepeatUpdateSteps) ActionProcessor.Reset(); }
public override void PrepareFrame(ElapsedTime elapsedTime, bool updateFull) { base.PrepareFrame(elapsedTime, updateFull); if (updateFull) { var act = Owner.Viewer.Simulator.ActivityRun; if (act != null) { var e = Activity.ReopenActivityWindow ? Activity.LastTriggeredEvent : Activity.TriggeredEvent; if (e != null) { if (Activity.IsComplete) { if (Owner.Viewer.Settings.DebriefActivityEval && !Owner.Viewer.HelpWindow.Visible) {//Show evaluation info. Owner.Viewer.HelpWindow.Visible = false; //TO DO: Change next lines to one line. Owner.Viewer.HelpWindow.TabAction(); Owner.Viewer.HelpWindow.TabAction(); Owner.Viewer.HelpWindow.TabAction(); Owner.Viewer.HelpWindow.TabAction(); } Visible = Activity.IsActivityWindowOpen = Owner.Viewer.HelpWindow.ActivityUpdated = Owner.Viewer.Simulator.Paused = true; ComposeMenu(e.ParsedObject.Name, Viewer.Catalog.GetStringFmt("This activity has ended {0}.\nFor a detailed evaluation, see the Help Window (F1).", Activity.IsSuccessful ? Viewer.Catalog.GetString("") : Viewer.Catalog.GetString("without success"))); EndMenu(); } else { var text = e.ParsedObject.Outcomes.DisplayMessage; if (!String.IsNullOrEmpty(text)) { if (Activity.ReopenActivityWindow) { ComposeMenu(e.ParsedObject.Name, text); if (Activity.IsActivityResumed) { ResumeActivity(); CloseMenu(); } else { Owner.Viewer.Simulator.Paused = true; ResumeMenu(); PopupTime = DateTime.Now; } Visible = Owner.Viewer.HelpWindow.ActivityUpdated = true; } else { // Only needs updating the first time through if (!Owner.Viewer.Simulator.Paused && Visible == false) { Owner.Viewer.Simulator.Paused = e.ParsedObject.ORTSContinue < 0 ? true : false; if (e.ParsedObject.ORTSContinue != 0) { ComposeMenu(e.ParsedObject.Name, text); if (e.ParsedObject.ORTSContinue < 0) { ResumeMenu(); } else { NoPauseMenu(); } } PopupTime = DateTime.Now; Visible = Owner.Viewer.HelpWindow.ActivityUpdated = true; } } } else { // Cancel the event as pop-up not needed. Activity.TriggeredEvent = null; } TimeSpan diff1 = DateTime.Now - PopupTime; if (Visible && e.ParsedObject.ORTSContinue >= 0 && diff1.TotalSeconds >= e.ParsedObject.ORTSContinue && !Owner.Viewer.Simulator.Paused) { CloseBox(); } } } else if (Activity.NewMsgFromNewPlayer) { // Displays messages related to actual player train, when not coincident with initial player train var text = Activity.MsgFromNewPlayer; if (!String.IsNullOrEmpty(text)) { if (Activity.ReopenActivityWindow) { ComposeActualPlayerTrainMenu(Owner.Viewer.PlayerTrain.Name, text); if (Activity.IsActivityResumed) { ResumeActivity(); CloseMenu(); } else { Owner.Viewer.Simulator.Paused = true; ResumeMenu(); PopupTime = DateTime.Now; } } else { // Only needs updating the first time through if (!Owner.Viewer.Simulator.Paused && Visible == false) { ComposeActualPlayerTrainMenu(Owner.Viewer.PlayerTrain.Name, text); NoPauseMenu(); PopupTime = DateTime.Now; } else if (Owner.Viewer.Simulator.Paused) { ResumeMenu(); } } Visible = true; } else { Activity.NewMsgFromNewPlayer = false; } TimeSpan diff1 = DateTime.Now - PopupTime; if (Visible && diff1.TotalSeconds >= 10 && !Owner.Viewer.Simulator.Paused) { CloseBox(); Activity.NewMsgFromNewPlayer = false; } } Activity.IsActivityResumed = !Owner.Viewer.Simulator.Paused; Activity.IsActivityWindowOpen = Visible; Activity.ReopenActivityWindow = false; } } }
/// <summary> /// Updates the specified elapsed time. /// </summary> /// <param name="elapsedTime">The elapsed time.</param> public override void Update(ElapsedTime elapsedTime) { Counter += elapsedTime.Elapsed.TotalMilliseconds; }
/// <summary> /// Updates an animated part that toggles between two states (e.g. pantograph, doors, mirrors). /// </summary> public void UpdateState(bool state, ElapsedTime elapsedTime) { SetFrameClamp(AnimationKey + (state ? 1 : -1) * elapsedTime.ClockSeconds); }
public Timer(int ticksCount, int interval, ElapsedTime callback) { this.TicksCount = ticksCount; this.Interval = interval; this.callback = callback; }
/// <summary> /// A keyboard or mouse click has occured. Read the UserInput /// structure to determine what was pressed. /// </summary> public override void HandleUserInput(ElapsedTime elapsedTime) { base.HandleUserInput(elapsedTime); }
public Time(ElapsedTime elapsed) { this.elapsed = elapsed; SetFpsTo60InitiallyAndSetUsefulInitialValues(); }
/// <summary> /// Updates the specified elapsed time. /// </summary> /// <param name="elapsedTime">The elapsed time.</param> public abstract void Update(ElapsedTime elapsedTime);
public void TestStringToElapsedTime() { ElapsedTime p = new ElapsedTime(); p.FromString("2:10"); Assert.AreEqual(130, p.Value); }
public void PrepareFrame(RenderFrame frame, ElapsedTime elapsedTime, Matrix xnaTileTranslation) { var initialise = DisplayState == -1; if (DisplayState != SignalHead.draw_state) { #if DEBUG_SIGNAL_SHAPES Console.WriteLine("{5} {0} signal {1} unit {2} state: {3} --> {4}", SignalShape.Location, SignalShape.UID, Index, DisplayState, SignalHead.draw_state, InfoDisplay.FormattedTime(Viewer.Simulator.ClockTime)); #endif DisplayState = SignalHead.draw_state; if (SignalTypeData.DrawAspects.ContainsKey(DisplayState)) { SemaphoreTarget = SignalTypeData.DrawAspects[DisplayState].SemaphorePos; SemaphoreSpeed = SignalTypeData.SemaphoreAnimationTime <= 0 ? 0 : (SemaphoreTarget > SemaphorePos ? +1 : -1) / SignalTypeData.SemaphoreAnimationTime; if (Sound != null) { Sound.HandleEvent(Event.SemaphoreArm); } } } CumulativeTime += elapsedTime.ClockSeconds; while (CumulativeTime > SignalTypeData.FlashTimeTotal) { CumulativeTime -= SignalTypeData.FlashTimeTotal; } if (DisplayState < 0 || !SignalTypeData.DrawAspects.ContainsKey(DisplayState)) { return; } if (SignalTypeData.Semaphore) { // We reset the animation matrix before preparing the lights, because they need to be positioned // based on the original matrix only. foreach (AnimatedPart SemaphorePart in SemaphoreParts) { SemaphorePart.SetFrameWrap(0); } } for (var i = 0; i < SignalTypeData.Lights.Count; i++) { if (SemaphorePos != SemaphoreTarget && SignalTypeData.LightsSemaphoreChange[i]) { continue; } if (!SignalTypeData.DrawAspects[DisplayState].DrawLights[i]) { continue; } if (SignalTypeData.DrawAspects[DisplayState].FlashLights[i] && (CumulativeTime > SignalTypeData.FlashTimeOn)) { continue; } bool isDay; if (Viewer.Settings.UseMSTSEnv == false) { isDay = Viewer.World.Sky.solarDirection.Y > 0; } else { isDay = Viewer.World.MSTSSky.mstsskysolarDirection.Y > 0; } bool isPoorVisibility = Viewer.Simulator.Weather.FogDistance < 200; if (!SignalTypeData.DayLight && isDay && !isPoorVisibility) { continue; } var xnaMatrix = Matrix.CreateTranslation(SignalTypeData.Lights[i].Position); foreach (int MatrixIndex in MatrixIndices) { Matrix.Multiply(ref xnaMatrix, ref SignalShape.XNAMatrices[MatrixIndex], out xnaMatrix); } Matrix.Multiply(ref xnaMatrix, ref xnaTileTranslation, out xnaMatrix); frame.AddPrimitive(SignalTypeData.Material, SignalTypeData.Lights[i], RenderPrimitiveGroup.Lights, ref xnaMatrix); if (Viewer.Settings.SignalLightGlow) { frame.AddPrimitive(SignalTypeData.GlowMaterial, SignalTypeData.Lights[i], RenderPrimitiveGroup.Lights, ref xnaMatrix); } } if (SignalTypeData.Semaphore) { // Now we update and re-animate the semaphore arm. if (SignalTypeData.SemaphoreAnimationTime <= 0 || initialise) { // No timing (so instant switch) or we're initialising. SemaphorePos = SemaphoreTarget; SemaphoreSpeed = 0; } else { // Animate slowly to target position. SemaphorePos += SemaphoreSpeed * elapsedTime.ClockSeconds; if (SemaphorePos * Math.Sign(SemaphoreSpeed) > SemaphoreTarget * Math.Sign(SemaphoreSpeed)) { SemaphorePos = SemaphoreTarget; SemaphoreSpeed = 0; } } foreach (AnimatedPart SemaphorePart in SemaphoreParts) { SemaphorePart.SetFrameCycle(SemaphorePos); } } }