public void PrepareFrame( FrameData info ) { Playable[] inputs = GetInputs(); // Advance to next clip if necessary time_to_next_clip -= (float)info.deltaTime; if ( time_to_next_clip <= 0.0f ) { current_clip_index++; if ( current_clip_index < inputs.Length ) { AnimationClipPlayable current_clip = inputs[current_clip_index] as AnimationClipPlayable; // Reset the time so that the next clip starts at the correct position inputs[current_clip_index].time = 0; time_to_next_clip = current_clip.clip.length; } else { // Pause when queue is complete state = PlayState.Paused; } } // Adjust the weight of the inputs for ( int a = 0; a < inputs.Length; a++ ) { if ( a == current_clip_index ) { SetInputWeight( a, 1.0f ); } else { SetInputWeight( a, 0.0f ); } } }
public RecordManager(string text) { string[] frameText = text.Split('\n'); numFrames = frameText.Length - 1; //handle the first row string[] first_row_data = frameText[0].Split('|'); string[] robotAIText = first_row_data[0].Split('*'); robotAIData = new RobotAIData[robotAIText.Length]; for(int i = 0; i<robotAIText.Length; i++) { robotAIData[i] = new RobotAIData(robotAIText[i]); } mapData = new MapData(first_row_data[1],first_row_data[2],first_row_data[3]); string[] achievementText = first_row_data[4].Split('*'); achievementData = new AchievementData[achievementText.Length]; for(int i = 0; i<achievementText.Length; i++) { achievementData[i] = new AchievementData(achievementText[i]); } winnerID = Convert.ToInt32(first_row_data[5]); //handle the following frame rows frameData = new FrameData[numFrames]; for(int i = 1; i < frameText.Length; i++) { frameData[i-1] = new FrameData(frameText[i]); } }
void CheckFrames() { Frame frame = Controller.GetFrame (); if (frame.Id != lastId) { FrameValue = new FrameData (frame, Controller); lastId = frame.Id; } }
IntPtr mouseHook_MessageIntercepted(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { FrameData data = new FrameData(); data.Timestamp = Stopwatch.GetTimestamp(); data.Images = new Service.ImageData[0]; NativeMethods.MSLLHOOKSTRUCT mouseStructure = (NativeMethods.MSLLHOOKSTRUCT) Marshal.PtrToStructure(lParam, typeof (NativeMethods.MSLLHOOKSTRUCT)); ContactData contact = new ContactData(); contact.MajorAxis = 10; contact.MinorAxis = 10; contact.Orientation = 0; IntPtr hwnd = NativeMethods.WindowFromPoint(mouseStructure.pt); if (hwnd != IntPtr.Zero) { contact.Hwnd = hwnd; NativeMethods.POINT clientPoint = NativeMethods.ScreenToClient(mouseStructure.pt, hwnd); contact.Position = new Point(clientPoint.X, clientPoint.Y); if (wParam == (IntPtr) NativeMethods.MouseMessages.WM_LBUTTONDOWN) { id++; if (id == int.MaxValue) id = 0; contact.State = Service.ContactState.New; } else if (wParam == (IntPtr) NativeMethods.MouseMessages.WM_LBUTTONUP) { contact.State = Service.ContactState.Removed; } else if (wParam == (IntPtr) NativeMethods.MouseMessages.WM_MOUSEMOVE) { contact.State = Service.ContactState.Moved; } contact.Id = id; contact.Bounds = new Rect(contact.Position.X - (contact.MajorAxis/2), contact.Position.Y - (contact.MinorAxis/2), contact.MajorAxis, contact.MinorAxis); data.Contacts = new[] {contact}; if (contact.State == Service.ContactState.New) contactPressent = true; if (contactPressent) Frame(data); else if (contact.State == Service.ContactState.Removed) contactPressent = false; } } return NativeMethods.CallNextHookEx(hookId, nCode, wParam, lParam); }
void parseJSONObject(string pJsonStr) { //JSONObject atlasObj = new JSONObject(pJsonStr); JsonData atlasObj = JsonMapper.ToObject (pJsonStr); if(atlasObj.GetJsonType() == LitJson.JsonType.None) return; JsonData metaDataObj = atlasObj["meta"]; if(metaDataObj.GetJsonType() == LitJson.JsonType.None) return; m_TextureW = (int)metaDataObj["size"]["w"]; m_TextureH = (int)metaDataObj["size"]["h"]; m_TextureFileName = (string)metaDataObj["image"]; m_AtlasTexture = Resources.Load(m_TextureFileName.Substring(0, m_TextureFileName.IndexOf('.'))) as Texture2D; m_AtlasMaterial= new Material(Shader.Find("Unlit/Transparent")); m_AtlasMaterial.mainTexture = m_AtlasTexture; Debug.Log(m_TextureFileName); Debug.Log(m_AtlasTexture); JsonData framesDataObj = atlasObj["frames"]; if(framesDataObj.GetJsonType() == LitJson.JsonType.None) return; IDictionary framesDataDic = (IDictionary)framesDataObj; foreach(string key in framesDataDic.Keys) { JsonData frameDataObj = framesDataObj[key]; FrameData frameData = new FrameData(); frameData.frameX = (int)frameDataObj["frame"]["x"]; frameData.frameY = (int)frameDataObj["frame"]["y"]; frameData.frameW = (int)frameDataObj["frame"]["w"]; frameData.frameH = (int)frameDataObj["frame"]["h"]; frameData.rotated = (bool)frameDataObj["rotated"]; frameData.trimmed = (bool)frameDataObj["trimmed"]; frameData.spriteSourceX = (int)frameDataObj["spriteSourceSize"]["x"]; frameData.spriteSourceY = (int)frameDataObj["spriteSourceSize"]["y"]; frameData.spriteSourceW = (int)frameDataObj["spriteSourceSize"]["w"]; frameData.spriteSourceH = (int)frameDataObj["spriteSourceSize"]["h"]; frameData.sourceW = (int)frameDataObj["sourceSize"]["w"]; frameData.sourceH = (int)frameDataObj["sourceSize"]["h"]; m_FramesList.Add(key, frameData); } Debug.Log("parseJSONObject"); }
public FrameData CollectFrameData() { _visibleMaterials.Clear (); _visibleTextures.Clear (); //Debug.Log(string.Format("creating frame data. {0}", Time.frameCount)); _currentFrame = new FrameData (); _currentFrame._frameCount = Time.frameCount; _currentFrame._frameDeltaTime = Time.deltaTime; _currentFrame._frameRealTime = Time.realtimeSinceStartup; _currentFrame._frameStartTime = Time.time; MeshRenderer[] meshRenderers = UnityEngine.Object.FindObjectsOfType(typeof(MeshRenderer)) as MeshRenderer[]; foreach (MeshRenderer mr in meshRenderers) { if (mr.isVisible) { GameObject go = mr.gameObject; if (_meshLut.AddMesh(go)) { _currentFrame._frameMeshes.Add (go.GetInstanceID()); _nameLut[go.GetInstanceID()] = go.name; // Debug.Log(string.Format("CollectFrameData(): adding game object. {0}, name {1}, name count {2}", // go.GetInstanceID(), // go.name, // _nameLut.Count)); foreach (var mat in mr.sharedMaterials) { AddVisibleMaterial(mat, mr.gameObject); if (mat != null) { if (Application.isEditor) { List<Texture> textures = UsEditorQuery.GetAllTexturesOfMaterial(mat); if (textures != null) { foreach (var texture in textures) { AddVisibleTexture(texture, mat); } } } else { AddVisibleTexture(mat.mainTexture, mat); } } } } } } _frames.Add (_currentFrame); return _currentFrame; }
/// <summary> /// Take a Dictionary of pins and write it to an XML file /// </summary> /// <param name="pinMap">A Dictionary of frame X and Y rotations to a list of pins on that frame</param> /// <param name="outfile">The file to write the formatted XML to</param> public void Pack(Dictionary<Tuple<int, int>, List<Pin>> pinMap, string outfile) { List<FrameData> frames = new List<FrameData>(); HashSet<DissectionPinData> pins = new HashSet<DissectionPinData>(); int nextId = 0; foreach (var pair in pinMap) { List<Pin> framePins = pair.Value; // All the pins on this frame Tuple<int, int> frame = pair.Key; // The 2D rotation of this frame FrameData frameData = new FrameData(); // Data for the frame to be represented in XML frameData.Rotation = new Vector3(frame.Item1, frame.Item2, 0.0f); List<FramePinData> framePinDatas = new List<FramePinData>(); // The links between this frame and its pins foreach (Pin pin in framePins) { DissectionPinData data = ConvertToData(pin); if (pins.Add(data)) { // This pin doesn't already exist, so give it an id data.Id = nextId++; } else { // This pin is in the HashSet so get the original instance data = pins.Single((DissectionPinData x) => { return x.Equals(data); }); } framePinDatas.Add(new FramePinData(new Vector2(pin.X, pin.Y), data.Id)); } frameData.Pins = framePinDatas.ToArray(); frames.Add(frameData); } PinContainer container = new PinContainer(); container.Frames = frames.ToArray(); container.Pins = pins.ToArray(); WriteXml(container, outfile); }
/// <summary> /// Initializes a new instance of the <see cref="Frame"/> class. /// </summary> /// <param name="clip"></param> internal Frame(Clip clip) : this() { Contract.Requires(clip != null); this.clip = clip; this.video = new FrameData<IBitmap>(clip.VideoTracks.Count); this.audio = new FrameData<ISegment>(clip.AudioTracks.Count); for (int i = 0; i < this.video.Count; ++i) { var track = clip.VideoTracks[i]; this.video[i] = track.Format.CreateBitmap(track.Dimensions); } for (int i = 0; i < this.audio.Count; ++i) { var track = clip.AudioTracks[i]; this.audio[i] = null; } }
public static IDictionary<string, FrameData[]> GetData(SpriterEntity entity, int interval) { IDictionary<string, FrameData[]> data = new Dictionary<string, FrameData[]>(); foreach (SpriterAnimation anim in entity.Animations) { int length = (int)Math.Ceiling(anim.Length / interval); FrameData[] animData = new FrameData[length]; for (int i = 0; i < animData.Length; ++i) { float time = i * interval; if (time > anim.Length) time = anim.Length; FrameData fd = new FrameData(); SpriterProcessor.UpdateFrameData(fd, anim, time); animData[i] = fd; } data[anim.Name] = animData; } return data; }
public void TestOpenSaveFrameData() { var frameData = new FrameData(); var frame = new Frame(); frameData.Frames.Add(frame); var stroke = new Stroke(); stroke.Add(new Point(0, 0)); stroke.Add(new Point(100, 100)); frame.Strokes.Add(stroke); System.IO.MemoryStream mem = new System.IO.MemoryStream(); Obf.OpenBinaryFormat f = Obf.OpenBinaryFormat.ToMemory(mem); frameData.Save(f); var bytes = mem.ToArray(); f.Close(); f = Obf.OpenBinaryFormat.FromBytes(bytes); var newFrameData = new FrameData(); newFrameData.Read(f); f.Close(); Assert.True(newFrameData.Frames.Count == 1); frame = newFrameData.Frames[0]; Assert.True(frame.Strokes.Count == 1); stroke = frame.Strokes[0]; Assert.True(stroke.Count == 2); var p1 = stroke[0]; Assert.True(p1.X == 0); Assert.True(p1.Y == 0); var p2 = stroke[1]; Assert.True(p2.X == 100); Assert.True(p2.Y == 100); }
internal FrameEventArgs(FrameData data, IntPtr relativeTo) { this.data = data; this.relativeTo = relativeTo; }
// --------------------------------------------------------------------------- //No explicit destructors in C# // --------------------------------------------------------------------------- public bool ReadFromFile(String FileName) { FileStream fs = null; BinaryReader SourceFile = null; byte[] Data = new byte[MAX_MPEG_FRAME_LENGTH * 2]; bool result = false; FResetData(); // At first search for tags, then search for a MPEG frame and VBR data // This part of code rewritten to add more flexibility (no need to have 3 tags to be able to read file info xD) //if ( (FID3v2.ReadFromFile(FileName)) && (FID3v1.ReadFromFile(FileName)) && (FAPEtag.ReadFromFile(FileName)) ) FID3v2.ReadFromFile(FileName); FID3v1.ReadFromFile(FileName); APEtag.ReadFromFile(FileName); try { // Open file, read first block of data and search for a frame fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); SourceFile = new BinaryReader(fs); FFileLength = (int)fs.Length; fs.Seek(FID3v2.Size, SeekOrigin.Begin); Data = SourceFile.ReadBytes(Data.Length); FFrame = FindFrame(Data, ref FVBR); // Try to search in the middle if no frame at the beginning found if ( ! FFrame.Found ) { fs.Seek((int)System.Math.Floor((decimal)(FFileLength - FID3v2.Size) / 2),SeekOrigin.Begin); Data = SourceFile.ReadBytes(Data.Length); FFrame = FindFrame(Data, ref FVBR); } // Search for vendor ID at the end if CBR encoded if ( (FFrame.Found) && (! FVBR.Found) ) { if (! FID3v1.Exists) fs.Seek(FFileLength - Data.Length, SeekOrigin.Begin); else fs.Seek(FFileLength - Data.Length - 128, SeekOrigin.Begin); Data = SourceFile.ReadBytes(Data.Length); FVendorID = FindVendorID(Data, (ushort)(FFrame.Size * 5)); } result = true; } catch (Exception e) { System.Console.WriteLine(e.StackTrace); result = false; } if (!FFrame.Found) FResetData(); if (SourceFile != null) SourceFile.Close(); if (fs != null) fs.Close(); return result; }
void SetAnimationFrame(int frameNumber) { foreach(KeyValuePair<int, SetFrameDelegate> pair in _setFrameDelegates) { if(pair.Key == frameNumber && pair.Value != null) pair.Value(); } currentFrameNumber = frameNumber; currentFrameData = currentAnimation.frames[currentFrameNumber]; }
// --------------------------------------------------------------------------- private byte GetPadding(FrameData Frame) { byte result; // Get frame padding if (Frame.PaddingBit) if (MPEG_LAYER_I == Frame.LayerID) result = 4; else result = 1; else result = 0; return result; }
// --------------------------------------------------------------------------- private byte GetVBRDeviation(FrameData Frame) { byte result; // Calculate VBR deviation if (MPEG_VERSION_1 == Frame.VersionID) if (Frame.ModeID != MPEG_CM_MONO) result = 36; else result = 21; else if (Frame.ModeID != MPEG_CM_MONO) result = 21; else result = 13; return result; }
// --------------------------------------------------------------------------- private void DecodeHeader(byte[] HeaderData, ref FrameData Frame) { // Decode frame header data Array.Copy(HeaderData, Frame.Data, 4); Frame.VersionID = (byte)((HeaderData[1] >> 3) & 3); Frame.LayerID = (byte)((HeaderData[1] >> 1) & 3); Frame.ProtectionBit = (HeaderData[1] & 1) != 1; Frame.BitRateID = (ushort)(HeaderData[2] >> 4); Frame.SampleRateID = (ushort)((HeaderData[2] >> 2) & 3); Frame.PaddingBit = ( ((HeaderData[2] >> 1) & 1) == 1); Frame.PrivateBit = ( (HeaderData[2] & 1) == 1); Frame.ModeID = (byte)((HeaderData[3] >> 6) & 3); Frame.ModeExtensionID = (byte)((HeaderData[3] >> 4) & 3); Frame.CopyrightBit = ( ((HeaderData[3] >> 3) & 1) == 1); Frame.OriginalBit = ( ((HeaderData[3] >> 2) & 1) == 1); Frame.EmphasisID = (byte)(HeaderData[3] & 3); }
// --------------------------------------------------------------------------- private ushort GetBitRate(FrameData Frame) { // Get bit rate return MPEG_BIT_RATE[Frame.VersionID, Frame.LayerID, Frame.BitRateID]; }
public sealed override void PushDirectory(DirectoryInfoBase directory) { // copy the current frame FrameData frame = Frame; if (IsStackEmpty()) { // initializing frame.SegmentGroupIndex = -1; frame.SegmentGroup = Pattern.StartsWith; } else if (Frame.IsNotApplicable) { // no change } else if (IsStartingGroup()) { if (!TestMatchingSegment(directory.Name)) { // nothing down this path is affected by this pattern frame.IsNotApplicable = true; } else { // starting path incrementally satisfied frame.SegmentIndex += 1; } } else if (!IsStartingGroup() && directory.Name == "..") { // any parent path segment is not applicable in ** frame.IsNotApplicable = true; } else if (!IsStartingGroup() && !IsEndingGroup() && TestMatchingGroup(directory)) { frame.SegmentIndex = Frame.SegmentGroup.Count; frame.BacktrackAvailable = 0; } else { // increase directory backtrack length frame.BacktrackAvailable += 1; } if (frame.InStem) { frame.StemItems.Add(directory.Name); } while ( frame.SegmentIndex == frame.SegmentGroup.Count && frame.SegmentGroupIndex != Pattern.Contains.Count) { frame.SegmentGroupIndex += 1; frame.SegmentIndex = 0; if (frame.SegmentGroupIndex < Pattern.Contains.Count) { frame.SegmentGroup = Pattern.Contains[frame.SegmentGroupIndex]; } else { frame.SegmentGroup = Pattern.EndsWith; } // We now care about the stem frame.InStem = true; } PushDataFrame(frame); }
public override void ProcessFrame(Playable playable, FrameData info, object playerData) { }
bool DetectDiscontinuity(Playable playable, FrameData info) { return(Math.Abs(playable.GetTime() - playable.GetPreviousTime() - info.m_DeltaTime * info.m_EffectiveSpeed) > DiscreteTime.tickValue); }
public void AddFrame(int streamId, FrameData frame) { var clone = DeepClone(frame); m_streamData[streamId].Queue.Add(clone); }
// Called each frame while the state is set to Play public override void PrepareFrame(Playable playable, FrameData info) { Update?.Invoke(); }
private static async void ProcessReceive(TcpTransport serverTransport, FrameData frameData, IMessageProcessor messageProcessor) { byte[] responseExtention = null; byte[] responseContent = null; byte responseCode = 0; try { ResponseBase response = null; if (frameData.TitleBytes == null || frameData.TitleBytes.Length == 0) { response = new ErrorResponse((byte)ResponseCode.SERVICE_TITLE_ERROR); } if (messageProcessor == null) { response = new ErrorResponse((byte)ResponseCode.SERVICE_NOT_FOUND); } if (response == null) { if (NetworkSettings.ServerProcessMode == CommunicationMode.Sync) { var responseTask = messageProcessor.Process(frameData); responseTask.Wait(); response = responseTask.Result; } else { response = await messageProcessor.Process(frameData); } } responseExtention = response.HeaderExtentionBytes ?? FrameFormat.EmptyBytes; responseContent = response.ContentBytes ?? FrameFormat.EmptyBytes; responseCode = (byte)response.Code; } catch { responseExtention = FrameFormat.EmptyBytes; responseContent = FrameFormat.EmptyBytes; responseCode = (byte)ResponseCode.SERVER_INTERNAL_ERROR; } try { var messageByteCount = FrameFormat.ComputeFrameByteCount(responseExtention, FrameFormat.EmptyBytes, responseContent); var sendBuffer = serverTransport.SendBufferCache.Get(messageByteCount); FrameFormat.FillFrame(sendBuffer, responseExtention, FrameFormat.EmptyBytes, responseContent, responseCode, frameData.MessageId); //if (NetworkSettings.ServerTcpSendMode == TcpSendMode.Async) //{ // serverTransport.SendAsync(sendBuffer, messageByteCount); //} //else //{ serverTransport.Send(sendBuffer, messageByteCount); //} serverTransport.SendBufferCache.Cache(sendBuffer); } catch { serverTransport.Close(); } }
internal override void OnReceiveMessage(TcpTransport serverTransport, FrameData frameData) { ProcessReceive(serverTransport, frameData, MessageProcessor); }
public static FrameData[] GetFrames(AtlasData[] atlasData, Texture texture) { if ((atlasData == null) || (texture == null)) { Debug.LogError(" can't find atlas data or texture, please check it!!"); return new FrameData[] { }; } Vector2 texSize = Vector2.zero; if (Vector2.Equals(texSize, Vector2.zero) && texture != null) texSize = new Vector2(texture.width, texture.height); // convert atlasData to frames FrameData[] frames = new FrameData[atlasData.Length]; for (int a = 0; a < atlasData.Length; a++) { AtlasData data = atlasData[a]; FrameData frame = new FrameData(); frame.name = data.name; frame.offset = Vector2.zero; frame.size = data.frameSize; Vector2 vOffset = new Vector2(data.offset.x / frame.size.x, data.offset.y / frame.size.y); Vector2 vSize = new Vector2(data.size.x / frame.size.x, data.size.y / frame.size.y); Vector3 tl = new Vector3(((1f / 2f) * -1) + vOffset.x, (1f / 2f) - vOffset.y, 0); frame.vertices = new Vector3[] { tl, tl + new Vector3(vSize.x,0,0), tl + new Vector3(vSize.x,vSize.y * -1,0), tl + new Vector3(0,vSize.y * -1,0) }; frame.imageSize = data.frameSize; frame.uv = new Vector2[4]; float sx = data.position.x / texSize.x; float sy = 1 - ((data.position.y + data.size.y) / texSize.y); float scx = data.size.x / texSize.x; float scy = data.size.y / texSize.y; if (data.rotated) { sy = 1 - ((data.position.y + data.size.x) / texSize.y); scx = data.size.y / texSize.x; scy = data.size.x / texSize.y; frame.uv[3] = new Vector2(sx, sy + scy); frame.uv[0] = new Vector2(sx + scx, sy + scy); frame.uv[1] = new Vector2(sx + scx, sy); frame.uv[2] = new Vector2(sx, sy); } else { frame.uv[0] = new Vector2(sx, sy + scy); frame.uv[1] = new Vector2(sx + scx, sy + scy); frame.uv[2] = new Vector2(sx + scx, sy); frame.uv[3] = new Vector2(sx, sy); } frames[a] = frame; } return frames; }
public override void ProcessFrame(Playable playable, FrameData info, object playerData) { if (!m_pending) { return; } var output = playerData as AudioSource; if (output == null || clip == null) { m_pending = false; return; } if (audioClip != null) { output.PlayOneShot(audioClip); m_pending = false; } else { var provider = talk.provider; if (provider != null) { provider.output = output; if (provider.Play(talk)) { var rtc = (RemoteTalkClip)clip.asset; rtc.audioClip.defaultValue = null; m_pending = false; #if UNITY_EDITOR if (provider.exportAudio) { m_exporting = true; if (RemoteTalkTrack.pauseWhenExport && director.state == PlayState.Playing) { // note: // on 2017.x, PlayableDirector.Pause() seems don't pause playback if not playing in editor. // so, emulate pause by updating PlayableDirector.time. m_timePaused = director.time; director.Pause(); } } #endif } } } #if UNITY_EDITOR if (m_exporting && m_timePaused > NullTime) { if (Math.Abs(director.time - m_timePaused) < MaxAllowedDelta) { director.time = m_timePaused; // see above note } else { m_timePaused = NullTime; } } #endif }
public override void OnBehaviourPause(Playable playable, FrameData info) { Time.timeScale = 1; }
public override void OnBehaviourPlay(Playable playable, FrameData info) { Time.timeScale = 1 - (1 - timeScale) * info.weight; }
// --------------------------------------------------------------------------- private byte GetCoefficient(FrameData Frame) { byte result; // Get frame size coefficient if (MPEG_VERSION_1 == Frame.VersionID) if (MPEG_LAYER_I == Frame.LayerID) result = 48; else result = 144; else if (MPEG_LAYER_I == Frame.LayerID) result = 24; else if (MPEG_LAYER_II == Frame.LayerID) result = 144; else result = 72; return result; }
// Called when the state of the playable is set to Play(Timeline上で呼ばれたとき) public override void OnBehaviourPlay(Playable playable, FrameData info) { MEM.SetIsMovieEvent(false); }
// --------------------------------------------------------------------------- private ushort GetSampleRate(FrameData Frame) { // Get sample rate return MPEG_SAMPLE_RATE[Frame.VersionID, Frame.SampleRateID]; }
// Called when the state of the playable is set to Paused public override void OnBehaviourPause(Playable playable, FrameData info) { }
// --------------------------------------------------------------------------- private ushort GetFrameLength(FrameData Frame) { ushort Coefficient; ushort BitRate; ushort SampleRate; ushort Padding; // Calculate MPEG frame length Coefficient = GetCoefficient(Frame); BitRate = GetBitRate(Frame); SampleRate = GetSampleRate(Frame); Padding = GetPadding(Frame); return (ushort)(Math.Floor((double)Coefficient * (double)BitRate * 1000 / SampleRate) + Padding); }
public static void Receive(FrameData data) { //Debug.Log("Connection Receive:" + data.ToString()); Game.Instance.frameBuffer.AddOneFrame(data); }
// --------------------------------------------------------------------------- private FrameData FindFrame(byte[] Data, ref VBRData oVBR) { byte[] HeaderData = new byte[4]; FrameData result = new FrameData(); // Search for valid frame //FillChar(result, sizeof(result), 0); result.Found = false; result.Position = 0; result.Size = 0; result.Xing = false; Array.Clear(result.Data,0,result.Data.Length); result.VersionID = 0; result.LayerID = 0; result.ProtectionBit = false; result.BitRateID = 0; result.SampleRateID = 0; result.PaddingBit = false; result.PrivateBit = false; result.ModeID = 0; result.ModeExtensionID = 0; result.CopyrightBit = false; result.OriginalBit = false; result.EmphasisID = 0; Array.Copy(Data, HeaderData, 4); for (uint iterator=0; iterator <= Data.Length - MAX_MPEG_FRAME_LENGTH; iterator++) { // Decode data if frame header found if ( IsFrameHeader(HeaderData) ) { DecodeHeader(HeaderData, ref result); // Check for next frame and try to find VBR header if ( ValidFrameAt((ushort)(iterator + GetFrameLength(result)), Data) ) { result.Found = true; result.Position = (int)iterator; result.Size = GetFrameLength(result); result.Xing = IsXing((ushort)(iterator + 4), Data); oVBR = FindVBR((ushort)(iterator + GetVBRDeviation(result)), Data); break; } } // Prepare next data block HeaderData[0] = HeaderData[1]; HeaderData[1] = HeaderData[2]; HeaderData[2] = HeaderData[3]; HeaderData[3] = Data[iterator + 4]; } return result; }
public void Frame(FrameData data) { logic.DispatchFrame(data); }
public bool Equals(FrameData p) { return p.CurrentFrame.Id == CurrentFrame.Id; }
private static void ReceiveCallback(IAsyncResult ar) { var tcpTransport = (TcpTransport)ar.AsyncState; if (tcpTransport == null) { return; } if (tcpTransport._state != 1) { return; } int readCount = -1; try { readCount = tcpTransport._socket.EndReceive(ar); } catch (Exception ex) { LogAgent.Warn("tcpTransport ReceiveCallback,socket EndReceive error", ex); } if (readCount == -1) { tcpTransport.Close(); return; } if (readCount == 0) { LogAgent.Info("tcpTransport ReceiveCallback,socket receive size:0,remote socket is closed"); tcpTransport.Close(false); return; } var receiveProcessor = tcpTransport._receiveProcessor; try { var step = receiveProcessor.CheckCurrentStep(readCount); if (step == -1) { throw new RpcException("tcpTransport ReceiveCallback,receiveProcessor CheckCurrentStep error"); } if (step == 0) { tcpTransport.BeginNewReceive(false); return; } } catch (Exception ex) { tcpTransport.Close(); LogAgent.Warn("tcpTransport ReceiveCallback,tcpTransport BeginNewReceive error", ex); return; } try { FrameData receiveData = receiveProcessor.GetCurrentReceiveData(); tcpTransport.BeginNewReceive(true); tcpTransport.OnReceive(receiveData); } catch (Exception ex) { tcpTransport.Close(); LogAgent.Warn("tcpTransport ReceiveCallback,tcpTransport BeginNewReceive error", ex); return; } }
public override void PrepareFrame( FrameData info ) { Debug.Log( "Preparing " + name ); }
private void OnReceive(FrameData messageData) { _transportHost.ReceiveMessage(this, messageData); }
public override void OnBehaviourPlay(Playable playable, FrameData info) { isPrompted = false; }
// Called when the state of the playable is set to Play public override void OnBehaviourPlay(Playable playable, FrameData info) { time = 0; Duration = (float)playable.GetDuration(); }
// Use this for initialization void Start() { m_maxBufferLength = (int)(m_maxBufferSizeSec / m_stepSizeSec)+1; // buffer size for all timestates, with padding if (!m_cloned) { // Debug.Log(m_maxBufferLength); m_startTime = GlobalTime.getTime(); m_endTime = m_startTime - 1.0f; m_buffer = new List<TimeState>(m_maxBufferLength); } m_renderers = transform.GetComponentsInChildren<Renderer>(); m_frameData = transform.GetComponent<FrameData>(); }
public override void ProcessFrame(Playable playable, FrameData info, object playerData) { Time.timeScale = 1 - (1 - timeScale) * info.weight; }
ParseFrameResult ParseFrame(List <byte> buffer, out FrameData frame) { frame = null; if (buffer.Count < 2) { return(ParseFrameResult.FrameIncomplete); } int p = 0; byte firstByte = buffer [p++]; byte secondByte = buffer [p++]; bool final = (firstByte & FINALBIT) > 0; bool reserved1 = (firstByte & RESERVEDBIT1) > 0; bool reserved2 = (firstByte & RESERVEDBIT2) > 0; bool reserved3 = (firstByte & RESERVEDBIT3) > 0; OpCode opCode = (OpCode)(firstByte & OP_CODE_MASK); bool masked = (secondByte & MASKBIT) > 0; long payloadLength64 = (secondByte & PAYLOAD_LENGTH_MASK); if (payloadLength64 > MAX_PAYLOAD_WITHOUT_EXTENDED_LENGTH_FIELD) { int extendedPayloadLengthSize; if (payloadLength64 == PAYLOAD_WITH_TWO_BYTE_EXTENDED_FIELD) { extendedPayloadLengthSize = 2; } else { extendedPayloadLengthSize = 8; } if (buffer.Count - p < extendedPayloadLengthSize) { return(ParseFrameResult.FrameIncomplete); } payloadLength64 = 0; for (int i = 0; i < extendedPayloadLengthSize; ++i) { payloadLength64 <<= 8; payloadLength64 |= buffer [p++]; } } const long maxPayloadLength = 0x7FFFFFFFFFFFFFFF; int maskingKeyLength = masked ? MASKING_KEY_WIDTH_IN_BYTES : 0; if (payloadLength64 > maxPayloadLength || payloadLength64 + maskingKeyLength > int.MaxValue) { Debug.LogError(string.Format("WebSocket frame length too large: {0} bytes", payloadLength64)); return(ParseFrameResult.FrameError); } int payloadLength = (int)payloadLength64; if ((buffer.Count - p) < maskingKeyLength + payloadLength) { return(ParseFrameResult.FrameIncomplete); } if (masked) { int maskingKey = p; int payload = p + MASKING_KEY_WIDTH_IN_BYTES; for (int i = 0; i < payloadLength; ++i) { buffer [payload + i] ^= buffer [maskingKey + (i % MASKING_KEY_WIDTH_IN_BYTES)]; // Unmask the payload. } } frame = new FrameData(); frame.opCode = opCode; frame.final = final; frame.reserved1 = reserved1; frame.reserved2 = reserved2; frame.reserved3 = reserved3; frame.masked = masked; frame.payload = p + maskingKeyLength; frame.payloadLength = payloadLength; frame.end = p + maskingKeyLength + payloadLength; return(ParseFrameResult.FrameOK); }
void HandleFrame(FrameData data) { IEnumerable<ContactHandler> handlers = windowsMap .SelectMany(pair => pair.Value .Where(handler => handler.ReceiveEmptyFrames || pair.Key == IntPtr.Zero || data.Contacts.Any(c => c.Hwnd.Equals(pair.Key)))); foreach (ContactHandler handler in handlers) handler.HandleFrame(data); }
// Called each frame the mixer is active, after inputs are processed public override void ProcessFrame(Playable handle, FrameData info, object playerData) { Volume volume = playerData as Volume; if (volume == null) { return; } DepthOfField m_depthOfField; var profile = Application.isPlaying ? volume.profile : volume.sharedProfile; if (!profile.Has <DepthOfField>()) { return; } var count = handle.GetInputCount(); //Short loop int activeClipsCount = 0; for (var i = 0; i < count; i++) { var inputHandle = handle.GetInput(i); var weight = handle.GetInputWeight(i); if (weight > 0) { activeClipsCount += 1; } } if (activeClipsCount == 0) { volume.weight = 0; return; } volume.weight = 1; float newFocusDistance = 0f; float newAperture = 0f; float newFocalLength = 0f; for (var i = 0; i < count; i++) { var inputHandle = handle.GetInput(i); var weight = handle.GetInputWeight(i); if (inputHandle.IsValid() && inputHandle.GetPlayState() == PlayState.Playing && weight > 0) { var data = ((ScriptPlayable <DOFPlayable>)inputHandle).GetBehaviour(); if (data != null) { newFocusDistance += data.focusDistance * weight; newAperture += data.aperture * weight; newFocalLength += data.focalLength * weight; } } } profile.TryGet <DepthOfField>(out m_depthOfField); m_depthOfField.focusDistance.value = newFocusDistance; }
private FrameData ProcessFrameData(DepthImageFrame depthFrame) { // get the raw data from kinect with the depth for every pixel short[] rawDepthData = new short[depthFrame.PixelDataLength]; depthFrame.CopyPixelDataTo(rawDepthData); // use depthFrame to create the image to display on-screen // depthFrame contains color information for all pixels in image // Height x Width x 4 (Red, Green, Blue, empty byte) byte[] pixels = new byte[depthFrame.Height * depthFrame.Width * 4]; // Bgr32 - Blue, Green, Red, empty byte // Bgra32 - Blue, Green, Red, transparency // You must set transparency for Bgra as .NET defaults a byte to 0 = fully transparent // hardcoded locations to Blue, Green, Red, Alpha (BGRA) index positions const int BlueIndex = 0; const int GreenIndex = 1; const int RedIndex = 2; const int AlphaIndex = 3; int farthestLayer = 0; int closestLayer = 10; // loop through all distances // pick a RGB color based on distance for (int depthIndex = 0, colorIndex = 0; depthIndex < rawDepthData.Length && colorIndex < pixels.Length; depthIndex++, colorIndex += 4) { // get the player (requires skeleton tracking enabled for values) int player = rawDepthData[depthIndex] & DepthImageFrame.PlayerIndexBitmask; // gets the depth value int depth = rawDepthData[depthIndex] >> DepthImageFrame.PlayerIndexBitmaskWidth; // get the layer from the depth value int layer = DepthToLayer((float)depth); // color all silhouettes if (player > 0) { //byte intensity = CalculateIntensityFromDepth(depth); //pixels[colorIndex + BlueIndex] = (byte)(silhouetteColorR + (255 - silhouetteColorR) * (1 - ((float)intensity / 255.0))); //pixels[colorIndex + GreenIndex] = (byte)(silhouetteColorG + (255 - silhouetteColorG) * (1 - ((float)intensity / 255.0))); //pixels[colorIndex + RedIndex] = (byte)(silhouetteColorB + (255 - silhouetteColorB) * (1 - ((float)intensity / 255.0))); pixels[colorIndex + BlueIndex] = silhouetteColorR; pixels[colorIndex + GreenIndex] = silhouetteColorG; pixels[colorIndex + RedIndex] = silhouetteColorB; pixels[colorIndex + AlphaIndex] = 255; if (layer < closestLayer) { closestLayer = layer; } if (layer > farthestLayer) { farthestLayer = layer; } } else { pixels[colorIndex + BlueIndex] = 0; pixels[colorIndex + GreenIndex] = 0; pixels[colorIndex + RedIndex] = 0; pixels[colorIndex + AlphaIndex] = 0; } } FrameData ret = new FrameData(pixels, (farthestLayer + closestLayer) / 2); return ret; }
internal void HandleFrame(FrameData frame) { EventHandler<FrameEventArgs> eventHandler = Frame; if(eventHandler != null) eventHandler(this, new FrameEventArgs(frame, RelativeTo)); }
// Called each frame while the state is set to Play public override void PrepareFrame(Playable playable, FrameData info) { }
internal void DispatchFrame(FrameData data) { foreach (ContactData contact in data.Contacts) HandleContact(contact, data.Timestamp); HandleFrame(data); }
/// <summary> /// 开启工作流程 /// </summary> private void StartWork() { switch (PresetInfo.CurrentOperateType) { case OperateType.Gather: _currentFrameData = _sqlPresenter.GetFrameDataFromDb(); switch (_currentFrameData.Type) { case FrameType.None: _view.CommunicateMessageShow("数据库检索已完成"); // MessageBox.Show("数据采集已完成!", "提示"); break; case FrameType.ControlGather: _timerSendDelay.Interval = PresetInfo.FrameSendDelay; _timerSendDelay.Start(); break; default: _view.CommunicateMessageShow("未知错误"); break; } break; case OperateType.Detect: case OperateType.Detect2: _currentFrameData = _poleDetectPresenter.GetPoleList(); switch (_currentFrameData.Type) { case FrameType.ControlGather: _commucationFacade.SendDataFrame(_currentFrameData); break; case FrameType.None: var electrodeInspect = _sqlPresenter.SecondRroundInspect(); if (electrodeInspect.NiceId == -1) { _view.CommunicateMessageShow("电极检测完毕,无错误"); _view.InitPoleSelection(new List <int>()); } else { var builder = new StringBuilder(); electrodeInspect.BadList.ForEach(id => { builder.Append(id + " "); }); _view.CommunicateMessageShow(string.Format("电极检测完毕,坏电极个数为:{0},结果如下:", electrodeInspect.BadList.Count)); _view.CommunicateMessageShow("状态最佳电极:" + electrodeInspect.NiceId); // + " 坏电极:" + builder if (electrodeInspect.BadList.Count > 32) { _view.CommunicateMessageShow("电极检测完毕,坏电极较多,程序终止"); return; } if (_poleDetectPresenter.RoundNum == 2) //第二轮从数据库获取不满足阈值的电极 { _view.CommunicateMessageShow("第二轮检测结束"); _view.InitPoleSelection(new List <int>(electrodeInspect.BadList)); return; } else { _view.CommunicateMessageShow("第一轮检测结束, 已开始第二轮检测"); } //第二轮检测初始化 _poleDetectPresenter.SetSecondRoundData(electrodeInspect); PresetInfo.CurrentOperateType = OperateType.Detect2; StartWork(); } break; default: _view.CommunicateMessageShow("未知错误"); break; } break; case OperateType.Debug: break; default: throw new ArgumentOutOfRangeException(); } }