private void PlayTimeline() { if (timelineTicker.currentTime < timelineMaximumTimeDuration) { GenerateMusicNotes(); if (timelineTicker.currentTime >= currentToTimeClamp * scrollBeginThreshold) { Debug.Log("expand timeline"); currentFromTimeClamp += Time.deltaTime; currentToTimeClamp += Time.deltaTime; GenerateTimelineTickers(); } // Debug.Log("fromTimeClamp : " + currentFromTimeClamp + " / toTimeClamp : " + currentToTimeClamp); timelineTicker.currentTime += Time.deltaTime; float x = ConvertFromTimeToTimelineXPosition(timelineTicker.currentTime); timelineTicker.transform.localPosition = new Vector3(x, timelineTicker.transform.localPosition.y, -0.50f); } else { currentFromTimeClamp = 0f; currentToTimeClamp = timelineMaximumTimeDuration / timelineScale; timelineState = TimelineState.Stop; } }
public TimelineState GetTimelineState(GameObject sourceObject = null) { if (_timelineState == null) { if (string.IsNullOrEmpty(_file._filePath)) { if (_stateMachine != null) { foreach (TimelineState state in _stateMachine._states) { if (state._stateId == _stateId) { _timelineState = state; break; } } } else { throw new Exception("TimelineStateRefProperty need to be fixed up by TimelineStateMachine"); } } else { TextAsset asset = _file.LoadAsset(); _stateMachine = TimelineStateMachine.FromTextAsset(asset, sourceObject); _file.UnloadAsset(); _timelineState = _stateMachine.GetTimelineState(_stateId); } } return(_timelineState); }
private void HandleTimelineStateChanged(TimelineState state) { if (state == TimelineState.Stopped) { OnTimelineStopped(); } }
public static void OnTimelineStateStarted(StateMachine stateMachine, TimelineState state, string fileName) { TimelineStateMachine parentStateMachine = state._debugParentStateMachine; if (parentStateMachine != null) { if (parentStateMachine != null) { StateInfo stateInfo; if (!_stateMachineMap.TryGetValue(stateMachine.gameObject, out stateInfo)) { stateInfo = new StateInfo(); _stateMachineMap.Add(stateMachine.gameObject, stateInfo); } stateInfo._stateMachine = parentStateMachine; stateInfo._state = state; stateInfo._time = 0.0f; if (!string.IsNullOrEmpty(fileName)) { stateInfo._fileName = fileName; } } } }
void Update() { switch (state) { case (TimelineState.Playing): time += Time.deltaTime; if (time > curve.keys[curve.length - 1].time) { time = curve.keys[curve.length - 1].time; state = TimelineState.Paused; } break; case (TimelineState.Reversing): time -= Time.deltaTime; if (time < 0) { time = 0.0f; state = TimelineState.Paused; } break; } parameter = curve.Evaluate(time); }
public TracingTimeline(GraphView graphView, GraphToolState windowGraphToolState) { m_GraphView = graphView; m_WindowGraphToolState = windowGraphToolState; m_TimeArea = new TimeArea(); m_Overlay = new AnimEditorOverlay() { PlayHeadColor = new Color(0.2117647F, 0.6039216F, 0.8F) }; m_State = new TimelineState(m_TimeArea); m_Overlay.state = m_State; var debugger = ((Stencil)m_WindowGraphToolState?.WindowState.GraphModel?.Stencil)?.Debugger; IGraphTrace trace = debugger?.GetGraphTrace(m_WindowGraphToolState?.WindowState.GraphModel, m_WindowGraphToolState.TracingControlState.CurrentTracingTarget); if (trace?.AllFrames != null && trace.AllFrames.Count > 0) { int firstFrame = trace.AllFrames[0].Frame; int lastFrame = trace.AllFrames[trace.AllFrames.Count - 1].Frame; m_TimeArea.SetShownRange( firstFrame - k_MinTimeVisibleOnTheRight, lastFrame + k_MinTimeVisibleOnTheRight); } }
/// <summary> /// Shows all documents associated with a given build document /// </summary> /// <param name="eventLogId"></param> /// <returns></returns> public ActionResult Documents(int eventLogId) { BuildEvent build = OsbideDb.BuildEvents .Include(be => be.Documents.Select(d => d.Document)) .Include(be => be.EventLog) .Where(be => be.EventLogId == eventLogId) .FirstOrDefault(); //find NPSM state for this build TimelineState buildState = (from npsm in Db.TimelineStates where npsm.StartTime >= build.EventLog.DateReceived && npsm.IsSocialEvent == false && npsm.UserId == build.EventLog.SenderId && npsm.State != "--" orderby npsm.Id ascending select npsm).Take(1).FirstOrDefault(); //find next "interested" build, defined as follows: //document contains +/- 10% more lines //new document added to build List <BuildEvent> futureBuilds = (from be in OsbideDb.BuildEvents join el in OsbideDb.EventLogs on be.EventLogId equals el.Id where el.Id > build.EventLogId && el.EventTypeId == 2 && //2 = build event log type el.SenderId == build.EventLog.SenderId select be) .Include(be => be.EventLog) .Include(be => be.Documents.Select(d => d.Document)) .Take(100) .ToList(); BuildEvent futureInterstingBuild = FindInterestingBuild(build, futureBuilds); //do the same thing, finding the most recent previously interesting build List <BuildEvent> pastBuilds = (from be in OsbideDb.BuildEvents join el in OsbideDb.EventLogs on be.EventLogId equals el.Id where el.Id < build.EventLogId && el.EventTypeId == 2 && //2 = build event log type el.SenderId == build.EventLog.SenderId orderby be.EventLogId descending select be ) .Include(be => be.EventLog) .Include(be => be.Documents.Select(d => d.Document)) .Take(100) .ToList(); BuildEvent pastInterestingBuild = FindInterestingBuild(build, pastBuilds); BuildDocumentsViewModel viewModel = new BuildDocumentsViewModel() { CurrentBuild = build, NextInterestingBuild = futureInterstingBuild, FutureBuilds = futureBuilds, PreviousInterestingBuild = pastInterestingBuild, PastBuilds = pastBuilds, BuildState = buildState }; return(View(viewModel)); }
// Called when the owning graph starts playing public override void OnGraphStart(Playable playable) { if (!EntityMgr.HasComponent <TimelineState>(Owner)) { return; } lastState = EntityMgr.GetComponentData <TimelineState>(Owner); }
public void FixUpRef(TimelineStateMachine stateMachine) { _stateMachine = stateMachine; _timelineState = null; #if UNITY_EDITOR _editorStateName = null; #endif }
public override bool IsConditionMet(StateMachineComponent stateMachine) { ITimelineStateTimer timer = TimelineState.GetTimer(stateMachine.gameObject); _time -= timer.GetDeltaTime(); return(_time <= 0.0f); }
/// <summary> /// Finds 50 build events centered around the supplied id parameter /// </summary> /// <param name="eventLogId">The id of the <see cref="EventLog"/> to use as an anchor</param> /// <returns></returns> public ActionResult Index(int eventLogId) { CommentTimeline timeline = Db.CommentTimelines.Where(t => t.EventLogId == eventLogId).FirstOrDefault(); EventLog commentLog = OsbideDb.EventLogs.Include(u => u.Sender).Where(el => el.Id == timeline.EventLogId).FirstOrDefault(); BuildDiffViewModel viewModel = new BuildDiffViewModel(); viewModel.User = commentLog.Sender; viewModel.Comment = timeline; viewModel.OriginalEvent = commentLog; //grab 10 prior builds viewModel.BuildsBefore = ( from el in OsbideDb.EventLogs join be in OsbideDb.BuildEvents .Include(b => b.Documents.Select(d => d.Document)) .Include(b => b.EventLog) on el.Id equals be.EventLogId where el.Id < commentLog.Id && el.SenderId == commentLog.SenderId orderby el.Id descending select be).Take(25).ToList(); //and 10 builds after viewModel.BuildsAfter = ( from el in OsbideDb.EventLogs join be in OsbideDb.BuildEvents .Include(b => b.Documents.Select(d => d.Document)) .Include(b => b.EventLog) on el.Id equals be.EventLogId where el.Id > commentLog.Id && el.SenderId == commentLog.SenderId orderby el.Id ascending select be).Take(25).ToList(); //for each build event, grab NPSM state foreach (BuildEvent build in viewModel.BuildsBefore.Union(viewModel.BuildsAfter)) { TimelineState priorBuildState = (from npsm in Db.TimelineStates where npsm.StartTime >= build.EventLog.DateReceived && npsm.IsSocialEvent == false && npsm.UserId == commentLog.SenderId && npsm.State != "--" orderby npsm.Id ascending select npsm).Take(1).FirstOrDefault(); if (priorBuildState == null) { priorBuildState = new TimelineState(); } viewModel.BuildStates.Add(build.Id, priorBuildState); } return(View(viewModel)); }
private bool DrawStateNamePopUps() { TimelineState[] states = null; switch (_editorLinkType) { case eType.External: { TimelineStateMachine stateMachines = SerializeConverter.FromFile <TimelineStateMachine>(AssetDatabase.GetAssetPath(_file._editorAsset)); states = stateMachines._states; } break; case eType.Internal: { if (_stateMachine != null) { states = _stateMachine._states; } } break; } if (states != null && states.Length > 0) { string[] stateNames = new string[states.Length + 1]; int index = 0; stateNames[0] = "<none>"; for (int i = 0; i < states.Length; i++) { stateNames[i + 1] = "State" + states[i]._stateId + " (" + StringUtils.GetFirstLine(states[i].GetDescription()) + ")"; if (states[i]._stateId == _stateId) { index = i + 1; } } EditorGUI.BeginChangeCheck(); index = EditorGUILayout.Popup("Timeline", index, stateNames); if (EditorGUI.EndChangeCheck()) { _stateId = index == 0 ? -1 : (int)states[index - 1]._stateId; _timelineState = null; _editorStateName = null; return(true); } } return(false); }
public StudentCommentTimeline() { CrowdCodings = new PostCoding(); CodeBeforeComment = new Dictionary <string, CodeDocument>(); CodeAfterComment = new Dictionary <string, CodeDocument>(); ProgrammingState = new TimelineState(); ProgrammingState.State = "not available"; ExpertCoding = new ContentCoding(); Log = new EventLog(); Author = new OsbideUser(); }
private void HandleStepStateChanged(Step step, TimelineState state) { // If playing, check if we're done. if (!RegisteredSteps.Any(s => s.IsBusy)) { State = TimelineState.Stopped; RecordingLord.StopRecording(); Camera.main.orthographic = false; if (HaxxisGlobalSettings.Instance.IsVgsJob == true) { if (TimelineViewBehaviour.Instance.NumRecordingsStartedThisPlayback == 0) { HaxxisGlobalSettings.Instance.ReportVgsError(6, "Choreography had no recording step"); } } if (HaxxisGlobalSettings.Instance.IsVgsJob == true) { HaxxisGlobalSettings.Instance.ReportVgsVideoDuration(); } } // Check for seek arrival if (IsSeeking) { if (step == SeekTarget) { // Hmm I thought something like this was going to be needed...? //if ( state == TimelineState.Playing ) IsSeeking = false; if (SeekThrough) { SetNormalSpeed(); } else { Pause(); } } } }
private void StopTimeline() { Debug.Log("stop timeline"); RemoveMusicNotes(); drumScorePoints = 0; drumScoreMissed = 0; DrumScoreHit.text = "0"; DrumScoreMiss.text = "0"; SetAllMusicNotesToBeUnTouched(); this.gameObject.SetActive(false); timelineState = TimelineState.Pause; timelineTicker.currentTime = 0; GenerateTimelineTickers(); UI_NotificationsManager.setUIConfiguration(); }
public static IEnumerator Run(StateMachine stateMachine, TimelineStateRef stateRef, GameObject sourceObject = null) { TimelineState state = stateRef.GetTimelineState(sourceObject != null ? sourceObject : stateMachine.gameObject); if (state != null) { #if UNITY_EDITOR && DEBUG string debugFileName = stateRef._file._filePath; TimelineStateMachineDebug.OnTimelineStateStarted(stateMachine, state, debugFileName); #endif return(PerformState(stateMachine, state, state._timeline)); } return(null); }
public static IEnumerator Run(StateMachine stateMachine, TimelineStateRefProperty stateRef, GameObject sourceObject = null) { TimelineState state = stateRef.LoadTimelineState(sourceObject != null ? sourceObject : stateMachine.gameObject); if (state != null) { #if UNITY_EDITOR && DEBUG string debugFileName = AssetDatabase.GetAssetPath(stateRef.GetFile()); TimelineStateMachineDebug.OnTimelineStateStarted(stateMachine, state, debugFileName); #endif return(PerformState(stateMachine, state, state._timeline)); } return(null); }
private void SetupStates() { this.Model.Reset(); foreach (var item in this.levelPoints) { item.Clear(); } resolution = TimeSpan.FromSeconds(5).Ticks; states = new TimelineState[6]; for (int i = 0; i < 6; i++) { states[i] = new TimelineState(i); states[i].resolution = TimeSpan.FromMilliseconds(500).Ticks; } states[0].resolution = TimeSpan.FromMinutes(1).Ticks; }
public void CheckTimeSpeed(TimelineState state) { if (state == TimelineState.STOP) { timeSpeedImage.sprite = pauseSprite; } else if (state == TimelineState.PLAY) { timeSpeedImage.sprite = playSprite; } else if (state == TimelineState.x2) { timeSpeedImage.sprite = fastPlaySprite; } else if (state == TimelineState.x4) { timeSpeedImage.sprite = veryFastPlaySprite; } }
private void SwitchViewsIfNeeded() { if (_requestSwitchViews) { if (_requestSwitchViewsStateId != -1) { StateEditorGUI state = GetStateGUI(_requestSwitchViewsStateId); if (state != null) { if (state.GetEditableObject() is TimelineState) { TimelineState timelineState = (TimelineState)state.GetEditableObject(); _currentMode = eMode.ViewingTimelineState; _editedState = state; _timelineEditor.SetTimeline(timelineState._timeline); _editorPrefs._stateId = _requestSwitchViewsStateId; SaveEditorPrefs(); foreach (StateEditorGUI stateView in _selectedObjects) { GetEditorWindow().OnDeselectObject(stateView); } } else { SetViewToStatemachine(); _selectedObjects.Clear(); _selectedObjects.Add(state); Selection.activeObject = state; } } } else { SetViewToStatemachine(); } _requestSwitchViews = false; } }
//adds normalized programming state metrics to each user public void NormalizeProgrammingStates() { //Algorithm: sum states total time, normalize based on total time spent in each state foreach (StudentTimeline timeline in Timeline.Values) { TimeSpan total_time = new TimeSpan(0, 0, 0); //pass #1: find total time foreach (string state in _intersting_states) { TimelineState aggregate = timeline.GetAggregateState(state); total_time += aggregate.TimeInState; } //add total time to states timeline.GetAggregateState("normalized_total_time").StartTime = DateTime.MinValue; timeline.GetAggregateState("normalized_total_time").EndTime = DateTime.MinValue + total_time; TimelineState totalState = new TimelineState() { State = "normalized_total_time", StartTime = DateTime.MinValue, EndTime = timeline.GetAggregateState("normalized_total_time").EndTime }; timeline.RawStates.Add(totalState); //pass #2: normalize foreach (string state in _intersting_states) { string normilzedKey = string.Format("normalized_{0}", state); TimelineState aggregate = timeline.GetAggregateState(state); TimelineState normalizedState = new TimelineState() { State = normilzedKey, NormalizedTimeInState = (aggregate.TimeInState.TotalSeconds / total_time.TotalSeconds) * 100, }; //add back to student timeline.GetAggregateState(normilzedKey).NormalizedTimeInState = normalizedState.NormalizedTimeInState; timeline.RawStates.Add(normalizedState); } } }
public static void GetTimelineTransform(TransformTimeline timeline, float position, DBTransform retult) { List <Frame> frameList = timeline.FrameList; int i = frameList.Count; TransformFrame currentFrame; float tweenEasing; float progress; TransformFrame nextFrame; while (i-- > 0) { currentFrame = frameList[i] as TransformFrame; if (currentFrame.Position <= position && currentFrame.Position + currentFrame.Duration > position) { tweenEasing = currentFrame.TweenEasing; if (i == frameList.Count - 1 || float.IsNaN(tweenEasing) || position == currentFrame.Position) { retult.Copy(currentFrame.Global); } else { progress = (position - currentFrame.Position) / currentFrame.Duration; if (tweenEasing != 0 && !float.IsNaN(tweenEasing)) { progress = TimelineState.GetEaseValue(progress, tweenEasing); } nextFrame = frameList[i + 1] as TransformFrame; retult.X = currentFrame.Global.X + (nextFrame.Global.X - currentFrame.Global.X) * progress; retult.Y = currentFrame.Global.Y + (nextFrame.Global.Y - currentFrame.Global.Y) * progress; retult.SkewX = TransformUtil.FormatRadian(currentFrame.Global.SkewX + (nextFrame.Global.SkewX - currentFrame.Global.SkewX) * progress); retult.SkewY = TransformUtil.FormatRadian(currentFrame.Global.SkewY + (nextFrame.Global.SkewY - currentFrame.Global.SkewY) * progress); retult.ScaleX = currentFrame.Global.ScaleX + (nextFrame.Global.ScaleX - currentFrame.Global.ScaleX) * progress; retult.ScaleY = currentFrame.Global.ScaleY + (nextFrame.Global.ScaleY - currentFrame.Global.ScaleY) * progress; } break; } } }
private void TimelineUpdated(TimelineState status) { if (!isInitialized) { return; } if (VideoPlayer && VideoPlayer.isPrepared) { if (VideoPlayer.isPlaying == false && status.TimelineStatus == TimelineStatus.PLAYING) { VideoPlayer.Play(); } else if (VideoPlayer.isPlaying == true && status.TimelineStatus == TimelineStatus.PAUSED) { VideoPlayer.Pause(); } VideoPlayer.time = GetVideoTimeForTimestamp(status.CurrentTimestamp); VideoPlayer.playbackSpeed = status.PlaybackSpeed; } }
private void HandleTimelineStateChanged(TimelineState timelineState) { if (State == LockedState) { throw new InvalidOperationException("Timeline changed state while View was locked."); } if (timelineState == TimelineState.Playing) { State = PlayingState; SeekEnabled = false; PlayStarted(); } if (timelineState == TimelineState.Paused) { State = PausedState; } if (timelineState == TimelineState.Stopped) { State = StoppedState; SeekEnabled = true; if (MinimizeOnPlay) { Restore(false); } if (HideChainViewOnPlay) { ChainView.Instance.Visible = WasChainViewOpen; } PlayStopped(); } }
private void TimelineUpdated(TimelineState timelineState) { if (!isInitialized) { return; } if (PlayButton) { var helper = PlayButton.GetComponent <ButtonConfigHelper>(); if (helper) { if (TimelineStatus == TimelineStatus.PAUSED) { helper.MainLabelText = "Play"; helper.SetSpriteIconByName("IconPlay"); } else if (TimelineStatus == TimelineStatus.PLAYING) { helper.MainLabelText = "Pause"; helper.SetSpriteIconByName("IconPause"); } } } PlaybackSpeed = timelineState.PlaybackSpeed; foreach (VideoPlayer vp in GameObject.FindObjectsOfType <VideoPlayer>()) { vp.playbackSpeed = PlaybackSpeed; } if (PlaybackSpeedLabel) { PlaybackSpeedLabel.text = "x" + PlaybackSpeed.ToString(CultureInfo.InvariantCulture); } UpdateView(); }
/// <summary> /// Gets comment details for a particular student /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult Student(int id) { /* * to fetch: * For each comment: * Comment * Option to view entire thread * Chris, Adam, Carla content coding info * Adam's student EC coding info * size of previous / next save * time of prevous / last save * NPSM state * */ List<CommentTimelineViewModel> viewModel = new List<CommentTimelineViewModel>(); //id is nice for MVC, but not very descriptive, switch to studentId in body. int studentId = id; int[] interestingEventIds = { 1 //ask for help , 2 //build event , 7 //feed post , 9 //log comment , 10 //save }; //only social events int[] socialEventIds = {1, 7, 9}; //check to see if we have cached results in the DB var cachedResults = Db .CommentTimelines .Include(c => c.ProgrammingState) .Include(c => c.QuestionCodings.Select(q => q.QuestionCoding.Post)) .Include(c => c.AnswerCodings.Select(q => q.AnswerCoding.Answer)) .Include(c => c.ExpertCoding) .Include(c => c.TimelineCodeDocuments) .Where(c => c.AuthorId == studentId) ; if (cachedResults.Count() > 0) { var authorQuery = from user in OsbideDb.Users where user.Id == studentId select user; OsbideUser student = authorQuery.FirstOrDefault(); student = (student == null) ? new OsbideUser() : student; var eventLogQuery = from log in OsbideDb.EventLogs where log.SenderId == studentId && socialEventIds.Contains(log.EventTypeId) select log; Dictionary<int, EventLog> allEventLogs = new Dictionary<int, EventLog>(); foreach(EventLog log in eventLogQuery) { allEventLogs.Add(log.Id, log); } foreach(CommentTimeline timeline in cachedResults) { CommentTimelineViewModel nextViewModel = new CommentTimelineViewModel(timeline); nextViewModel.Log = allEventLogs[timeline.EventLogId]; nextViewModel.Author = student; List<TimelineCodeDocument> beforeDocuments = timeline.TimelineCodeDocuments.Where(t => t.isBeforeComment == true).ToList(); List<TimelineCodeDocument> afterDocuments = timeline.TimelineCodeDocuments.Where(t => t.isBeforeComment == false).ToList(); nextViewModel.CodeBeforeComment = new Dictionary<string, TimelineCodeDocument>(); nextViewModel.CodeAfterComment = new Dictionary<string, TimelineCodeDocument>(); foreach(TimelineCodeDocument tcd in beforeDocuments) { nextViewModel.CodeBeforeComment.Add(tcd.DocumentName, tcd); } foreach(TimelineCodeDocument tcd in afterDocuments) { nextViewModel.CodeAfterComment.Add(tcd.DocumentName, tcd); } viewModel.Add(nextViewModel); } } else { //no cached results, do it the long way... //this query pulls most questions (ask for help excluded?) from the analytics DB //and should be faster than loading all questions from the OSBIDE DB var commentQuery = from comment in Db.Posts where comment.AuthorId == studentId select comment; //convert into dictionary for lookup by logsQuery Dictionary<int, Post> posts = new Dictionary<int, Post>(); foreach (Post post in commentQuery) { posts.Add(post.OsbideId, post); } //This query will pull down all content coding questions, organized by Osbide user ID var contentCodingQuery = from code in Db.ContentCodings where code.AuthorId == studentId select code; SortedList<DateTime, ContentCoding> expertCodings = new SortedList<DateTime, ContentCoding>(); foreach (ContentCoding coding in contentCodingQuery) { //I was getting key mismatch (probably difference in milliseconds). My solution was to create //a new date using only coarser measures DateTime dateKey = new DateTime(coding.Date.Year, coding.Date.Month, coding.Date.Day, coding.Date.Hour, coding.Date.Minute, coding.Date.Second, DateTimeKind.Utc); expertCodings.Add(dateKey, coding); } //This query will pull down information obtained from my crowd-sourced content coding. //AnswerCodings have FK reference to the original question as well as the answer. If a Post //is in the AnswerCodings table, it must be an answer var answeredQuestionsQuery = from answer in Db.AnswerCodings .Include(c => c.Answer) .Include(c => c.Question) where answer.Answer.AuthorId == studentId || answer.Question.AuthorId == studentId select answer; var allPostsQuery = from question in Db.QuestionCodings .Include(c => c.Post) where question.Post.AuthorId == studentId select question; Dictionary<int, PostCoding> crowdCodings = new Dictionary<int, PostCoding>(); foreach (QuestionCoding coding in allPostsQuery) { if (crowdCodings.ContainsKey(coding.Post.OsbideId) == false) { crowdCodings.Add(coding.Post.OsbideId, new PostCoding()); crowdCodings[coding.Post.OsbideId].OsbidePostId = coding.Post.OsbideId; } crowdCodings[coding.Post.OsbideId].Codings.Add(coding); } foreach (AnswerCoding coding in answeredQuestionsQuery) { if (crowdCodings.ContainsKey(coding.Question.OsbideId) == false) { crowdCodings.Add(coding.Question.OsbideId, new PostCoding()); crowdCodings[coding.Question.OsbideId].OsbidePostId = coding.Question.OsbideId; } crowdCodings[coding.Question.OsbideId].Responses.Add(coding); } //grab all save and build events for this user Dictionary<int, SaveEvent> allSaves = new Dictionary<int, SaveEvent>(); Dictionary<int, BuildEvent> allBuilds = new Dictionary<int, BuildEvent>(); var savesQuery = from save in OsbideDb.SaveEvents .Include(s => s.Document) join log in OsbideDb.EventLogs on save.EventLogId equals log.Id where log.SenderId == studentId select save; foreach (SaveEvent saveEvent in savesQuery) { allSaves[saveEvent.EventLogId] = saveEvent; } var buildsQuery = from build in OsbideDb.BuildEvents .Include(b => b.Documents.Select(d => d.Document)) join log in OsbideDb.EventLogs on build.EventLogId equals log.Id where log.SenderId == studentId select build; foreach (BuildEvent buildEvent in buildsQuery) { allBuilds[buildEvent.EventLogId] = buildEvent; } //this query pulls data directly from event logs. var logsQuery = from log in OsbideDb.EventLogs where log.SenderId == studentId && interestingEventIds.Contains(log.EventTypeId) select log; List<EventLog> eventLogs = logsQuery.ToList(); Stack<EventLog> saveEvents = new Stack<EventLog>(); List<EventLog> socialEvents = new List<EventLog>(); foreach (EventLog log in eventLogs) { //holds the next entry into the view model CommentTimelineViewModel nextViewModel = new CommentTimelineViewModel(); //if we have a document save event, remember for later until we get a social event if (log.LogType == SaveEvent.Name || log.LogType == BuildEvent.Name) { saveEvents.Push(log); } else { //social event detected //1: grab previous edit information string solutionName = ""; Dictionary<string, CodeDocument> previousDocuments = new Dictionary<string, CodeDocument>(); //Start with saves as they will contain more up-to-date information than last build while (saveEvents.Count > 0 && saveEvents.Peek().LogType != BuildEvent.Name) { EventLog next = saveEvents.Pop(); if (allSaves.ContainsKey(next.Id)) { SaveEvent save = allSaves[next.Id]; if (solutionName.Length == 0) { solutionName = save.SolutionName; } if (save.SolutionName == solutionName) { if (previousDocuments.ContainsKey(save.Document.FileName) == false) { previousDocuments[save.Document.FileName] = save.Document; } } } } //at this point, saveEvents should be empty or we should be at a build event. //Finish off the snapshot with documents transferred with last build if (saveEvents.Count > 0) { EventLog top = saveEvents.Pop(); if (allBuilds.ContainsKey(top.Id)) { BuildEvent build = allBuilds[top.Id]; if (solutionName.Length == 0) { solutionName = build.SolutionName; } if (build.SolutionName == solutionName) { foreach (BuildDocument doc in build.Documents) { if (previousDocuments.ContainsKey(doc.Document.FileName) == false) { previousDocuments[doc.Document.FileName] = doc.Document; } } } } } //store final result in view model foreach(CodeDocument document in previousDocuments.Values) { TimelineCodeDocument tcd = new TimelineCodeDocument() { CodeDocumentId = document.Id, CommentTimeline = nextViewModel.Timeline, DocumentContent = document.Content, DocumentName = document.FileName, isBeforeComment = true }; if(nextViewModel.Timeline.TimelineCodeDocuments == null) { nextViewModel.Timeline.TimelineCodeDocuments = new List<TimelineCodeDocument>(); } nextViewModel.Timeline.TimelineCodeDocuments.Add(tcd); } //2: grab next edit information (will have to be done on 2nd pass) //grab expert content coding info DateTime dateKey = new DateTime(log.DateReceived.Year, log.DateReceived.Month, log.DateReceived.Day, log.DateReceived.Hour, log.DateReceived.Minute, log.DateReceived.Second, DateTimeKind.Utc); //I was getting key mismatch (probably difference in milliseconds). My solution was to create //a new date using only coarser measures if (expertCodings.ContainsKey(dateKey)) { nextViewModel.Timeline.ExpertCoding = expertCodings[dateKey]; nextViewModel.Timeline.ExpertCodingId = expertCodings[dateKey].Id; } //grab crowd coding info var crowd = crowdCodings.Where(cc => cc.Key == log.Id).Select(k => k.Value).FirstOrDefault(); if (crowd != null) { foreach (var question in crowd.Codings) { TimelineQuestionCoding questionCode = new TimelineQuestionCoding() { CommentTimeline = nextViewModel.Timeline, QuestionCoding = question, QuestionCodingId = question.Id }; nextViewModel.Timeline.QuestionCodings.Add(questionCode); } foreach (var answer in crowd.Responses) { TimelineAnswerCoding responseCoding = new TimelineAnswerCoding() { CommentTimeline = nextViewModel.Timeline, AnswerCoding = answer, AnswerCodingId = answer.Id }; nextViewModel.Timeline.AnswerCodings.Add(responseCoding); } } //grab NPSM state info //we want the most recent NPSM state that occurred before the comment was made var npsmQuery = from npsm in Db.TimelineStates where npsm.StartTime <= log.DateReceived && npsm.IsSocialEvent == false && npsm.UserId == log.SenderId && npsm.State != "--" orderby npsm.Id ascending select npsm; TimelineState state = npsmQuery.Take(1).FirstOrDefault(); if (state != null) { nextViewModel.Timeline.ProgrammingState = state; nextViewModel.Timeline.ProgrammingStateId = state.Id; } //add in comment information if (posts.ContainsKey(log.Id) == true) { nextViewModel.Timeline.Comment = posts[log.Id].Content; } else { //not found in pre-query. Pull manually if (log.LogType == FeedPostEvent.Name) { FeedPostEvent feedPost = OsbideDb.FeedPostEvents.Where(fpe => fpe.EventLogId == log.Id).FirstOrDefault(); if (feedPost != null) { nextViewModel.Timeline.Comment = feedPost.Comment; } } else if (log.LogType == LogCommentEvent.Name) { LogCommentEvent logComment = OsbideDb.LogCommentEvents.Where(fpe => fpe.EventLogId == log.Id).FirstOrDefault(); if (logComment != null) { nextViewModel.Timeline.Comment = logComment.Content; } } else if (log.LogType == AskForHelpEvent.Name) { AskForHelpEvent ask = OsbideDb.AskForHelpEvents.Where(fpe => fpe.EventLogId == log.Id).FirstOrDefault(); if (ask != null) { nextViewModel.Timeline.Comment = ask.UserComment + "\n" + ask.Code; } } } nextViewModel.Log = log; nextViewModel.Timeline.EventLogId = log.Id; nextViewModel.Timeline.AuthorId = log.SenderId; nextViewModel.Author = log.Sender; if(nextViewModel.Timeline.ExpertCoding == null) { nextViewModel.Timeline.ExpertCoding = new ContentCoding(); } if(nextViewModel.Timeline.ProgrammingState == null) { nextViewModel.Timeline.ProgrammingState = new TimelineState() { EndTime = new DateTime(2016, 01, 01), StartTime = new DateTime(2016, 01, 01), State = "not available" }; } viewModel.Add(nextViewModel); } } //2nd pass: find code modifications made after comment. for (int i = 0; i < viewModel.Count; i++) { CommentTimelineViewModel current = viewModel[i] as CommentTimelineViewModel; CommentTimelineViewModel next = new CommentTimelineViewModel(); if (i + 1 < viewModel.Count) { next = viewModel[i + 1] as CommentTimelineViewModel; } else { next.Log = eventLogs.Last(); } List<EventLog> logsBetween = eventLogs .Where(l => l.DateReceived >= current.Log.DateReceived) .Where(l => l.DateReceived <= next.Log.DateReceived) .ToList(); Dictionary<string, CodeDocument> nextDocuments = new Dictionary<string, CodeDocument>(); string solutionName = ""; foreach (EventLog log in logsBetween) { if (log.LogType == SaveEvent.Name) { if (allSaves.ContainsKey(log.Id)) { SaveEvent save = allSaves[log.Id]; if (solutionName.Length == 0) { solutionName = save.SolutionName; } if (save.SolutionName == solutionName) { if (nextDocuments.ContainsKey(save.Document.FileName) == false) { nextDocuments[save.Document.FileName] = save.Document; } } } } else if (log.LogType == BuildEvent.Name) { if (allBuilds.ContainsKey(log.Id)) { BuildEvent build = allBuilds[log.Id]; if (solutionName.Length == 0) { solutionName = build.SolutionName; } if (build.SolutionName == solutionName) { foreach (BuildDocument doc in build.Documents) { if (nextDocuments.ContainsKey(doc.Document.FileName) == false) { nextDocuments[doc.Document.FileName] = doc.Document; } } } } } } //store after documents foreach (CodeDocument document in nextDocuments.Values) { TimelineCodeDocument tcd = new TimelineCodeDocument() { CodeDocumentId = document.Id, CommentTimeline = current.Timeline, DocumentContent = document.Content, DocumentName = document.FileName, isBeforeComment = false }; if(current.Timeline.TimelineCodeDocuments == null) { current.Timeline.TimelineCodeDocuments = new List<TimelineCodeDocument>(); } current.Timeline.TimelineCodeDocuments.Add(tcd); } } //try jamming all this crap into DB Db.CommentTimelines.AddRange(viewModel.Select(m => m.Timeline).ToList()); Db.SaveChanges(); } return View(viewModel); }
/// <summary> /// Generates a list of document saves centered around a particular point of interest /// </summary> /// <param name="id">The id of the <see cref="CommentTimeline"/> to use as an anchor</param> /// <returns></returns> public ActionResult DocumentSaveTimeline(int id) { CommentTimeline timeline = Db.CommentTimelines.Where(t => t.Id == id).FirstOrDefault(); EventLog commentLog = OsbideDb.EventLogs.Include(u => u.Sender).Where(el => el.Id == timeline.EventLogId).FirstOrDefault(); //get all posts in the conversation Post userPost = Db.Posts.Where(p => p.OsbideId == commentLog.Id).FirstOrDefault(); List<Post> entireDiscussion = new List<Post>(); if(userPost.ParentId > 0) { entireDiscussion = (from post in Db.Posts where (post.ParentId == userPost.ParentId || post.Id == userPost.ParentId) orderby post.OsbideId select post).ToList(); } else { entireDiscussion = (from post in Db.Posts where (post.ParentId == userPost.Id || post.Id == userPost.Id) orderby post.OsbideId select post).ToList(); } //for each post in the discussion, grab a snapshot of the user's code Dictionary<int, BuildEvent> beforeBuildEvents = new Dictionary<int, BuildEvent>(); Dictionary<int, BuildEvent> afterBuildEvents = new Dictionary<int, BuildEvent>(); Dictionary<int, TimelineState> statesBefore = new Dictionary<int, TimelineState>(); Dictionary<int, TimelineState> statesAfter = new Dictionary<int, TimelineState>(); foreach(Post post in entireDiscussion) { //get prior build event BuildEvent priorBuildEvent = (from el in OsbideDb.EventLogs join be in OsbideDb.BuildEvents .Include(b => b.Documents.Select(d => d.Document)) .Include(b => b.EventLog) on el.Id equals be.EventLogId where el.Id < post.OsbideId && el.SenderId == commentLog.SenderId orderby el.Id descending select be).Take(1).FirstOrDefault(); //grab next build event BuildEvent nextBuildEvent = (from el in OsbideDb.EventLogs join be in OsbideDb.BuildEvents .Include(b => b.Documents.Select(d => d.Document)) .Include(b => b.EventLog) on el.Id equals be.EventLogId where el.Id > post.OsbideId && el.SenderId == commentLog.SenderId orderby el.Id ascending select be).Take(1).FirstOrDefault(); if (priorBuildEvent != null) { //we want the NPSM state that resulted from this build TimelineState priorBuildState = (from npsm in Db.TimelineStates where npsm.StartTime >= priorBuildEvent.EventLog.DateReceived && npsm.IsSocialEvent == false && npsm.UserId == commentLog.SenderId && npsm.State != "--" orderby npsm.Id ascending select npsm).Take(1).FirstOrDefault(); statesBefore.Add(post.Id, priorBuildState); beforeBuildEvents.Add(post.Id, priorBuildEvent); } if(nextBuildEvent != null) { //we want the NPSM state that resulted from this build TimelineState afterBuildState = (from npsm in Db.TimelineStates where npsm.StartTime >= nextBuildEvent.EventLog.DateReceived && npsm.IsSocialEvent == false && npsm.UserId == commentLog.SenderId && npsm.State != "--" orderby npsm.Id ascending select npsm).Take(1).FirstOrDefault(); statesAfter.Add(post.Id, afterBuildState); afterBuildEvents.Add(post.Id, nextBuildEvent); } } //construct final VM DocumentSaveTimelineViewModel viewModel = new DocumentSaveTimelineViewModel() { BuildsAfter = afterBuildEvents, BuildsBefore = beforeBuildEvents, Discussion = entireDiscussion, StatesAfter = statesAfter, StatesBefore = statesBefore, Timeline = timeline, TimelineLog = commentLog, User = commentLog.Sender }; return View(viewModel); }
/// <summary> /// Stops the timeline. /// </summary> public void Stop() { //Stop the timeline. _State = TimelineState.Concluded; //If someone has hooked up a delegate to the event, fire it. if (OnConcluded != null) { OnConcluded(); } }
/// <summary> /// Initialize the timeline. /// </summary> /// <param name="move">The battle move to execute.</param> private void Initialize(BattleMove move) { //Initialize the fields. _Move = move; _ElapsedTime = 0; _Events = new List<TimelineEvent>(); _State = TimelineState.Idle; }
void Update() { switch (state) { case (TimelineState.Playing): time += Time.deltaTime; if (time > curve.keys[curve.length-1].time) { time = curve.keys[curve.length-1].time; state = TimelineState.Paused; } break; case (TimelineState.Reversing): time -= Time.deltaTime; if (time < 0) { time = 0.0f; state = TimelineState.Paused; } break; } parameter = curve.Evaluate(time); }
/// <summary> /// Perform this event. /// </summary> /// <param name="gametime">The elapsed game time.</param> /// <param name="elapsedTime">The elapsed time since the beginning of this event.</param> /// <returns>Whether the event was performed this cycle or not.</returns> protected virtual bool PerformEvent(GameTime gametime, float elapsedTime) { //If the elapsed time is less than 0, quit. if (_State == TimelineState.Concluded || elapsedTime < 0) { return false; } //Activate the event. _State = TimelineState.Active; //The event was performed. return true; }
/// <summary> /// Initialize the timeline event. /// </summary> /// <param name="timeline">The timeline this event is part of.</param> /// <param name="start">The start of the event.</param> /// <param name="dependentOn">An optional event to be dependent upon, ie. wait for.</param> protected virtual void Initialize(Timeline timeline, float start, TimelineEvent dependentOn) { //Initialize the variables. _Timeline = timeline; _StartTime = start; _EndTime = start; _DependentOn = dependentOn; _Outcome = EventOutcome.None; _State = TimelineState.Idle; //If this event is dependent upon someone else, subscribe to it. if (_DependentOn != null) { _DependentOn.OnConcluded += OnDependentEnded; } }
public void Play() { state = TimelineState.Playing; }
public void PlayFromStart() { state = TimelineState.Playing; time = 0; }
public void Reverse() { state = TimelineState.Reversing; }
private static IEnumerator PerformState(StateMachine stateMachine, TimelineState state, Timeline timeline) { if (timeline != null && timeline._events.Length > 0) { ITimelineStateMachineTimer timer = TimelineStateMachine.GetTimer(stateMachine.gameObject); float currentTime = 0.0f; List <Event> nonInstantEvents = new List <Event>(); int eventIndex = 0; Event currentEvent = timeline._events[eventIndex]; while (currentEvent != null || nonInstantEvents.Count > 0) { IStateMachineEvent currentStateMachineEvent = currentEvent as IStateMachineEvent; if (currentStateMachineEvent == null && currentEvent != null) { throw new System.Exception("Event doesn't implement IStateMachineEvent"); } float nextEventTime = currentEvent != null ? timeline._events[eventIndex].GetTime() : 0.0f; //Wait until event time while (currentTime < nextEventTime || (currentEvent == null && nonInstantEvents.Count > 0)) { currentTime += timer.GetDeltaTime(); #if DEBUG TimelineStateMachineDebug.OnTimelineStateTimeProgress(stateMachine, state, currentTime); #endif //Updated non instant events, if any now wants to exit the state then break out of coroutine if (UpdateNonInstantEvents(stateMachine, ref nonInstantEvents, currentTime)) { EndNonInstantEvents(stateMachine, ref nonInstantEvents); yield break; } yield return(null); } if (currentEvent == null) { break; } //Trigger event eEventTriggerReturn status = currentStateMachineEvent.Trigger(stateMachine); switch (status) { case eEventTriggerReturn.EventFinished: //Do nothing, just move on to next event break; case eEventTriggerReturn.EventFinishedExitState: //Exit state so break out of coroutine EndNonInstantEvents(stateMachine, ref nonInstantEvents); yield break; case eEventTriggerReturn.EventOngoing: //Track timed event, move on to next event nonInstantEvents.Add(currentEvent); break; } //Get next currentEvent = ++eventIndex < timeline._events.Length ? timeline._events[eventIndex] : null; } } #if DEBUG TimelineStateMachineDebug.OnTimelineStateStoped(stateMachine); #endif yield break; }
public void ReverseFromEnd() { state = TimelineState.Reversing; time = 0; }
/// <summary> /// This timeline event has now ended. /// </summary> protected void EventConcludedInvoke() { //The event has now occurred. _State = TimelineState.Concluded; //If someone has hooked up a delegate to the event, fire it. if (OnConcluded != null) { OnConcluded(this); } }
public void Pause() { state = TimelineState.Paused; }
/// <summary> /// Activate this event if the one we have been dependent upon has ended. /// </summary> /// <param name="eventRule">The event that has ended.</param> protected virtual void OnDependentEnded(TimelineEvent eventRule) { //Set the state to active. _State = TimelineState.Active; }
public static void OnTimelineStateTimeProgress(StateMachine stateMachine, TimelineState intialState, float time) { StateInfo stateInfo; if (_stateMachineMap.TryGetValue(stateMachine.gameObject, out stateInfo)) { _stateMachineMap[stateMachine.gameObject]._time = time; } }
public MainPage() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += navigationHelper_LoadState; this.navigationHelper.SaveState += navigationHelper_SaveState; this.SizeChanged+=MainPage_SizeChanged; this.NavigationCacheMode = NavigationCacheMode.Enabled; VisualStateManager.GoToState(this,VisualStateTimeline.MultiTimeline,true); timelineState = TimelineState.MultiTimeline; Application.Current.Suspending += async(s, e) => { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: アプリケーションの状態を保存してバックグラウンドの動作があれば停止します await viewModel.SaveTwitterDataAsync(); deferral.Complete(); }; Application.Current.Resuming += (s,e) => { }; textKeyManager = new TweetKeyManager(textPost,KeyBindings.PostTextKeyBinder); textKeyManager.CommandList.Add("PostTweet",(bind)=>{ viewModel.PostStatusCommand.Execute(null); }); textBottomKeyManager = new TweetKeyManager(textPostBottom, KeyBindings.PostTextKeyBinder); textBottomKeyManager.CommandList.Add("PostTweet", (bind) => { viewModel.PostStatusCommand.Execute(null); }); pageKeyManager=new KeyManager(this,KeyBindings.PageTextKeyBinder); pageKeyManager.CommandList.Add("UpTab", (bind) => { viewModel.NextTabCommand.Execute(null); ChangeTimelineSize(new Size(Window.Current.Bounds.Width,Window.Current.Bounds.Height)); }); pageKeyManager.CommandList.Add("DownTab", (bind) => { viewModel.PrevTabCommand.Execute(null); ChangeTimelineSize(new Size(Window.Current.Bounds.Width, Window.Current.Bounds.Height)); }); MessengerRegister(); mediaElementNotification = new MediaElement(); mediaElementNotification.AutoPlay = false; var uri = new Uri("ms-appx:///Assets/Sound/notification.wav"); var file = Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri).AsTask<StorageFile>().Result; var stream = file.OpenAsync(Windows.Storage.FileAccessMode.Read).AsTask<IRandomAccessStream>().Result; mediaElementNotification.SetSource(stream,file.ContentType); }
/// <summary> /// Starts the timeline. /// </summary> public void Start() { _State = TimelineState.Active; }
/// <summary> /// Initializes a new instance of the <see cref="MessageUpdateTimeline"/> class. /// </summary> /// <param name="status">The new <see cref="TimelineState"/>.</param> public MessageUpdateTimeline(TimelineState status) { TimelineState = status; }
/// <summary> /// Resets the timeline. /// </summary> public void Reset() { //Stops the timeline, resets the elapsed time and all events. Stop(); _ElapsedTime = 0; _Events.ForEach(item => item.State = TimelineState.Idle); _State = TimelineState.Idle; }