public void SendScenarioState(Player player) { ScenarioState scenarioState = new ScenarioState(); BuildScenarioState(scenarioState); player.SendPacket(scenarioState); }
/// <summary> /// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the /// passed in state value. Handles failures and resets the state if necessary. /// </summary> /// <param name="newState">State to switch to</param> private async void ChangeScenarioState(ScenarioState newState) { // Disable UI while state change is in progress this.CameraStreamingButton.IsEnabled = false; switch (newState) { case ScenarioState.Idle: this.ShutdownWebCam(); this.VisualizationCanvas.Children.Clear(); this.CameraStreamingButton.Content = "Start Streaming"; this.currentState = newState; break; case ScenarioState.Streaming: if (!await this.StartWebcamStreaming()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.VisualizationCanvas.Children.Clear(); this.CameraStreamingButton.Content = "Stop Streaming"; this.currentState = newState; this.CameraStreamingButton.IsEnabled = true; break; } }
public void StartReplay(string replayPath, bool loop) { simEngine.StartReplay(replayPath, loop, 1.0); replayState = ScenarioState.RUNNING; SendServerStateEvent("LOADING_REPLAY", replayPath); }
static ScenarioState RandomizeEntityStartingCoordinates(ScenarioState state, List <EntityData> entities, int boardWidth, Tile playerTile, GameBoard board) { for (int i = 0; i < entities.Count; i++) { EntityData entity = entities[i]; int entityRange = entity.attackCard.range; int minimumRange = entityRange + 1; int maximumRange = entityRange + 3; Tile entityTile = board.GetTileAtPosition(entity.Position); // Upper bound is exclusive. int spawnRange = GenerateSpawnRange(minimumRange, maximumRange + 1); List <Tile> possibleSpawnTiles = playerTile.GetAllTilesAtDistance(spawnRange); Tile spawnTile = possibleSpawnTiles.GetAndRemoveRandomElement(); while (playerTile == spawnTile || entities.Any(e => e.Position == spawnTile.Position)) { if (possibleSpawnTiles.Count == 0) { spawnRange++; possibleSpawnTiles = playerTile.GetAllTilesAtDistance(spawnRange); } spawnTile = playerTile.GetAllTilesAtDistance(spawnRange).GetRandomElement(); } entities[i].SetPosition(spawnTile.Position, state); } return(state); }
/// <summary> /// Initializes a new instance of the <see cref="DetectFacesInWebcam"/> class. /// </summary> public DetectFacesInWebcam() { this.InitializeComponent(); this.currentState = ScenarioState.Idle; App.Current.Suspending += this.OnSuspending; }
public static ScenarioState CollectItem(this ScenarioState state, ItemData item, EntityData collector) { switch (item.itemCategory) { case ItemCategory.Treasure: if (collector != state.player) { break; } TreasureData treasure = item as TreasureData; state.inventory.gold += treasure.value; state.items.Remove(item); break; case ItemCategory.Trap: TrapData trap = item as TrapData; ApplyTrapToEntity(state, trap, collector); break; case ItemCategory.Artifact: if (collector != state.player) { break; } state.inventory.artifacts++; state.items.Remove(item); break; default: break; } return(state); }
public void SimControlPauseScenario() { if (scenarioState != ScenarioState.STOPPED) { if (scenarioState == ScenarioState.PAUSED) {//un-pause scenarioState = ScenarioState.RUNNING; simEngine.Resume(); } else {//pause scenarioState = ScenarioState.PAUSED; simEngine.Pause(); } } if (replayState != ScenarioState.STOPPED) { if (replayState == ScenarioState.PAUSED) {//un-pause replayState = ScenarioState.RUNNING; simEngine.Resume(); } else {//pause replayState = ScenarioState.PAUSED; simEngine.Pause(); } } }
public void DrawUpcomingStates(ScenarioState currentState, List <ProjectedGameState> upcomingStates) { Clear(); drawingSelectedEntity = true; EntityData lastActiveEntity = null; for (int i = 0; i < upcomingStates.Count; i++) { ProjectedGameState projectedState = upcomingStates[i]; if (projectedState.IsDummyState) { continue; } ProjectedGameState nextState = i == upcomingStates.Count - 1 ? null : upcomingStates[i + 1]; DrawState(projectedState, nextState, lastActiveEntity); lastActiveEntity = projectedState.activeEntity; } DrawItemDurations(currentState.items); DrawEntityHealths(currentState.GetAllEntities()); }
private void SetupCountdownLogic() { PlayerInfoHandler.sharedInstance.GetInventoryService().DisableWeapon(); scenarioTimer.onStartTimer.AddListener(PlayerInfoHandler.sharedInstance.GetInventoryService().EnableWeapon); scenarioTimer.onStartTimer.AddListener(() => { _scenarioState = ScenarioState.Playing; }); scenarioTimer.onStartTimer.AddListener(onScenarioStarted.Invoke); }
static ProjectedGameState GetNextGameStateFromAction(ScenarioState lastState, EntityData entity, Action action) { ScenarioState newState = lastState.DeepCopy(); newState.lastGameState = lastState; EntityData entityCopy = newState.GetAllEntities().Find(e => entity.ID == e.ID); // TODO: This is pretty bare-bones right now because it isn't clear how other card categories will be // implemented--need to get it more set up once the basic structure of the state list is running. switch (action.card.category) { case CardCategory.Movement: return(GetNextGameStateFromMove(newState, entityCopy, action.direction)); case CardCategory.Attack: return(GetNextStateFromAction_Attack(newState, entityCopy, action)); case CardCategory.Self: return(GetNextStateFromAction_Self(newState, entityCopy, action)); default: return(GetNextGameStateFromMove(newState, entityCopy, action.direction)); } }
public FaceTrackerProxy(Canvas canvas, MainPage page, CaptureElement capture, MediaCapture mediacapture) { if (this.faceTracker == null) { this.faceTracker = FaceTracker.CreateAsync().AsTask().Result; } rootPage = page; VisualizationCanvas = canvas; this.VisualizationCanvas.Children.Clear(); mediaCapture = mediacapture; var deviceController = mediaCapture.VideoDeviceController; this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; currentState = ScenarioState.Streaming; // Ensure the Semaphore is in the signalled state. this.frameProcessingSemaphore.Release(); // Use a 66 milisecond interval for our timer, i.e. 15 frames per second TimeSpan timerInterval = TimeSpan.FromMilliseconds(200); this.frameProcessingTimer = Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(new Windows.System.Threading.TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval); }
void BuildScenarioState(ScenarioState scenarioState) { scenarioState.ScenarioID = (int)_data.Entry.Id; ScenarioStepRecord step = GetStep(); if (step != null) { scenarioState.CurrentStep = (int)step.Id; } scenarioState.CriteriaProgress = GetCriteriasProgress(); scenarioState.BonusObjectives = GetBonusObjectivesData(); // Don't know exactly what this is for, but seems to contain list of scenario steps that we're either on or that are completed foreach (var state in _stepStates) { if (state.Key.IsBonusObjective()) { continue; } switch (state.Value) { case ScenarioStepState.InProgress: case ScenarioStepState.Done: break; case ScenarioStepState.NotStarted: default: continue; } scenarioState.PickedSteps.Add(state.Key.Id); } scenarioState.ScenarioComplete = IsComplete(); }
static ProjectedGameState GetNextGameStateFromMove(ScenarioState lastState, EntityData entity, Direction move) { ScenarioState newState = lastState.DeepCopy(); newState.lastGameState = lastState; EntityData entityCopy = newState.GetAllEntities().Find(e => entity.ID == e.ID); Tile currentEntityTile = BoardController.CurrentBoard.GetTileAtPosition(entityCopy.Position); Action stateAction = new Action(GenericMovementCard, entity, move, 1); // If entity can't move that direction, return state as-is. if (!currentEntityTile.ConnectsToNeighbor(move)) { return(new ProjectedGameState(entityCopy, newState, stateAction)); } Tile nextTile = currentEntityTile.GetDirectionalNeighbor(move); // If tile is empty, move entity there and return. if (!newState.IsTileOccupied(nextTile)) { entityCopy.SetPosition(nextTile.Position, newState); return(new ProjectedGameState(entityCopy, newState, stateAction)); } EntityData tileOccupant = newState.GetTileOccupant(nextTile.Position); ResolveBump(entity, tileOccupant, move, newState); Bump bump = new Bump(entityCopy, tileOccupant); return(new ProjectedGameState(entityCopy, newState, stateAction, bump)); }
/// <summary> /// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the /// passed in state value. Handles failures and resets the state if necessary. /// </summary> /// <param name="newState">State to switch to</param> private async void ChangeScenarioState(ScenarioState newState) { switch (newState) { case ScenarioState.Idle: this.ShutdownWebCam(); this.VisualizationCanvas.Children.Clear(); this.CameraStreamingButton.Content = "Start Streaming"; this.currentState = newState; break; case ScenarioState.Streaming: if (!await this.StartWebcamStreaming()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.VisualizationCanvas.Children.Clear(); this.CameraStreamingButton.Content = "Stop Streaming"; this.currentState = newState; break; } }
private async void ChangeScenarioState(ScenarioState newState) { // Disable UI while state change is in progress switch (newState) { case ScenarioState.Idle: this.ShutdownWebCam(); this.VisualizationCanvas.Children.Clear(); this.currentState = newState; break; case ScenarioState.Streaming: if (!await this.StartWebcamStreaming()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.VisualizationCanvas.Children.Clear(); this.currentState = newState; break; } }
private async void ChangeScenarioState(ScenarioState newState) { switch (newState) { case ScenarioState.Idle: this.ShutdownWebCam(); btnTomarFoto.IsEnabled = false; this.VisualizationCanvas.Children.Clear(); this.currentState = newState; break; case ScenarioState.Streaming: btnTomarFoto.IsEnabled = true; if (!await this.StartWebcamStreaming()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.VisualizationCanvas.Children.Clear(); this.currentState = newState; break; } }
private void StopReplay() { simEngine.StopReplay(); scenarioState = ScenarioState.STOPPED; replayState = ScenarioState.STOPPED; isReady = false; }
public static void UpdateStagnation(this ScenarioState state, GameBoard board) { if (state.isBossScenario) { return; } switch (state.stagnationState) { case StagnationStates.Dormant: state.stagnationState = StagnationStates.Threatening; break; case StagnationStates.Threatening: state.ThreatenNewPositions(board); state.stagnationState = StagnationStates.Moving; break; case StagnationStates.Moving: state.stagnatedPositions.AddRange(state.threatenedStagnationPositions); state.threatenedStagnationPositions.Clear(); state.stagnationState = StagnationStates.Threatening; break; default: break; } }
/// <summary> /// Initializes a new instance of the <see cref="TrackFacesInWebcam"/> class. /// </summary> public TrackFacesInWebcam() { this.InitializeComponent(); this.currentState = ScenarioState.Idle; App.Current.Suspending += this.OnSuspending; }
public void DrawBoard(ScenarioState currentGameState, bool isResolvingTurn) { ClearBoard(); // Draw current player at position. DrawEntityAtPosition(currentGameState.player, opaque); // Draw current enemies at positions. for (int i = 0; i < currentGameState.enemies.Count; i++) { EntityData entity = currentGameState.enemies[i]; if (entity != null) { DrawEntityAtPosition(entity, opaque); } } for (int i = 0; i < currentGameState.items.Count; i++) { ItemData item = currentGameState.items[i]; if (item != null) { DrawItemAtPosition(item, opaque); } } }
public ScenarioState finishState(ScenarioState next) { SwipeState swipeState = new SwipeState(this); // make sure these are the same type if (next.GetType().Equals(this.GetType())) { // make sure this is not state if (!this.isSameState(next)) { SwipeState nextState = (SwipeState)next; // make gualState's start be the earlier of the two if (nextState._start.CompareTo(swipeState._start) < 0) { swipeState._start = nextState._start; } // make gualState's start be the later of the two if (nextState._end.CompareTo(swipeState._end) > 0) { swipeState._end = nextState._end; } if (this.Pos.Equals(SwipePosition.START) && nextState.Pos.Equals(SwipePosition.MOVING)) { // if going from start state to moving state // make the capped start state have the same location as moving state swipeState._loc = nextState._loc; } } } return swipeState; }
public static bool IsTileOccupied(this ScenarioState state, Vector2Int originPosition, Direction directionFromOrigin, int distanceFromOrigin) { Vector2Int updatedPosition = originPosition; switch (directionFromOrigin) { case Direction.Up: updatedPosition.y -= distanceFromOrigin; break; case Direction.Down: updatedPosition.y += distanceFromOrigin; break; case Direction.Left: updatedPosition.x -= distanceFromOrigin; break; case Direction.Right: updatedPosition.x += distanceFromOrigin; break; default: break; } return(state.IsTileOccupied(updatedPosition.x, updatedPosition.y)); }
private void DisableMovementAtTheEnd() { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; _scenarioState = ScenarioState.Results; DisablePlayer(); }
void UpdateScenarioState(ScenarioState newScenarioState) { CurrentScenarioState = newScenarioState; GameStateManager.CurrentCampaign.player = newScenarioState.player; GameStateManager.CurrentCampaign.inventory = newScenarioState.inventory; GameStateDelegates.OnCampaignStateUpdated(GameStateManager.CurrentCampaign); }
List <ItemData> UpdateItemDurations(ScenarioState currentScenarioState) { List <ItemData> items = currentScenarioState.items; items.ForEach(i => i.Duration--); return(items.Where(i => i.Duration > 0).ToList()); }
public MainPage() { ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; localSettings.Values["valorIdGroup"] = "1"; this.InitializeComponent(); LearningModelDeviceKindSelected = LearningModelDeviceKind.Default; var modelosKind = new List <LearningModelDeviceKind>() { LearningModelDeviceKind.Cpu, LearningModelDeviceKind.Default, LearningModelDeviceKind.DirectX, LearningModelDeviceKind.DirectXHighPerformance, LearningModelDeviceKind.DirectXMinPower }; foreach (var item in modelosKind) { learningModelDeviceKinds.Add(item); } NetworkInformation.NetworkStatusChanged += cambioConection; IniciarModelo().Wait(1000); ObtenerVideoDevices(); if (HayConectividad.Conectividad()) { Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { btnIniciarStream.IsEnabled = true; }); } else { Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { btnIniciarStream.IsEnabled = false; }); } listaCaras.ItemsSource = listCaras; if (localSettings.Values["apiKey"] as string == "") { this.btnIniciarStream.IsEnabled = false; } else { this.btnIniciarStream.IsEnabled = true; } ShutdownWebCam(); btnTomarFoto.IsEnabled = false; this.currentState = ScenarioState.Idle; App.Current.Suspending += this.OnSuspending; App.Current.LeavingBackground += apagarCamara; }
public static EntityData GetTileOccupant(this ScenarioState state, Vector2Int position) { if (state.player.Position == position) { return(state.player); } return(state.enemies.Find(enemy => enemy.Position == position)); }
void RoundEndHandler(ScenarioState updatedGameState) { CurrentEnergy = CalculateUpdatedEnergy(CurrentEnergy, projectedEnergyGain, projectedEnergyLoss); projectedEnergyGain = 0; projectedEnergyLoss = 0; UpdateEnergyDisplay(); }
public MainPage() { this.InitializeComponent(); this.currentState = ScenarioState.Idle; //Scope is constant scope.Add("https://www.googleapis.com/auth/youtube.force-ssl"); scope.Add("https://www.googleapis.com/auth/youtube"); }
public MainPageVideoSource() { ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; localSettings.Values["valorIdGroup"] = "1"; this.InitializeComponent(); this.currentState = ScenarioState.Idle; App.Current.Suspending += this.OnSuspending; }
private void UntimedOnScenarioLoaded() { _scenarioState = ScenarioState.Untimed; session.SetScoreSystem(NagaUtils.FindObjectOfType <IScoreSystem>()); EnablePlayer(); statUI.SetUntimed(); countdownUI.Hide(); onScenarioStarted.Invoke(); }
public static void ChangeHealthValue_Scenario(this EntityData entity, int value, ScenarioState scenarioState) { if (value > 0) { entity.ChangeHealthValue_Campaign(value); } else if (value < 0) { entity.DealDamage(value, scenarioState); } }
public ProjectedGameState(EntityData _activeEntity, ScenarioState _gameState, Action _action, Bump bump) { activeEntity = _activeEntity; scenarioState = _gameState; bumps = new List <Bump>() { bump }; action = _action; attackedPositions = new List <Vector2Int>(); }
void Start() { qHandler = GameObject.FindGameObjectWithTag("GameController").GetComponent<QuestionnaireHandler>(); if (!qHandler.QuestionnaireEnabled) { DoneTesting = true; CurrentScenario = ScenarioState.WITH_TAIS; } else { if (CurrentScenario == ScenarioState.NONE) { CurrentScenario = Random.Range(0, 2) == 0 ? ScenarioState.WITH_TAIS : ScenarioState.WITHOUT_TAIS; } } }
public void IterateScenario() { if (!DoneTesting) { if (LastScenario == ScenarioState.NONE) { LastScenario = CurrentScenario; CurrentScenario = LastScenario == ScenarioState.WITHOUT_TAIS ? ScenarioState.WITH_TAIS : ScenarioState.WITHOUT_TAIS; Debug.Log("Second Scenario commencing"); } else { DoneTesting = true; CurrentScenario = ScenarioState.WITH_TAIS; Debug.Log("Done Scenario testing"); } } }
public ScenarioState finishState(ScenarioState next) { ResumeState gualState = new ResumeState(this); // make sure this is same state if (!this.isSameState(next)) { if (next.GetType().Equals(this.GetType())) { ResumeState nextState = (ResumeState)next; // make gualState's start be the earlier of the two if (nextState._start.CompareTo(gualState._start) < 0) { gualState._start = nextState._start; } // make gualState's start be the later of the two if (nextState._end.CompareTo(gualState._end) > 0) { gualState._end = nextState._end; } } } return gualState; }
public CameraScenario() { this.InitializeComponent(); this.currentState = ScenarioState.Idle; App.Current.Suspending += this.OnSuspending; }
/// <summary> /// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the /// passed in state value. Handles failures and resets the state if necessary. /// </summary> /// <param name="newState">State to switch to</param> private async void ChangeScenarioState(ScenarioState newState) { // Disable UI while state change is in progress this.StreamButton.IsEnabled = false; switch (newState) { case ScenarioState.Ready: this.StreamButton.IsEnabled = true; break; case ScenarioState.Idle: this.ShutdownCameraAsync(); this.StreamButton.Content = "Start Streaming"; this.currentState = newState; this.StreamButton.IsEnabled = true; break; case ScenarioState.Streaming: if (!await this.StartStreamingAsync()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.StreamButton.Content = "Stop Streaming"; this.currentState = newState; this.StreamButton.IsEnabled = true; break; } }
private async void ChangeScenarioState(ScenarioState newState) { switch (newState) { case ScenarioState.Idle: this.ShutdownWebCam(); //this.SnapshotCanvas.Background = null; //this.SnapshotCanvas.Children.Clear(); this.CameraSnapshotButton.IsEnabled = false; this.CameraStreamingButton.Content = "Start Cam"; this.CameraSnapshotButton.Content = "Capture"; this.currentState = newState; break; case ScenarioState.Streaming: if (!await this.StartWebcamStreaming()) { this.ChangeScenarioState(ScenarioState.Idle); break; } //this.SnapshotCanvas.Children.Clear(); this.CameraSnapshotButton.IsEnabled = true; this.CameraStreamingButton.Content = "Stop Cam"; this.CameraSnapshotButton.Content = "Capture"; this.currentState = newState; break; case ScenarioState.Snapshot: if (!await this.TakeSnapshotAndFindFaces()) { this.ChangeScenarioState(ScenarioState.Idle); break; } // this.ShutdownWebCam(); // I don't really know what happened here, it just seems to work \w/ this.CameraSnapshotButton.IsEnabled = true; this.CameraStreamingButton.Content = "Start Cam"; this.CameraSnapshotButton.Content = "Clear Display"; this.currentState = newState; break; } }
public FaceTrackerProxy (Canvas canvas, MainPage page, CaptureElement capture, MediaCapture mediacapture ) { if (this.faceTracker == null) { this.faceTracker = FaceTracker.CreateAsync().AsTask().Result; } rootPage = page; VisualizationCanvas = canvas; this.VisualizationCanvas.Children.Clear(); mediaCapture = mediacapture; var deviceController = mediaCapture.VideoDeviceController; this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; currentState = ScenarioState.Streaming; // Ensure the Semaphore is in the signalled state. this.frameProcessingSemaphore.Release(); // Use a 66 milisecond interval for our timer, i.e. 15 frames per second TimeSpan timerInterval = TimeSpan.FromMilliseconds(200); this.frameProcessingTimer = Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(new Windows.System.Threading.TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval); }
public Boolean isSameState(ScenarioState ss) { if (ss == null) { return false; } if (!ss.GetType().Equals(this.GetType())) { return false; } else { return this.Pos == ((PresenceState)ss).Pos; } }
/// <summary> /// when swipes get merged, their start and end times get merged /// the most recent position becomes the poisiton /// </summary> /// <param name="next"></param> /// <returns></returns> public ScenarioState mergeEqualStates(ScenarioState next) { SwipeState swipeState = new SwipeState(this); // make sure this is same state if (this.isSameState(next)) { if (next.GetType().Equals(this.GetType())) { SwipeState nextState = (SwipeState)next; // make gualState's start be the earlier of the two if (nextState._start.CompareTo(swipeState._start) < 0) { swipeState._start = nextState._start; } // make gualState's end be the later of the two // and make its loc the one of the later state if (nextState._end.CompareTo(swipeState._end) > 0) { swipeState._end = nextState._end; if (nextState.Pos.Equals(SwipePosition.MOVING)) { // only merge state location if merging two moving states swipeState._loc = nextState.Loc; } } } } return swipeState; }
public ScenarioState mergeEqualStates(ScenarioState next) { TalkOnPhoneState curState = new TalkOnPhoneState(this); if (this.isSameState(next)) { if (next.GetType().Equals(this.GetType())) { TalkOnPhoneState nextState = (TalkOnPhoneState)next; // make gualState's start be the earlier of the two if (nextState._start.CompareTo(curState._start) < 0) { curState._start = nextState._start; } // make gualState's start be the later of the two if (nextState._end.CompareTo(curState._end) > 0) { curState._end = nextState._end; } } } return curState; }
public Boolean isSameState(ScenarioState ss) { if (!ss.GetType().Equals(this.GetType())) { return false; } else { return this.Pos == ((ResumeState)ss).Pos; } }
public void StartSimulationPaused(string schemaFile, string scenarioFile,string replayFile) { scenarioState = ScenarioState.LOADING; simEngine.StartScenCon(schemaFile, scenarioFile, 1, debugFile,replayFile);//start as paused }
private void StopScenario(Boolean guiInitiated) { if (guiInitiated) { if (scenarioState != ScenarioState.STOPPED) { WriteScoreSummary(); } } scenarioState = ScenarioState.STOPPED; replayState = ScenarioState.STOPPED; simEngine.StopScenario(); isReady = false; }
public void addState(ScenarioState nextState) { if (this._history.Count > 0) { // previous states have been seen // pop off the previous state ScenarioState lastState = this.Pop(); if (lastState.isSameState(nextState)) { // previous state is same as current state // merge them ScenarioState newState = lastState.mergeEqualStates(nextState); // add new state back on // this replaces current and previous state this._history.Add(newState); } else { // previous state is not the same as the current // cap the previous state ScenarioState cappedOldState = lastState.finishState(nextState); if (cappedOldState.getDurationInSeconds() > this._falseStateDurationInSeconds) { // if the capped previous state has a reasonable length // add it // now add next state this._history.Add(cappedOldState); this._history.Add(nextState); } else if (this._history.Count > 0) { // so previous state didn't last for a reasonable amount of time // get the state before previous state... this one is gaurunteed to be a quality amount of time ScenarioState lastGoodState = this.Pop(); if (lastGoodState.isSameState(nextState)) { // if the next state is the same as the last good state // merge them ScenarioState newState = lastGoodState.mergeEqualStates(nextState); this._history.Add(newState); } else { ScenarioState cappedLastGoodState = lastGoodState.finishState(nextState); // otherwise cap the last good state this._history.Add(cappedLastGoodState); // add the next state this._history.Add(nextState); } } else { // this was the second state added // weve popped off the previous bad state // put this one one now. this._history.Add(nextState); } } } else { this._history.Add(nextState); } if (this._history.Count > this._maxSize) { int numRemove = this._history.Count - this._maxSize; this._history.RemoveRange(0, numRemove); } }
public void SimControlLoadReplay(String replayLogPath, Double replaySpeed) { Authenticator.LoadUserFile(); if (replayLogPath == this.Log) { SendServerStateEvent("REPLAY_LOAD_FAILURE", "Your current replay log is set to the same file as the file you'll be replaying from. To prevent error, change one of these two files before starting the server."); return; } if (Authenticator.GetNumUsers() == 0) { SendServerStateEvent("REPLAY_LOAD_FAILURE", "You must create at least one user account before loading a replay.\nUse the Users-->User Administration menu item."); return; } try { StreamReader re = File.OpenText(replayLogPath); string input = re.ReadLine(); re.Close(); creatorRegex = new Regex(@"^<Creator><Version>" + SimCoreServer.GetProductVersion() + "</Version><CompiledOn>" + SimCoreServer.GetCompileDate() + "</CompiledOn></Creator>$", RegexOptions.Singleline); if (!creatorRegex.IsMatch(input)) { SendServerStateEvent("REPLAY_LOAD_FAILURE", "This file must be replayed in a different version of the DDD."); return; } } catch (System.IO.IOException exc) { SendServerStateEvent("REPLAY_LOAD_FAILURE", String.Format("The selected file could not be opened for replay.\n{0}",exc.Message)); return; } simEngine.StartTextChatServer(); simEngine.StartWhiteboardServer(); // Start the voice server if it exists and is needed // The conditions will be added later if (ServerOptions.EnableVoiceServer) { // Get the simulation start time from the replay filename DateTime time = DateTime.Now; try { string timeString = replayLogPath.Remove(replayLogPath.LastIndexOf('.')); timeString = timeString.Substring(timeString.LastIndexOf('.') + 1); time = DateTime.ParseExact(timeString, "yyyyMMddHHmmss", null); } catch (Exception exc) { } HandshakeManager.SetVoiceEnabled(true); HandshakeManager.SetVoiceServerName(ServerOptions.VoiceServerHostname); HandshakeManager.SetVoiceServerPassword(ServerOptions.VoiceServerUserPassword); HandshakeManager.SetVoiceServerPort(ServerOptions.VoiceServerPort); simEngine.StartVoiceServer(ServerOptions.VoiceServerPort, ServerOptions.VoiceServerUserPassword, ServerOptions.VoiceServerAdminUsername, ServerOptions.VoiceServerAdminPassword, ServerOptions.EnableVoiceServerRecordings, time, true, replaySpeed); } else { HandshakeManager.SetVoiceEnabled(false); HandshakeManager.SetVoiceServerName(ServerOptions.VoiceServerHostname); HandshakeManager.SetVoiceServerPassword(ServerOptions.VoiceServerUserPassword); HandshakeManager.SetVoiceServerPort(ServerOptions.VoiceServerPort); } this.StartReplay(replayLogPath, false); this.SimControlPauseScenario(); SimCoreServer.replayState = Aptima.Asim.DDD.SimCoreServer.SimCoreServer.ScenarioState.LOADING; this.SetReplaySpeed(replaySpeed); }
/// <summary> /// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the /// passed in state value. Handles failures and resets the state if necessary. /// </summary> /// <param name="newState">State to switch to</param> private async void ChangeScenarioState(ScenarioState newState) { switch (newState) { case ScenarioState.Idle: this.ShutdownWebCam(); this.SnapshotCanvas.Background = null; this.SnapshotCanvas.Children.Clear(); this.CameraSnapshotButton.IsEnabled = false; this.CameraStreamingButton.Content = "Start Streaming"; this.CameraSnapshotButton.Content = "Take Snapshot"; this.currentState = newState; break; case ScenarioState.Streaming: if (!await this.StartWebcamStreaming()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.SnapshotCanvas.Background = null; this.SnapshotCanvas.Children.Clear(); this.CameraSnapshotButton.IsEnabled = true; this.CameraStreamingButton.Content = "Stop Streaming"; this.CameraSnapshotButton.Content = "Take Snapshot"; this.currentState = newState; break; case ScenarioState.Snapshot: if (!await this.TakeSnapshotAndFindFaces()) { this.ChangeScenarioState(ScenarioState.Idle); break; } this.ShutdownWebCam(); this.CameraSnapshotButton.IsEnabled = true; this.CameraStreamingButton.Content = "Start Streaming"; this.CameraSnapshotButton.Content = "Clear Display"; this.currentState = newState; break; } }
public void Update() { if (scenarioState == ScenarioState.LOADING) { if (simEngine.ErrorLoadingScenario()) { SendServerStateEvent("SCENARIO_LOAD_FAILURE", "Error Loading Scenario."); this.ResetServer(); return; } if (simEngine.IsReady()) { scenarioState = ScenarioState.PAUSED; isReady = true; SendServerStateEvent("SCENARIO_LOAD_SUCCESS", ""); } } if (replayState == ScenarioState.LOADING) { if (simEngine.ErrorLoadingScenario()) { this.StopReplay(); SendServerStateEvent("REPLAY_LOAD_FAILURE", "Error Loading Replay."); return; } if (simEngine.IsReady()) { replayState = ScenarioState.PAUSED; //SendOutAvailablePlayers(); isReady = true; SendServerStateEvent("REPLAY_LOAD_SUCCESS", ""); } } currentTime = (simEngine.simCore.GetSimTime() / 1000); List<SimulationEvent> events = eventClient.GetEvents(); if (events.Count > 0) { foreach (SimulationEvent e in events) { switch (e.eventType) { case "PauseScenarioRequest": if (scenarioState == ScenarioState.RUNNING) { SimControlPauseScenario(); } break; case "ResumeScenarioRequest": if (scenarioState == ScenarioState.PAUSED) { SimControlPauseScenario(); } break; case "LoadScenarioRequest": if (scenarioState == ScenarioState.STOPPED) { SimControlLoadScenario(((StringValue)e["ScenarioPath"]).value, ((StringValue)e["GroupName"]).value, ((StringValue)e["OutputLogDir"]).value); } break; case "StopScenarioRequest": if (scenarioState != ScenarioState.STOPPED) { SimControlStopScenario(false); } break; case "SimCoreReady": SendOutAvailablePlayers(); break; case "GameSpeedRequest": double speed = 1.0; try { speed = ((DoubleValue)e["SpeedFactor"]).value; } catch (Exception ex) { continue; } this.SetReplaySpeed(speed); break; case "ForkReplayFinished": HandshakeManager.IsForkReplay = false; simEngine.SetGameSpeed(1); if (scenarioState == ScenarioState.RUNNING) { SimControlPauseScenario(); } break; case "ForkReplayStarted": HandshakeManager.IsForkReplay = true; simEngine.SetGameSpeed(ServerOptions.ForkReplaySpeed); break; } } } }
public Boolean isSameState(ScenarioState ss) { if (!ss.GetType().Equals(this.GetType())) { return false; } else { return this.State == ((TalkOnPhoneState)ss).State; } }