/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); frameinfo = new FrameInfo(); text = new Text(GraphicsDevice, Services, "Content", "Arial"); model = new SLModel(GraphicsDevice, Services, "Content", "earth"); model.Para.BasePara.space = 200; model.Para.BasePara.speed3D = Vector3.Backward * 3f; model.Para.BasePara.rotationspeed3D = Vector3.UnitY * 0.3f; model.ProjectionType = ProjectionType.Perspective; model.globalCamera.Position = Vector3.UnitZ * 200; model.globalCamera.NearPlane = 1.0f; model.globalCamera.FarPlane = 1000f; audio = new SLAudio(SLConfig["content"] + "StiLib", SLConfig["content"] + "SLMWB", SLConfig["content"] + "SLSWB", SLConfig["content"] + "SLSB"); audiolistener = new AudioListener() { Forward = model.globalCamera.Direction, Position = model.globalCamera.Position, Up = model.globalCamera.Up, Velocity = Vector3.Zero }; audio.Listeners.Add(audiolistener); audioemitter = new AudioEmitter() { DopplerScale = 1.0f, Forward = Vector3.Forward, Position = model.BasePara.center, Up = Vector3.Up, Velocity = model.BasePara.speed3D }; //audio.Update(); audio.Play("Buzz", audioemitter); }
public bool ShouldUpdate (FrameInfo frameInfo) { if (_lastDrawNumberOfUpdate == frameInfo.DrawNumber) return false; _lastDrawNumberOfUpdate = frameInfo.DrawNumber; return true; }
public override void onEnterFrame(int frame) { setAnimationInfo(); owner.setAnimationFrame(frame, animationInfo.texRow); if (frame < animationInfo.frames.Length) { frameInfo = animationInfo.frames[frame]; if (owner.activeWeapon != null) { owner.gripPoint = frameInfo.gripPoint; owner.activeWeapon.setStance(frameInfo.stance); owner.activeWeapon.frameRotation = frameInfo.rotation; } } }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); frameinfo = new FrameInfo(); text = new Text(GraphicsDevice, Services, "Content", "Arial"); point = new Primitive(GraphicsDevice, PrimitivePara.Point(Vector3.UnitX,Color.White)); line = new Primitive(GraphicsDevice,PrimitivePara.Line(Vector3.UnitX*3, -Vector3.UnitX*5,Color.Blue,Vector3.UnitY*8,Color.Red)); linestrip = new Primitive(GraphicsDevice,PrimitivePara.LineStrip(true,Vector3.Zero, Color.Yellow,-Vector3.UnitX*7,Vector3.UnitY*6,Vector3.UnitX*4,-Vector3.UnitY*2)); triangle = new Primitive(GraphicsDevice,PrimitivePara.Triangle(-Vector3.UnitY*2,Color.Tomato,-Vector3.UnitX,Vector3.UnitX,Vector3.UnitY,true)); rectangle = new Primitive(GraphicsDevice,PrimitivePara.Rectangle(Vector3.UnitY*2,Color.MistyRose,4f,3f,true)); quadrate = new Primitive(GraphicsDevice,PrimitivePara.Quadrate(Vector3.UnitX*4,Color.Chocolate,3f,true)); ellipse = new Primitive(GraphicsDevice,PrimitivePara.Ellipse(4f,3f,Color.Purple,Vector3.UnitY*5,Color.TransparentWhite,100,true)); circle = new Primitive(GraphicsDevice,PrimitivePara.Circle(3f,Color.Tan,-Vector3.UnitY*8,Color.Green,100,true)); grid = new Primitive(GraphicsDevice,PrimitivePara.Grid(1.0f,1.5f,12,15,-Vector3.UnitY*3,Color.LightSalmon,Color.PowderBlue)); }
public override void onEnterFrame(int frame) { //setAnimationInfo(); frameIndex.X = animationInfo.texColumn + curFrame; frameIndex.Y = animationInfo.texRow; owner.setAnimationFrame(frameIndex.X, frameIndex.Y); frameInfo = animationInfo.frames[frame]; if (owner.activeWeapon != null) { owner.gripPoint = frameInfo.gripPoint; owner.activeWeapon.setStance(frameInfo.stance); owner.activeWeapon.frameRotation = frameInfo.rotation; } if (frameInfo.attackPoints != null && frameInfo.attackPoints.Count > 0) { attackBoxes = new List<Rectangle>(); foreach (Rectangle attackPoint in frameInfo.attackPoints) { Point offset = new Point(attackPoint.X, attackPoint.Y); float s = (float)(Math.Sin(owner.bodyRotation)); float c = (float)(Math.Cos(owner.bodyRotation)); Point newOffset = new Point((int)(offset.X * c - offset.Y * s), (int)(offset.X * s + offset.Y * c)); damageRect = new Rectangle(); damageRect.Width = attackPoint.Width; damageRect.Height = attackPoint.Height; damageRect.X = owner.hitBox.Center.X + newOffset.X - damageRect.Width / 2; damageRect.Y = owner.hitBox.Center.Y + newOffset.Y - damageRect.Height / 2; attackBoxes.Add(damageRect); } DamageInfo damageInfo; if (owner.activeWeapon != null) { damageInfo = new DamageInfo(owner, (int)(owner.activeWeapon.damage * owner.damageFactor), this.attackBoxes); } else { damageInfo = new DamageInfo(owner, (int)(frameInfo.attackDamage * owner.damageFactor), this.attackBoxes); } owner.onAttack(damageInfo); attackBoxes.Clear(); } }
private void allocUnwindInfo(byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind) { Debug.Assert(FrameInfoFlags.Filter == (FrameInfoFlags)CorJitFuncKind.CORJIT_FUNC_FILTER); Debug.Assert(FrameInfoFlags.Handler == (FrameInfoFlags)CorJitFuncKind.CORJIT_FUNC_HANDLER); FrameInfoFlags flags = (FrameInfoFlags)funcKind; if (funcKind == CorJitFuncKind.CORJIT_FUNC_ROOT) { if (this.MethodBeingCompiled.IsNativeCallable) flags |= FrameInfoFlags.ReversePInvoke; } byte[] blobData = new byte[unwindSize]; for (uint i = 0; i < unwindSize; i++) { blobData[i] = pUnwindBlock[i]; } _frameInfos[_usedFrameInfos++] = new FrameInfo(flags, (int)startOffset, (int)endOffset, blobData); }
public override async Task <int> CaptureWithCursorAsync(FrameInfo frame) { return(await Task.Factory.StartNew(() => CaptureWithCursor(frame))); }
private Browser GetPivotFrame() { FrameInfo f = new FrameInfo(); f.Id = "Mainc_BOCc_ptf"; return ActiveBrowser.WaitForFrame(f, 15000); }
public void AddFrame(Func<Action> EnterAndGetExit, bool PreserveFuture) { if (!PreserveFuture) { this.GoForward.Clear(); } this.Owner.ButtonGoForward.Enabled = this.GoForward.Any(); if (AddFrame_Current != null) { AddFrame_Current.Exit(); var AddFrame_Back = AddFrame_Current; this.Owner.ButtonGoBack.Enabled = true; this.GoBack.Push( delegate { if (AddFrame_Current != null) { AddFrame_Current.Exit(); var AddFrame_Forward = AddFrame_Current; this.Owner.ButtonGoForward.Enabled = true; this.GoForward.Push( delegate { AddFrame(AddFrame_Forward.EnterAndGetExit, true); } ); } AddFrame_Current = AddFrame_Back; AddFrame_Current.Exit = AddFrame_Current.EnterAndGetExit(); this.Owner.ButtonGoBack.Enabled = this.GoBack.Any(); } ); } AddFrame_Current = new FrameInfo { EnterAndGetExit = EnterAndGetExit, Exit = EnterAndGetExit() }; }
private void RaiseLastFrameRenderEvent(ProcessInfo processData, FrameInfo frameData) { RaiseEvent(new FrameRenderRoutedEventArgs { ProcessData = processData, FrameData = frameData }); }
public GpuRawFrame(FrameInfo info, IPooled<ITexture2D> texturePooled) { Info = info; TexturePooled = texturePooled; }
public void Iss2527PivotColorAfterFormatChange() { OpenObject(pivotName); //ActiveBrowser.Actions.WaitForElement(new FindParam("id=Mainc_BOCc_ptf"), 5000); ActiveBrowser.WaitForElement(5000, "id=Mainc_BOCc_ptf"); FrameInfo f = new FrameInfo(); f.Id = "Mainc_BOCc_ptf"; ActiveBrowser.WaitForFrame(f, 15000); ActiveBrowser.Frames.RefreshAllDomTrees(); ActiveBrowser.Frames.WaitAllUntilReady(); Browser frame = ActiveBrowser.Frames[0]; Assert.IsNotNull(frame); frame.WaitForElement(5000, "id=PivotTable_Grid"); HtmlDiv div = frame.Find.ById<HtmlDiv>("PivotTable_Grid"); Assert.IsNotNull(div); /* HtmlAnchor a = frame.Find.ByXPath<HtmlAnchor>("//*[@id=\"PivotTable_Grid_olapgrid_menun38\"]/td/table/tbody/tr/td/a"); Assert.IsNull(a); HtmlTableCell cell = frame.Find.ByXPath<HtmlTableCell>("//*[@id=\"olapgrid_FTABLE\"]/tbody/tr[4]/td"); Assert.IsNotNull(cell); cell.MouseClick(MouseClickType.RightClick); Thread.Sleep(3000); Assert.IsNull(a); */ HtmlStyle style = div.GetStyle("backgroundColor"); System.Drawing.Color color = style.ToColor(); int r = color.R, b = color.B, g = color.G; Assert.IsTrue(style.ToColor().R == r && b == style.ToColor().B && g == style.ToColor().G); frame.Window.SetActive(); frame.Window.SetFocus(); frame.Actions.InvokeScript("javascript:__doPostBack('PivotTable$Grid','popupselected|FormatNumbersFormatNumbers_Percentage')"); Thread.Sleep(5000); Assert.IsTrue(style.ToColor().R == r && b == style.ToColor().B && g == style.ToColor().G); }
private BitmapSource Render(int index) { var currentFrame = _frames[index]; FrameInfo previousFrame = null; BitmapSource previousRendered = null; BitmapSource previousPreviousRendered = null; if (index > 0) { if (_renderedFrames[index - 1] == null) { _renderedFrames[index - 1] = Render(index - 1); } previousFrame = _frames[index - 1]; previousRendered = _renderedFrames[index - 1]; } // when saying APNGDisposeOpPrevious, we need to find the last frame not having APNGDisposeOpPrevious. // Only [index-2] is not correct here since that frame may also have APNGDisposeOpPrevious. if (index > 1) { previousPreviousRendered = _renderedFrames[_lastEffectivePreviousPreviousFrameIndex]; } if (_frames[index].DisposeOp != DisposeOps.APNGDisposeOpPrevious) { _lastEffectivePreviousPreviousFrameIndex = Math.Max(_lastEffectivePreviousPreviousFrameIndex, index); } var visual = new DrawingVisual(); using (var context = visual.RenderOpen()) { // protect region if (currentFrame.BlendOp == BlendOps.APNGBlendOpSource) { var freeRegion = new CombinedGeometry(GeometryCombineMode.Xor, new RectangleGeometry(currentFrame.FrameRect), new RectangleGeometry(currentFrame.FrameRect)); context.PushOpacityMask( new DrawingBrush(new GeometryDrawing(Brushes.Transparent, null, freeRegion))); } if (previousFrame != null) { switch (previousFrame.DisposeOp) { case DisposeOps.APNGDisposeOpNone: if (previousRendered != null) { context.DrawImage(previousRendered, currentFrame.FullRect); } break; case DisposeOps.APNGDisposeOpPrevious: if (previousPreviousRendered != null) { context.DrawImage(previousPreviousRendered, currentFrame.FullRect); } break; case DisposeOps.APNGDisposeOpBackground: // do nothing break; } } // unprotect region and draw current frame if (currentFrame.BlendOp == BlendOps.APNGBlendOpSource) { context.Pop(); } context.DrawImage(currentFrame.Pixels, currentFrame.FrameRect); } var bitmap = new RenderTargetBitmap( (int)currentFrame.FullRect.Width, (int)currentFrame.FullRect.Height, Math.Floor(currentFrame.Pixels.DpiX), Math.Floor(currentFrame.Pixels.DpiY), PixelFormats.Pbgra32); bitmap.Render(visual); bitmap.Freeze(); return(bitmap); }
static ThreadInfo ParseCallstack(string LogOutput, out DateTime Timestamp, out int FrameNum) { Timestamp = DateTime.UtcNow; FrameNum = 0; Regex LogLineRegex = new Regex(@"(?<timestamp>\s\[\d.+\]\[\s*\d+\])(?<log>.*)"); Regex TimeRegex = new Regex(@"\[(?<year>\d+)\.(?<month>\d+)\.(?<day>\d+)-(?<hour>\d+)\.(?<minute>\d+)\.(?<second>\d+):(?<millisecond>\d+)\]\[(?<frame>\s*\d+)\]", RegexOptions.IgnoreCase); Regex ThreadRegex = new Regex(@"(thread\s#)(?<threadnum>\d+),?(?<status>.+)"); Regex SymbolicatedFrameRegex = new Regex(@"\s#(?<framenum>\d+):\s0x(?<address>[\da-f]+)\s(?<module>.+)\`(?<symbol>.+)(\sat\s)(?<source>.+)\s\[opt\]"); Regex UnsymbolicatedFrameRegex = new Regex(@"frame\s#(?<framenum>\d+):\s0x(?<address>[\da-f]+)\s(?<module>.+)\`(?<symbol>.+)\s\+\s(?<offset>\d+)"); LinkedList <string> CrashLog = new LinkedList <string>(Regex.Split(LogOutput, "\r\n|\r|\n")); List <ThreadInfo> Threads = new List <ThreadInfo>(); ThreadInfo Thread = null; ThreadInfo CrashThread = null; var LineNode = CrashLog.First; while (LineNode != null) { string Line = LineNode.Value.Trim(); // If Gauntlet marks the test as complete, ignore any thread dumps from forcing process to exit if (Line.Contains("**** TEST COMPLETE. EXIT CODE: 0 ****")) { return(null); } // Parse log timestamps if (LogLineRegex.IsMatch(Line)) { GroupCollection LogGroups = LogLineRegex.Match(Line).Groups; if (TimeRegex.IsMatch(LogGroups["timestamp"].Value)) { GroupCollection TimeGroups = TimeRegex.Match(LogGroups["timestamp"].Value).Groups; int Year = int.Parse(TimeGroups["year"].Value); int Month = int.Parse(TimeGroups["month"].Value); int Day = int.Parse(TimeGroups["day"].Value); int Hour = int.Parse(TimeGroups["hour"].Value); int Minute = int.Parse(TimeGroups["minute"].Value); int Second = int.Parse(TimeGroups["second"].Value); FrameNum = int.Parse(TimeGroups["frame"].Value); Timestamp = new DateTime(Year, Month, Day, Hour, Minute, Second); } LineNode = LineNode.Next; continue; } if (Thread != null) { FrameInfo Frame = null; GroupCollection FrameGroups = null; // Parse symbolicated frame if (SymbolicatedFrameRegex.IsMatch(Line)) { FrameGroups = SymbolicatedFrameRegex.Match(Line).Groups; Frame = new FrameInfo() { Address = FrameGroups["address"].Value, Module = FrameGroups["module"].Value, Symbol = FrameGroups["symbol"].Value, }; Frame.Source = FrameGroups["source"].Value; if (Frame.Source.Contains(":")) { Frame.Source = FrameGroups["source"].Value.Split(':')[0]; Frame.Line = FrameGroups["source"].Value.Split(':')[1]; } } // Parse unsymbolicated frame if (UnsymbolicatedFrameRegex.IsMatch(Line)) { FrameGroups = UnsymbolicatedFrameRegex.Match(Line).Groups; Frame = new FrameInfo() { Address = FrameGroups["address"].Value, Offset = FrameGroups["offset"].Value, Module = FrameGroups["module"].Value, Symbol = FrameGroups["symbol"].Value }; } if (Frame != null) { Thread.Frames.Add(Frame); } else { Thread = null; } } // Parse thread if (ThreadRegex.IsMatch(Line)) { GroupCollection ThreadGroups = ThreadRegex.Match(Line).Groups; Thread = new ThreadInfo() { Num = int.Parse(ThreadGroups["threadnum"].Value), Status = ThreadGroups["status"].Value.Trim() }; if (Line.StartsWith("*")) { Thread.Current = true; } if (CrashThread == null) { CrashThread = Thread; } else { Threads.Add(Thread); } } LineNode = LineNode.Next; } if (CrashThread == null) { return(null); } Thread = Threads.Single(T => T.Num == CrashThread.Num); if (Thread == null) { Log.Warning("Unable to parse full crash callstack"); Thread = CrashThread; } return(Thread); }
public static IEnumerator Process(byte[] gifData, Action <Texture2D, Rect[], float, TextureDownloadInfo> callback, TextureDownloadInfo imageDownloadInfo) { Plugin.Log($"Started decoding gif {imageDownloadInfo.spriteIndex}"); List <Texture2D> texList = new List <Texture2D>(); GifInfo frameInfo = new GifInfo(); DateTime startTime = DateTime.Now; Task.Run(() => ProcessingThread(gifData, ref frameInfo)); yield return(new WaitUntil(() => { return frameInfo.initialized; })); int textureSize = 2048; Texture2D texture = null; float delay = -1f; for (int i = 0; i < frameInfo.frameCount; i++) { yield return(new WaitUntil(() => { return frameInfo.frames.Count > i; })); //Plugin.Log($"Frame {i} is ready for processing! Frame is {frameInfo.frames[i].frame.Width}x{frameInfo.frames[i].frame.Height}"); if (texture == null) { textureSize = GetTextureSize(frameInfo, i); texture = new Texture2D(textureSize, textureSize); } FrameInfo currentFrameInfo = frameInfo.frames[i]; if (delay == -1f) { delay = currentFrameInfo.delay; } var frameTexture = new Texture2D(currentFrameInfo.frame.Width, currentFrameInfo.frame.Height); try { int colorIndex = 0; Color32[] colors = new Color32[currentFrameInfo.frame.Width * currentFrameInfo.frame.Height]; for (int x = 0; x < currentFrameInfo.frame.Width; x++) { for (int y = 0; y < currentFrameInfo.frame.Height; y++) { System.Drawing.Color sourceColor = currentFrameInfo.colors[colorIndex]; colors[(currentFrameInfo.frame.Height - y - 1) * currentFrameInfo.frame.Width + x] = new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A); colorIndex++; } } frameTexture.wrapMode = TextureWrapMode.Clamp; frameTexture.SetPixels32(colors); frameTexture.Apply(i == 0); } catch (Exception e) { Plugin.Log($"Exception while decoding gif! Frame: {i}, Exception: {e}"); yield break; } yield return(null); texList.Add(frameTexture); // Instant callback after we decode the first frame in order to display a still image until the animated one is finished loading if (i == 0) { callback?.Invoke(frameTexture, texture.PackTextures(new Texture2D[] { frameTexture }, 2, textureSize, true), delay, imageDownloadInfo); } } Rect[] atlas = texture.PackTextures(texList.ToArray(), 2, textureSize, true); yield return(null); callback?.Invoke(texture, atlas, delay, imageDownloadInfo); Plugin.Log($"Finished decoding gif {imageDownloadInfo.spriteIndex}! Elapsed time: {(DateTime.Now - startTime).TotalSeconds} seconds."); }
public override int CaptureWithCursor(FrameInfo frame) { try { new System.Security.Permissions.UIPermission(System.Security.Permissions.UIPermissionWindow.AllWindows).Demand(); //var success = Native.BitBlt(CompatibleDeviceContext, 0, 0, Width, Height, WindowDeviceContext, Left, Top, Native.CopyPixelOperation.SourceCopy | Native.CopyPixelOperation.CaptureBlt); var success = Native.StretchBlt(CompatibleDeviceContext, 0, 0, StartWidth, StartHeight, WindowDeviceContext, Left, Top, Width, Height, Native.CopyPixelOperation.SourceCopy | Native.CopyPixelOperation.CaptureBlt); if (!success) { return(FrameCount); } #region Cursor try { var cursorInfo = new Native.CursorInfo(); cursorInfo.cbSize = Marshal.SizeOf(cursorInfo); if (Native.GetCursorInfo(out cursorInfo)) { if (cursorInfo.flags == Native.CursorShowing) { var hicon = Native.CopyIcon(cursorInfo.hCursor); if (hicon != IntPtr.Zero) { if (Native.GetIconInfo(hicon, out var iconInfo)) { frame.CursorX = cursorInfo.ptScreenPos.X - Left; frame.CursorY = cursorInfo.ptScreenPos.Y - Top; //If the cursor rate needs to be precisely captured. //https://source.winehq.org/source/dlls/user32/cursoricon.c#2325 //int rate = 0, num = 0; //var ok1 = Native.GetCursorFrameInfo(cursorInfo.hCursor, IntPtr.Zero, 17, ref rate, ref num); //CursorStep var ok = Native.DrawIconEx(CompatibleDeviceContext, frame.CursorX - iconInfo.xHotspot, frame.CursorY - iconInfo.yHotspot, cursorInfo.hCursor, 0, 0, CursorStep, IntPtr.Zero, 0x0003); if (!ok) { CursorStep = 0; Native.DrawIconEx(CompatibleDeviceContext, frame.CursorX - iconInfo.xHotspot, frame.CursorY - iconInfo.yHotspot, cursorInfo.hCursor, 0, 0, CursorStep, IntPtr.Zero, 0x0003); } else { CursorStep++; } //Set to fix all alpha bits back to 255. //frame.RemoveAnyTransparency = iconInfo.hbmMask != IntPtr.Zero; } Native.DeleteObject(iconInfo.hbmColor); Native.DeleteObject(iconInfo.hbmMask); } Native.DestroyIcon(hicon); } Native.DeleteObject(cursorInfo.hCursor); } } catch (Exception e) { //LogWriter.Log(e, "Impossible to get the cursor"); } #endregion //Set frame details. FrameCount++; frame.Path = $"{Project.FullPath}{FrameCount}.png"; frame.Delay = FrameRate.GetMilliseconds(SnapDelay); frame.DataLength = _byteLength; frame.Data = new byte[_byteLength]; Native.GetDIBits(WindowDeviceContext, CompatibleBitmap, 0, (uint)StartHeight, frame.Data, ref _infoHeader, Native.DibColorMode.DibRgbColors); BlockingCollection.Add(frame); } catch (Exception e) { //LogWriter.Log(ex, "Impossible to get the screenshot of the screen"); } return(FrameCount); }
public override void UpdateFrame(ViewportBase viewport, FrameInfo frame) { WidgetAction((w, vp, ev) => w.UpdateFrame(vp, frame), viewport, null); base.UpdateFrame(viewport, frame); }
private void BuildWindow() { // Initialize property block state. int colorID = Shader.PropertyToID("_Color"); propertyBlockFrameTarget = new MaterialPropertyBlock(); propertyBlockFrameTarget.SetColor(colorID, targetFrameRateColor); propertyBlockFrameMissed = new MaterialPropertyBlock(); propertyBlockFrameMissed.SetColor(colorID, missedFrameRateColor); // Build the window root. { window = CreateQuad("VisualProfiler", null); InitializeRenderer(window, backgroundMaterial, colorID, baseColor); window.transform.localScale = new Vector3(0.2f, 0.04f, 1.0f); windowRotation = Quaternion.AngleAxis(windowYawRotation, Vector3.right); } // Add frame rate text and frame indicators. { frameRateText = CreateText("FrameRateText", new Vector3(-0.495f, 0.5f, 0.0f), window.transform, TextAnchor.UpperLeft, textMaterial, Color.white, string.Empty); frameInfo = new FrameInfo[frameRange]; Vector3 scale = new Vector3(1.0f / frameRange, 0.2f, 1.0f); Vector3 position = new Vector3(0.5f - (scale.x * 0.5f), 0.15f, 0.0f); for (int i = 0; i < frameRange; ++i) { frameInfo[i] = new FrameInfo(); frameInfo[i].PropertyBlock = propertyBlockFrameTarget; GameObject quad = CreateQuad("Frame", window.transform); frameInfo[i].Renderer = InitializeRenderer(quad, defaultMaterial, colorID, missedFrameRateColor); quad.transform.localPosition = position; Vector3 bufferedScale = new Vector3(scale.x * 0.8f, scale.y, scale.z); quad.transform.localScale = bufferedScale; position.x -= scale.x; } } // Add memory usage text and bars. { usedMemoryText = CreateText("UsedMemoryText", new Vector3(-0.495f, 0.0f, 0.0f), window.transform, TextAnchor.UpperLeft, textMaterial, memoryUsedColor, usedMemoryString); peakMemoryText = CreateText("PeakMemoryText", new Vector3(0.0f, 0.0f, 0.0f), window.transform, TextAnchor.UpperCenter, textMaterial, memoryPeakColor, peakMemoryString); limitMemoryText = CreateText("LimitMemoryText", new Vector3(0.495f, 0.0f, 0.0f), window.transform, TextAnchor.UpperRight, textMaterial, Color.white, limitMemoryString); GameObject limitBar = CreateQuad("LimitBar", window.transform); InitializeRenderer(limitBar, defaultMaterial, colorID, memoryLimitColor); limitBar.transform.localScale = new Vector3(0.99f, 0.2f, 1.0f); limitBar.transform.localPosition = new Vector3(0.0f, -0.37f, 0.0f); { usedAnchor = CreateAnchor("UsedAnchor", limitBar.transform); GameObject bar = CreateQuad("UsedBar", usedAnchor); Material material = new Material(foregroundMaterial); material.renderQueue = material.renderQueue + 1; InitializeRenderer(bar, material, colorID, memoryUsedColor); bar.transform.localScale = Vector3.one; bar.transform.localPosition = new Vector3(0.5f, 0.0f, 0.0f); } { peakAnchor = CreateAnchor("PeakAnchor", limitBar.transform); GameObject bar = CreateQuad("PeakBar", peakAnchor); InitializeRenderer(bar, foregroundMaterial, colorID, memoryPeakColor); bar.transform.localScale = Vector3.one; bar.transform.localPosition = new Vector3(0.5f, 0.0f, 0.0f); } } window.SetActive(initiallyActive); }
public override int Capture(FrameInfo frame) { var res = Result.Ok; try { //Try to get the duplicated output frame within given time. res = DuplicatedOutput.TryAcquireNextFrame(0, out var info, out var resource); //Somehow, it was not possible to retrieve the resource or any frame. if (res.Failure || resource == null || info.AccumulatedFrames == 0) { resource?.Dispose(); return(FrameCount); } //Copy resource into memory that can be accessed by the CPU. using (var screenTexture = resource.QueryInterface <Texture2D>()) { //Copies from the screen texture only the area which the user wants to capture. Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), StagingTexture, 0); } //Get the desktop capture texture. var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None, out var stream); if (data.IsEmpty) { Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); stream?.Dispose(); resource.Dispose(); return(FrameCount); } #region Get image data //Set frame details. FrameCount++; frame.Path = $"{Project.FullPath}{FrameCount}.png"; frame.Delay = FrameRate.GetMilliseconds(SnapDelay); frame.DataLength = stream.Length; frame.Data = new byte[stream.Length]; //BGRA32 is 4 bytes. for (var height = 0; height < Height; height++) { stream.Position = height * data.RowPitch; Marshal.Copy(new IntPtr(stream.DataPointer.ToInt64() + height * data.RowPitch), frame.Data, height * Width * 4, Width * 4); } BlockingCollection.Add(frame); #endregion Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); resource.Dispose(); return(FrameCount); } catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { return(FrameCount); } catch (Exception ex) { LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX."); OnError.Invoke(ex); return(FrameCount); } finally { try { //Only release the frame if there was a sucess in capturing it. if (res.Success) { DuplicatedOutput.ReleaseFrame(); } } catch (Exception e) { LogWriter.Log(e, "It was not possible to release the frame."); } } }
protected override void Initialize() { logger = new SLLogger(); frameinfo = new FrameInfo(); audio = new SLAudio(SLConfig["content"] + "StiLib", SLConfig["content"] + "SLMWB", SLConfig["content"] + "SLSWB", SLConfig["content"] + "SLSB"); audio.Update(); audio.StartBgMusic("BgMusic"); BarPara bpara = BarPara.Default; bpara.width = 4.0f; bpara.height = 1.0f; bpara.BasePara.direction = 0.0f; bpara.BasePara.speed = 10.0f; bpara.BasePara.space = 10.0f; bpara.BasePara.center = new Vector3(-2.0f, -2.0f, 0.0f); bpara.BasePara.color = Color.SeaGreen; bar = new Bar(GraphicsDevice, SLConfig, bpara); GratingPara gpara = GratingPara.Default; gpara.shape = Shape.Circle; gpara.gratingtype = GratingType.Sinusoidal; gpara.BasePara.center = new Vector3(2.0f, 2.0f, 0.0f); gpara.lhcolor = Color.OrangeRed; gpara.rlcolor = new Color(0f, 1f, 0f, 1f); gpara.BasePara.diameter = 7.0f; gpara.sf = 0.5f; gpara.contrast = 0.8f; gpara.luminance = 0.3f; gpara.maskpara.BasePara.diameter = 1.2f; grating = new Grating(GraphicsDevice, Services, "Content", gpara); text = new Text(GraphicsDevice, Services, "Content", "Arial"); model = new SLModel(GraphicsDevice, Services, "Content", "earth"); cross = new Primitive(GraphicsDevice, PrimitivePara.Cross(3f, Color.Green, 4 * Vector3.UnitX)); arrow = new Primitive(GraphicsDevice, PrimitivePara.Arrow(4f, Color.Red, -4 * Vector3.UnitX, 60f, 1f)); model.Para.BasePara.rotationspeed3D = Vector3.UnitY; model.ProjectionType = ProjectionType.Perspective; model.globalCamera.NearPlane = 0.1f; timer = new SLTimer(); timer.Start(); }
public override int CaptureWithCursor(FrameInfo frame) { var res = Result.Ok; try { //Try to get the duplicated output frame within given time. res = DuplicatedOutput.TryAcquireNextFrame(0, out var info, out var resource); //Checks how to proceed with the capture. It could have failed, or the screen, cursor or both could have been captured. if (res.Failure || resource == null || (info.AccumulatedFrames == 0 && info.LastMouseUpdateTime <= LastProcessTime)) { //Somehow, it was not possible to retrieve the resource, frame or metadata. resource?.Dispose(); return(FrameCount); } else if (info.AccumulatedFrames == 0 && info.LastMouseUpdateTime > LastProcessTime) { //Gets the cursor shape if the screen hasn't changed in between, so the cursor will be available for the next frame. GetCursor(null, info, frame); return(FrameCount); //TODO: if only the mouse changed, but there's no frame accumulated, but there's data in the texture from the previous frame, I need to merge with the cursor and add to the list. } //Saves the most recent capture time. LastProcessTime = Math.Max(info.LastPresentTime, info.LastMouseUpdateTime); //Copy resource into memory that can be accessed by the CPU. using (var screenTexture = resource.QueryInterface <Texture2D>()) { //Copies from the screen texture only the area which the user wants to capture. Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), BackingTexture, 0); //Copy the captured desktop texture into a staging texture, in order to show the mouse cursor and not make the captured texture dirty with it. Device.ImmediateContext.CopyResource(BackingTexture, StagingTexture); //Gets the cursor image and merges with the staging texture. GetCursor(StagingTexture, info, frame); } //Get the desktop capture texture. var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None, out var stream); if (data.IsEmpty) { Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); stream?.Dispose(); resource.Dispose(); return(FrameCount); } #region Get image data //Set frame details. FrameCount++; frame.Path = $"{Project.FullPath}{FrameCount}.png"; frame.Delay = FrameRate.GetMilliseconds(SnapDelay); frame.DataLength = stream.Length; frame.Data = new byte[stream.Length]; //BGRA32 is 4 bytes. for (var height = 0; height < Height; height++) { stream.Position = height * data.RowPitch; Marshal.Copy(new IntPtr(stream.DataPointer.ToInt64() + height * data.RowPitch), frame.Data, height * Width * 4, Width * 4); } BlockingCollection.Add(frame); #endregion Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); stream.Dispose(); resource.Dispose(); return(FrameCount); } catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { return(FrameCount); } catch (Exception ex) { LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX."); OnError.Invoke(ex); return(FrameCount); } finally { try { //Only release the frame if there was a sucess in capturing it. if (res.Success) { DuplicatedOutput.ReleaseFrame(); } } catch (Exception e) { LogWriter.Log(e, "It was not possible to release the frame."); } } }
static void Main(string[] args) { using (NpkReader npk = new NpkReader(@"C:\Neople\DFO\ImagePacks2\sprite_character_fighter_equipment_avatar_cap.NPK")) { npk.PreLoadAllSpriteFrameMetadata(); List <NpkPath> imgs = npk.Frames.Where(kvp => kvp.Value.Any(f => f.CompressedLength == 84)).Select(kvp => kvp.Key).ToList(); foreach (NpkPath img in imgs) { IReadOnlyList <FrameInfo> frames = npk.Frames[img]; for (int i = 0; i < frames.Count; i++) { if (frames[i].CompressedLength == 84 && !frames[i].IsCompressed) { Console.WriteLine(string.Format("{0} {1}", img, i)); } } } } Environment.Exit(0); foreach (string path in Directory.GetFiles(@"C:\Neople\DFO\ImagePacks2", "*.NPK")) { Console.WriteLine(path); using (NpkReader npk = new NpkReader(path)) { npk.PreLoadAllSpriteFrameMetadata(); foreach (NpkPath npkPath in npk.Frames.Keys) { var x = npk.Frames[npkPath]; for (int i = 0; i < x.Count; i++) { FrameInfo frame = x[i]; if (!frame.IsCompressed && frame.LinkFrame == null) { string pixelFormatString = frame.PixelFormat.ToString(); int actualLength = frame.Width * frame.Height * 2; if (frame.PixelFormat == PixelDataFormat.EightEightEightEight) { actualLength *= 2; } if (frame.CompressedLength != actualLength) { Console.WriteLine("Pixel Format: {0,22}, Compressed Length: {1,9}, Actual Length: {2,9} {3} {4}", pixelFormatString, frame.CompressedLength, actualLength, npkPath, i); } } } } } } Environment.Exit(0); using (NpkReader npkReader = new NpkReader(@"C:\Neople\DFO\ImagePacks2\sprite_monster_impossible_bakal.NPK")) using (NpkReader coolReader = new NpkReader(@"C:\Neople\DFO\ImagePacks2\sprite_character_swordman_effect_sayaex.NPK")) { DFO.Common.Images.Image image = npkReader.GetImage("monster/impossible_bakal/ashcore.img", 0); //Image image2 = npkReader.GetImage("worldmap/act1/elvengard.img", 1); using (Bitmap bitmap = new Bitmap(image.Attributes.Width, image.Attributes.Height)) { BitmapData raw = bitmap.LockBits(new Rectangle(0, 0, image.Attributes.Width, image.Attributes.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); unsafe { byte *ptr = (byte *)raw.Scan0; // RGBA -> BGRA (pixels in the bitmap have endianness) int width = image.Attributes.Width; int height = image.Attributes.Height; int stride = raw.Stride; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { ptr[y * stride + x * 4 + 0] = image.PixelData[y * width * 4 + x * 4 + 2]; ptr[y * stride + x * 4 + 1] = image.PixelData[y * width * 4 + x * 4 + 1]; ptr[y * stride + x * 4 + 2] = image.PixelData[y * width * 4 + x * 4 + 0]; ptr[y * stride + x * 4 + 3] = image.PixelData[y * width * 4 + x * 4 + 3]; } } } bitmap.UnlockBits(raw); bitmap.Save(@"output.png", System.Drawing.Imaging.ImageFormat.Png); RawAnimation animationData = new RawAnimation(); animationData.Loop = true; animationData.Frames = new List <ConstAnimationFrame>() { new AnimationFrame() { DelayInMs = 1000, Image = new ImageIdentifier("worldmap/act1/elvengard.img", 0) }.AsConst(), new AnimationFrame() { DelayInMs = 1000, Image = new ImageIdentifier("worldmap/act1/elvengard.img", 1) }.AsConst() }; RawAnimation cool = new RawAnimation(); cool.Loop = true; cool.Frames = new List <ConstAnimationFrame>() { new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 0) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 1) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 2) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 3) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 4) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 5) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 6) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 7) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 8) }.AsConst(), new AnimationFrame() { DelayInMs = 100, Image = new ImageIdentifier("character/swordman/effect/sayaex/wingdodge.img", 9) }.AsConst(), }; using (GifMaker giffer = new GifMaker(npkReader, disposeImageSource: false)) using (GifMaker coolGiffer = new GifMaker(coolReader, disposeImageSource: false)) using (FileStream gifOutputStream = new FileStream("output.gif", FileMode.Create, FileAccess.ReadWrite, FileShare.None)) using (FileStream coolGifOutputStream = new FileStream("cool.gif", FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { giffer.Create(animationData.AsConst(), gifOutputStream); coolGiffer.Create(cool.AsConst(), coolGifOutputStream); } } Console.WriteLine("Success!"); } }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); audio = new SLAudio(SLConfig["content"] + "StiLib", SLConfig["content"] + "SLMWB", SLConfig["content"] + "SLSWB", SLConfig["content"] + "SLSB"); audio.Update(); audio.StartBgMusic("BgMusic"); frameinfo = new FrameInfo(); text = new Text(GraphicsDevice, Services, "Content", "Arial"); model = new SLModel(GraphicsDevice, Services, "Content", "earth"); model.Para.BasePara.space = 10; model.Para.BasePara.rotationspeed3D = Vector3.UnitY; model.ProjectionType = ProjectionType.Perspective; model.globalCamera.Position = Vector3.UnitZ * 20; CollectionPara cpara = CollectionPara.Default; cpara.BasePara.center = Vector3.Zero; cpara.CollectionCenter = new Vector3(2f, 3f, 0.0f); cpara.CollectionSpeed = new Vector3(0.02f, 0.03f, 0.0f); vsc = new VSCollection<SLModel>(10, GraphicsDevice, model, cpara); }
/// <summary> /// /// </summary> /// <param name="imgPath"></param> /// <param name="frameIndex"></param> /// <param name="newFrameMetadata">If this indicates a link frame, <paramref name="newFramePixels"/> is ignored. The IsCompressed flag is honored, compressing the image if it is set. The CompressedLength field is not used.</param> /// <param name="newFramePixels">Readable stream consisting solely of the pixel data, in the format indicated by the metadata.</param> public void EditFrame(NpkPath imgPath, int frameIndex, FrameInfo newFrameMetadata, Stream newFramePixels) { ThrowIfDisposed(); ThrowIfNoFileOpen(); if (!_reader.Frames.ContainsKey(imgPath)) { throw new ArgumentException("{0} is not in the NPK.".F(imgPath)); } if (frameIndex >= _reader.Frames[imgPath].Count) { throw new ArgumentException("{0} does not have a frame {1}.".F(imgPath, frameIndex)); } NpkFileTableEntry entryOfImgEditing = _reader.Files.Where(f => f.Name.Equals(imgPath)).First(); IReadOnlyList <FrameInfo> frameListOfImgEditing = _reader.Frames[imgPath]; FrameInfo frameMetadataOfFrameEditing = frameListOfImgEditing[frameIndex]; // Render the new frame in memory // pixelData is null if it's a link frame // pixelData length may be bigger than the actual pixel data. Use newPixelDataLength instead of newPixelData.Length int newPixelDataLength; byte[] newPixelData = GetPixelData(newFrameMetadata, newFramePixels, out newPixelDataLength); byte[] frameMetadataBytes = GetFrameMetadataBytes(newFrameMetadata, newPixelDataLength); string tempNpkPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".NPK"); using (FileStream tempFileStream = File.OpenWrite(tempNpkPath)) { WriteEditedNPK(tempFileStream, imgPath, entryOfImgEditing, frameIndex, frameListOfImgEditing, frameMetadataOfFrameEditing, newFrameMetadata, newPixelData, newPixelDataLength, frameMetadataBytes); } // temp file now has the new NPK! // close _reader // close _npkStream // delete original file // move temp file // TODO: "refresh" it _reader.Dispose(); _npkStream.Dispose(); // TODO: Error handling File.Delete(_openFilePath); File.Move(tempNpkPath, _openFilePath); // reopen try { _reader = new NpkReader(_openFilePath); } catch (Exception) { _openFilePath = null; _reader = null; _npkStream = null; throw; } try { _npkStream = new FileStream(_openFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception) { _openFilePath = null; _reader.Dispose(); _reader = null; _npkStream = null; throw; } }
internal FrameInfo[] Thread_GetFrameInfo(long id, int start_frame, int length) { var res = SendReceive(CommandSet.THREAD, (int)CmdThread.GET_FRAME_INFO, new PacketWriter().WriteId(id).WriteInt(start_frame).WriteInt(length)); int count = res.ReadInt(); var frames = new FrameInfo[count]; for (int i = 0; i < count; ++i) { frames[i].id = res.ReadInt(); frames[i].method = res.ReadId(); frames[i].il_offset = res.ReadInt(); frames[i].flags = (StackFrameFlags)res.ReadByte(); } return frames; }
private uint GetImgField1Value(IReadOnlyList <FrameInfo> frameListOfImgEditing, FrameInfo frameMetadataOfFrameEditing, FrameInfo frameMetadataOfNewFrame) { int numberOfLinkFramesInImgBeforeEdit = 0; int numberOfNonLinkFramesInImgBeforeEdit = 0; foreach (FrameInfo frame in frameListOfImgEditing) { if (frame.PixelFormat == PixelDataFormat.Link) { numberOfLinkFramesInImgBeforeEdit++; } else { numberOfNonLinkFramesInImgBeforeEdit++; } } int numberOfLinkFramesInImgAfterEdit = numberOfLinkFramesInImgBeforeEdit; int numberOfNonLinkFramesInImgAfterEdit = numberOfNonLinkFramesInImgBeforeEdit; if (frameMetadataOfFrameEditing.PixelFormat == PixelDataFormat.Link) { numberOfLinkFramesInImgAfterEdit--; } else { numberOfNonLinkFramesInImgAfterEdit--; } if (frameMetadataOfNewFrame.PixelFormat == PixelDataFormat.Link) { numberOfLinkFramesInImgAfterEdit++; } else { numberOfNonLinkFramesInImgAfterEdit++; } uint field1Value = (uint)(36 * numberOfNonLinkFramesInImgAfterEdit + 8 * numberOfLinkFramesInImgAfterEdit); return(field1Value); }
protected internal bool GetCursor(Texture2D screenTexture, OutputDuplicateFrameInformation info, FrameInfo frame) { //Prepare buffer array to hold the cursor shape. if (CursorShapeBuffer == null || info.PointerShapeBufferSize > CursorShapeBuffer.Length) { CursorShapeBuffer = new byte[info.PointerShapeBufferSize]; } //If there's a cursor shape available to be captured. if (info.PointerShapeBufferSize > 0) { //Pin the buffer in order to pass the address as parameter later. var pinnedBuffer = GCHandle.Alloc(CursorShapeBuffer, GCHandleType.Pinned); var cursorBufferAddress = pinnedBuffer.AddrOfPinnedObject(); //Load the cursor shape into the buffer. DuplicatedOutput.GetFramePointerShape(info.PointerShapeBufferSize, cursorBufferAddress, out _, out CursorShapeInfo); //If the cursor is monochrome, it will return the cursor shape twice, one is the mask. if (CursorShapeInfo.Type == 1) { CursorShapeInfo.Height /= 2; } //The buffer must be unpinned, to free resources. pinnedBuffer.Free(); } //Store the current cursor position, if it was moved. if (info.LastMouseUpdateTime != 0) { PreviousPosition = info.PointerPosition; } //TODO: In a future version, don't merge the cursor image in here, let the editor do that. //Saves the position of the cursor, so the editor can add the mouse events overlay later. frame.CursorX = PreviousPosition.Position.X - (Left - OffsetLeft); frame.CursorY = PreviousPosition.Position.Y - (Top - OffsetTop); //If the method is supposed to simply the get the cursor shape no shape was loaded before, there's nothing else to do. //if (CursorShapeBuffer?.Length == 0 || (info.LastPresentTime == 0 && info.LastMouseUpdateTime == 0) || !info.PointerPosition.Visible) if (screenTexture == null || CursorShapeBuffer?.Length == 0)// || !info.PointerPosition.Visible) { //FallbackCursorCapture(frame); //if (CursorShapeBuffer != null) return(false); } //Don't let it bleed beyond the top-left corner, calculate the dimensions of the portion of the cursor that will appear. var leftCut = frame.CursorX; var topCut = frame.CursorY; var rightCut = screenTexture.Description.Width - (frame.CursorX + CursorShapeInfo.Width); var bottomCut = screenTexture.Description.Height - (frame.CursorY + CursorShapeInfo.Height); //Adjust to the hotspot offset, so it's possible to add the highlight correctly later. frame.CursorX += CursorShapeInfo.HotSpot.X; frame.CursorY += CursorShapeInfo.HotSpot.Y; //Don't try merging the textures if the cursor is out of bounds. if (leftCut + CursorShapeInfo.Width < 1 || topCut + CursorShapeInfo.Height < 1 || rightCut + CursorShapeInfo.Width < 1 || bottomCut + CursorShapeInfo.Height < 1) { return(false); } var cursorLeft = Math.Max(leftCut, 0); var cursorTop = Math.Max(topCut, 0); var cursorWidth = leftCut < 0 ? CursorShapeInfo.Width + leftCut : rightCut < 0 ? CursorShapeInfo.Width + rightCut : CursorShapeInfo.Width; var cursorHeight = topCut < 0 ? CursorShapeInfo.Height + topCut : bottomCut < 0 ? CursorShapeInfo.Height + bottomCut : CursorShapeInfo.Height; //The staging texture must be able to hold all pixels. if (CursorStagingTexture == null || CursorStagingTexture.Description.Width != cursorWidth || CursorStagingTexture.Description.Height != cursorHeight) { //In order to change the size of the texture, I need to instantiate it again with the new size. CursorStagingTexture?.Dispose(); CursorStagingTexture = new Texture2D(Device, new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Write, Height = cursorHeight, Format = Format.B8G8R8A8_UNorm, Width = cursorWidth, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Staging }); } //The region where the cursor is located is copied to the staging texture to act as the background when dealing with masks and transparency. //The cutout must be the exact region needed and it can't overflow. It's not allowed to try to cut outside of the screenTexture region. var region = new ResourceRegion { Left = cursorLeft, Top = cursorTop, Front = 0, Right = cursorLeft + cursorWidth, Bottom = cursorTop + cursorHeight, Back = 1 }; //Copy from the screen the region in which the cursor is located. Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, region, CursorStagingTexture, 0); //Get cursor details and draw it to the staging texture. DrawCursorShape(CursorStagingTexture, CursorShapeInfo, CursorShapeBuffer, leftCut < 0 ? leftCut * -1 : 0, topCut < 0 ? topCut * -1 : 0, cursorWidth, cursorHeight); //Copy back the cursor texture to the screen texture. Device.ImmediateContext.CopySubresourceRegion(CursorStagingTexture, 0, null, screenTexture, 0, cursorLeft, cursorTop); return(true); }
private void WriteEditedImg(FileStream tempFileStream, int editedFrameIndex, IReadOnlyList <FrameInfo> frameListOfImgEditing, FrameInfo frameMetadataOfFrameEditing, FrameInfo newFrameMetadata, byte[] newPixelData, int newPixelDataLength, byte[] frameMetadataBytes, List <NpkByteRange> frameLocationsOfImgEditing) { // Need to know exact ordering of files // Need to know ALL files, even non-image files // Need to update offset of all files with an offset greater or equal to the one we're changing // Need to update file size of file that we're changing and any that occupy the same space //.img files begin with "Neople Img File\0" in ASCII tempFileStream.Write(NpkReader.s_imgHeaderBytes, 0, NpkReader.s_imgHeaderBytes.Length); // field 1 - (36 * (# non-link frames) + 8 * (# link frames)) //uint field1Value = (uint)(36 * numberOfNonLinkFramesInImgBeforeEdit + 8 * numberOfLinkFramesInImgBeforeEdit); uint field1Value = GetImgField1Value(frameListOfImgEditing, frameMetadataOfFrameEditing, newFrameMetadata); tempFileStream.WriteUnsigned32Le(field1Value, _intWriteBuffer); // field 2 - always 0 tempFileStream.WriteUnsigned32Le(0, _intWriteBuffer); // field 3 - always 2 tempFileStream.WriteUnsigned32Le(2, _intWriteBuffer); // frame count tempFileStream.WriteUnsigned32Le((uint)frameListOfImgEditing.Count, _intWriteBuffer); // frame metadata for each frame in order for (int frameIndexToWrite = 0; frameIndexToWrite < frameListOfImgEditing.Count; frameIndexToWrite++) { if (frameIndexToWrite != editedFrameIndex) { FrameInfo frameToCopy = frameListOfImgEditing[frameIndexToWrite]; byte[] metadataBytes = GetFrameMetadataBytes(frameToCopy, frameToCopy.CompressedLength); tempFileStream.Write(metadataBytes, 0, metadataBytes.Length); } else { tempFileStream.Write(frameMetadataBytes, 0, frameMetadataBytes.Length); } } // frame pixel data for each non-link frame in order for (int frameIndexToWrite = 0; frameIndexToWrite < frameListOfImgEditing.Count; frameIndexToWrite++) { if (frameIndexToWrite != editedFrameIndex) { FrameInfo frameToCopy = frameListOfImgEditing[frameIndexToWrite]; if (frameToCopy.PixelFormat != PixelDataFormat.Link) { NpkByteRange frameToWriteOriginalLocation = frameLocationsOfImgEditing[frameIndexToWrite]; _npkStream.Seek(frameToWriteOriginalLocation.FileOffset, SeekOrigin.Begin); _npkStream.CopyToPartially(tempFileStream, frameToWriteOriginalLocation.Size); } } else { // Write the pixel data for the frame we're changing, if it's not a link frame if (newFrameMetadata.PixelFormat != PixelDataFormat.Link) { tempFileStream.Write(newPixelData, 0, newPixelDataLength); } } } }
private void allocUnwindInfo(IntPtr _this, byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind) { FrameInfo frameInfo = new FrameInfo(); frameInfo.StartOffset = (int)startOffset; frameInfo.EndOffset = (int)endOffset; frameInfo.BlobData = new byte[unwindSize]; for (uint i = 0; i < unwindSize; i++) { frameInfo.BlobData[i] = pUnwindBlock[i]; } Debug.Assert(_usedFrameInfos < _frameInfos.Length); _frameInfos[_usedFrameInfos++] = frameInfo; }
public void Update(float deltaTime) { if (match == null) { return; } //计数回合内逻辑帧(服务器进度) acumulativeTimeServer += deltaTime * 1000; if (acumulativeTimeServer >= GAME_UPDATE_LENGTH) { acumulativeTimeServer -= GAME_UPDATE_LENGTH; ++gameUpdateIndexInTurnServer; } //如果预测平均回合间隔将大于定义回合间隔,则可能出现等回合。通过减慢逻辑帧速度,平滑等帧的卡顿(TODO:先注释,因在比赛中如果虚拟服务器手动停止,消息turn之间的间隔过大,下面的运算会让excatGameUpdateLength变成无穷大,影响正常的业务逻辑) //float turnInterval = match.turnManager.averageTurnInterval; //if (turnInterval > ((float)TURN_LENGTH / 1000 + 0.2f)) //{ // float factor = turnInterval / ((float)TURN_LENGTH / 1000); // //Debug.Log("Scale exactGameUpdateLength: " + factor); // exactGameUpdateLength = exactGameUpdateLength * factor; //} //执行逻辑帧 acumulativeTime += deltaTime * 1000; if (acumulativeTime >= exactGameUpdateLength) { acumulativeTime -= exactGameUpdateLength; //计算需执行的逻辑帧数量(叠帧) int gameUpdateNum = CalcGameUpdateNumPerLoop(); for (int i = 0; i < gameUpdateNum && pendingGameUpdateNum > 0; ++i) { //处理回合 int indexInTurn = match.curGameUpdateID % GAME_UPDATE_PER_TURN; bool toProcessTurn = (indexInTurn == 0); if (toProcessTurn) { FrameInfo nextTurn = match.turnManager.NextTurn(); if (nextTurn == null) //等回合,不执行逻辑帧 { break; } match.ProcessTurn(nextTurn, TurnController.deltaTime); } //Debug.Log("Turn:" + match.turnManager.CurTurnID + " GameUpdateIndex:" + indexInTurn + // " PendingGameUpdateNum:" + pendingGameUpdateNum); //执行逻辑帧 match.GameUpdate(TurnController.deltaTime); match.GameLateUpdate(TurnController.deltaTime); //* //发送关键数据校验 if (toProcessTurn && match is GameMatch_PVP) { match.turnManager.SendTurnCheckData(); } //*/ --pendingGameUpdateNum; } } }
public override int Capture(FrameInfo frame) { var res = new Result(-1); try { //Try to get the duplicated output frame within given time. res = DuplicatedOutput.TryAcquireNextFrame(0, out var info, out var resource); //Somehow, it was not possible to retrieve the resource or any frame. if (res.Failure || resource == null || info.AccumulatedFrames == 0) { resource?.Dispose(); return(FrameCount); } //Copy resource into memory that can be accessed by the CPU. using (var screenTexture = resource.QueryInterface <Texture2D>()) { //Copies from the screen texture only the area which the user wants to capture. Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), StagingTexture, 0); } //Get the desktop capture texture. var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None); if (data.IsEmpty) { //frame.WasDropped = true; //BlockingCollection.Add(frame); Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); resource.Dispose(); return(FrameCount); } #region Get image data var bitmap = new System.Drawing.Bitmap(Width, Height, PixelFormat.Format32bppArgb); var boundsRect = new System.Drawing.Rectangle(0, 0, Width, Height); //Copy pixels from screen capture Texture to the GDI bitmap. var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat); var sourcePtr = data.DataPointer; var destPtr = mapDest.Scan0; for (var y = 0; y < Height; y++) { //Copy a single line. Utilities.CopyMemory(destPtr, sourcePtr, Width * 4); //Advance pointers. sourcePtr = IntPtr.Add(sourcePtr, data.RowPitch); destPtr = IntPtr.Add(destPtr, mapDest.Stride); } //Release source and dest locks. bitmap.UnlockBits(mapDest); //Set frame details. FrameCount++; frame.Path = $"{Project.FullPath}{FrameCount}.png"; frame.Delay = FrameRate.GetMilliseconds(); frame.Image = bitmap; BlockingCollection.Add(frame); #endregion Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); resource.Dispose(); return(FrameCount); } catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { return(FrameCount); } catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Result.Code || se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceReset.Result.Code) { //When the device gets lost or reset, the resources should be instantiated again. DisposeInternal(); Initialize(); return(FrameCount); } catch (Exception ex) { LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX."); OnError.Invoke(ex); return(FrameCount); } finally { try { //Only release the frame if there was a sucess in capturing it. if (res.Success) { DuplicatedOutput.ReleaseFrame(); } } catch (Exception e) { LogWriter.Log(e, "It was not possible to release the frame."); } } }
public abstract void PredictFrameSize([In, Out] FrameInfo frame);
public override int ManualCapture(FrameInfo frame, bool showCursor = false) { var res = new Result(-1); try { //Try to get the duplicated output frame within given time. res = DuplicatedOutput.TryAcquireNextFrame(1000, out var info, out var resource); //Checks how to proceed with the capture. It could have failed, or the screen, cursor or both could have been captured. if (res.Failure || resource == null || (!showCursor && info.AccumulatedFrames == 0) || (showCursor && info.AccumulatedFrames == 0 && info.LastMouseUpdateTime <= LastProcessTime)) { //Somehow, it was not possible to retrieve the resource, frame or metadata. //frame.WasDropped = true; //BlockingCollection.Add(frame); resource?.Dispose(); return(FrameCount); } else if (showCursor && info.AccumulatedFrames == 0 && info.LastMouseUpdateTime > LastProcessTime) { //Gets the cursor shape if the screen hasn't changed in between, so the cursor will be available for the next frame. GetCursor(null, info, frame); resource.Dispose(); return(FrameCount); } //Saves the most recent capture time. LastProcessTime = Math.Max(info.LastPresentTime, info.LastMouseUpdateTime); //Copy resource into memory that can be accessed by the CPU. using (var screenTexture = resource.QueryInterface <Texture2D>()) { if (showCursor) { //Copies from the screen texture only the area which the user wants to capture. Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), BackingTexture, 0); //Copy the captured desktop texture into a staging texture, in order to show the mouse cursor and not make the captured texture dirty with it. Device.ImmediateContext.CopyResource(BackingTexture, StagingTexture); //Gets the cursor image and merges with the staging texture. GetCursor(StagingTexture, info, frame); } else { //Copies from the screen texture only the area which the user wants to capture. Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), StagingTexture, 0); } } //Get the desktop capture texture. var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None); if (data.IsEmpty) { //frame.WasDropped = true; //BlockingCollection.Add(frame); Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); resource.Dispose(); return(FrameCount); } #region Get image data var bitmap = new System.Drawing.Bitmap(Width, Height, PixelFormat.Format32bppArgb); var boundsRect = new System.Drawing.Rectangle(0, 0, Width, Height); //Copy pixels from screen capture Texture to the GDI bitmap. var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat); var sourcePtr = data.DataPointer; var destPtr = mapDest.Scan0; for (var y = 0; y < Height; y++) { //Copy a single line. Utilities.CopyMemory(destPtr, sourcePtr, Width * 4); //Advance pointers. sourcePtr = IntPtr.Add(sourcePtr, data.RowPitch); destPtr = IntPtr.Add(destPtr, mapDest.Stride); } //Release source and dest locks. bitmap.UnlockBits(mapDest); //Set frame details. FrameCount++; frame.Path = $"{Project.FullPath}{FrameCount}.png"; frame.Delay = FrameRate.GetMilliseconds(); frame.Image = bitmap; BlockingCollection.Add(frame); #endregion Device.ImmediateContext.UnmapSubresource(StagingTexture, 0); resource.Dispose(); return(FrameCount); } catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { return(FrameCount); } catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Result.Code || se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceReset.Result.Code) { //When the device gets lost or reset, the resources should be instantiated again. DisposeInternal(); Initialize(); return(FrameCount); } catch (Exception ex) { LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX."); MajorCrashHappened = true; OnError.Invoke(ex); return(FrameCount); } finally { try { //Only release the frame if there was a success in capturing it. if (res.Success) { DuplicatedOutput.ReleaseFrame(); } } catch (Exception e) { LogWriter.Log(e, "It was not possible to release the frame."); } } }
public UncompressedFrame Decompress(CompressedFrame compressedFrame) { FrameInfo frameInfo; IPooled<byte[]> resultBuffer; fixed (byte* source = compressedFrame.DataPooled.Item) { var compressedFrameInfo = *(CompressedFrameInfo*)source; frameInfo = new FrameInfo(compressedFrameInfo.Type, compressedFrameInfo.Timestamp, compressedFrameInfo.MostDetailedMip, compressedFrameInfo.ColorDiffThreshold, compressedFrameInfo.OriginalWidth, compressedFrameInfo.OriginalHeight, compressedFrameInfo.MouseX, compressedFrameInfo.MouseY); resultBuffer = byteArrayPool.Extract(frameInfo.UncompressedSize); var partInfoBuffer = partInfoArrayPool.Extract(); var auxiliaryBuffer = byteArrayPool.Extract(frameInfo.UncompressedSize); fixed (byte* auxiliary = auxiliaryBuffer.Item) fixed (byte* lut = dottedEncodingReadLut) fixed (byte* result = resultBuffer.Item) { var lutLocal = lut; var partInfos = partInfoBuffer.Item; var partOffsetsTable = (int*)(source + CompressedFrameInfo.Size); FillPartInfosForDecompression(partInfos, frameInfo, source, auxiliary, result, partOffsetsTable); for (int i = 0; i < PartCount; i++) //Parallel.For(0, PartCount, i => DecompressPart(i, partInfos, lutLocal);//); } auxiliaryBuffer.Release(); partInfoBuffer.Release(); } return new UncompressedFrame(frameInfo, resultBuffer); }
private unsafe void DoTest(int width, int height, Func<int, uint> getPixel) { var frameInfo = new FrameInfo(FrameType.Relative, 123456.789f, 0, 0, width, height, 0, 0); var uncompressedSizeInPixels = frameInfo.UncompressedSize / 4; var pixels = Enumerable.Range(0, uncompressedSizeInPixels).Select(getPixel).ToArray(); FillAlpha(pixels); var frame = new UncompressedFrame(frameInfo, byteArrayPool.Extract(uncompressedSizeInPixels * 4)); fixed (byte* frameData = frame.DataPooled.Item) { var frameDataUint = (uint*)frameData; for (int i = 0; i < uncompressedSizeInPixels; i++) frameDataUint[i] = pixels[i]; } var compressedFrame = codec.Compress(frame); Console.WriteLine(compressedFrame.CompressedSize); var decompressedFrame = codec.Decompress(compressedFrame); Assert.That(decompressedFrame.Info.AlignedWidth, Is.EqualTo(frame.Info.AlignedWidth)); Assert.That(decompressedFrame.Info.AlignedHeight, Is.EqualTo(frame.Info.AlignedHeight)); Assert.That(decompressedFrame.Info.Timestamp, Is.EqualTo(frame.Info.Timestamp)); var resultPixels = new uint[uncompressedSizeInPixels]; fixed (byte* resultData = decompressedFrame.DataPooled.Item) { var resultDataUint = (uint*)resultData; for (int i = 0; i < uncompressedSizeInPixels; i++) resultPixels[i] = resultDataUint[i] & 0x00FFFFFF; } EraseAlpha(pixels); Assert.That(resultPixels, Is.EqualTo(pixels)); }
private static void FillPartInfosForDecompression(PartInfo[] partInfos, FrameInfo frameInfo, byte* source, byte* auxiliary, byte* result, int* partOffsetsTable) { int typicalPartSizeInPixelTuples = frameInfo.UncompressedSize / 16 / PartCount; int typicalSizeInBytes = typicalPartSizeInPixelTuples * 16; for (int i = 0; i < PartCount; i++) partInfos[i] = new PartInfo { Source = source + HeaderSize + partOffsetsTable[i], Auxiliary = auxiliary + i * typicalSizeInBytes, Result = result + i * typicalSizeInBytes, UncompressedSize = typicalSizeInBytes }; partInfos[LastPartIndex].UncompressedSize = frameInfo.UncompressedSize - (PartCount - 1) * typicalSizeInBytes; }
public void UpdateFrame(FrameInfo frame) { }
public abstract void FrameAdvance([In, Out] FrameInfo frame);
/// <summary> /// Gets the create Frame from the create form screen /// </summary> /// <returns></returns> public override FrameInfo GetHostedFrameInfo() { FrameInfo frameInfo = new FrameInfo() { Name = "create" }; return frameInfo; }
public virtual void Save(FrameInfo info) { }
private static void FillPartInfosForCompression(PartInfo[] partInfos, FrameInfo frameInfo, byte* source, byte* auxiliary, byte* result) { int typicalPartSizeInPixelTuples = frameInfo.UncompressedSize / 16 / PartCount; for (int i = 0; i < PartCount; i++) partInfos[i] = new PartInfo { Source = source + i * typicalPartSizeInPixelTuples * 16, Auxiliary = auxiliary + i * typicalPartSizeInPixelTuples * 24, Result = result + HeaderSize + i * typicalPartSizeInPixelTuples * 24, UncompressedSize = typicalPartSizeInPixelTuples * 16 }; partInfos[LastPartIndex].UncompressedSize = frameInfo.UncompressedSize - (PartCount - 1) * typicalPartSizeInPixelTuples * 16; }
public virtual int Capture(FrameInfo frame) { return(0); }
private Browser GetContentBlockFrame() { FrameInfo frameInfo = new FrameInfo(string.Empty, string.Empty, "javascript:\"\"", 1); Browser frame = ActiveBrowser.Frames[frameInfo]; return frame; }
public virtual int CaptureWithCursor(FrameInfo frame) { return(0); }
/// <summary> /// Enters the new title. /// </summary> /// <param name="title">The image title.</param> public void EnterNewTitleInPropertiesDialogAndPublish(string title) { FrameInfo frameInfo = new FrameInfo(string.Empty, string.Empty, "~/Sitefinity/Dialog/ContentViewEditDialog", string.Empty, 1, false, false); Manager.Current.ActiveBrowser.WaitForFrame(frameInfo); var frames = Manager.Current.ActiveBrowser.Frames; frames[0].WaitForAsyncOperations(); HtmlInputText titleField = frames[0].Find.ByExpression<HtmlInputText>("tagName=input", "id=?TitleFieldControl_0_ctl00_0_ctl00_0_textBox_write_0") .AssertIsPresent("Image title field"); titleField.Text = string.Empty; titleField.Text = title; HtmlAnchor publishBtn = frames[0].Find.ByExpression<HtmlAnchor>("class=sfLinkBtn sfSave", "title=~Publish", "id=?_Publish").AssertIsPresent("Publish button"); publishBtn.Click(); ActiveBrowser.WaitForAsyncOperations(); ActiveBrowser.RefreshDomTree(); }
public virtual Task <int> CaptureWithCursorAsync(FrameInfo frame) { return(null); }
protected override void Initialize() { logger = new SLLogger(); frameinfo = new FrameInfo(); audio = new SLAudio(SLConfig["content"] + "StiLib", SLConfig["content"] + "SLMWB", SLConfig["content"] + "SLSWB", SLConfig["content"] + "SLSB"); audio.Update(); audio.StartBgMusic("BgMusic"); BarPara bpara = BarPara.Default; bpara.width = 4.0f; bpara.height = 1.0f; bpara.BasePara.direction = 0.0f; bpara.BasePara.speed = 10.0f; bpara.BasePara.space = 10.0f; bpara.BasePara.center = new Vector3(-2.0f, -2.0f, 0.0f); bpara.BasePara.color = Color.SeaGreen; bar = new Bar(GraphicsDevice, SLConfig, bpara); GratingPara gpara = GratingPara.Default; gpara.shape = Shape.Circle; gpara.gratingtype = GratingType.Sinusoidal; gpara.BasePara.center = new Vector3(2.0f, 2.0f, 0.0f); gpara.lhcolor = Color.OrangeRed; gpara.rlcolor = new Color(0f, 1f, 0f, 1f); gpara.BasePara.diameter = 7.0f; gpara.sf = 0.5f; gpara.contrast = 0.8f; gpara.luminance = 0.3f; gpara.maskpara.BasePara.diameter = 1.2f; grating = new Grating(GraphicsDevice, Services, "Content", gpara); text = new Text(GraphicsDevice, Services, "Content", "Arial"); image = new Image(GraphicsDevice, Services, "Content", "Turtle"); quad = new SLQuad(GraphicsDevice, Services, "Content", "StiLib_Logo"); model = new SLModel(GraphicsDevice, Services, "Content", "earth"); video = new SLVideo(GraphicsDevice, Services, "Content", "Butterfly"); point = new Primitive(GraphicsDevice, PrimitivePara.Default); circle = new Primitive(GraphicsDevice, PrimitivePara.Circle(5f, Color.Azure, false)); disk = new Primitive(GraphicsDevice, PrimitivePara.Circle(0.3f, Color.DarkBlue, 4 * Vector3.UnitY,Color.DarkBlue, 100, true)); cross = new Primitive(GraphicsDevice, PrimitivePara.Cross(3f, Color.Green, 4 * Vector3.UnitX)); arrow = new Primitive(GraphicsDevice, PrimitivePara.Arrow(4f, Color.Red, -4 * Vector3.UnitX, 60f, 1f)); radialcircle = new Primitive(GraphicsDevice, PrimitivePara.Circle(5f, new Color(0f, 0f, 0f, 0.5f),Vector3.Zero, new Color(0f, 0f, 0f, 0.0f),100,true)); gaussian = new Primitive(GraphicsDevice, PrimitivePara.Gaussian(10, 1.5f, Color.Gray, Vector3.Zero)); disk.Para.BasePara.space = 10; model.Para.BasePara.rotationspeed3D = Vector3.UnitY; model.ProjectionType = ProjectionType.Perspective; //model.globalCamera.NearPlane = 0.1f; CollectionPara cpara = CollectionPara.Default; cpara.BasePara.center = Vector3.UnitX * 5; cpara.CollectionCenter = new Vector3(2f, 3f, 0.0f); cpara.CollectionSpeed = new Vector3(0.02f, 0.03f, 0.0f); vsc = new VSCollection<Primitive>(50, GraphicsDevice, cross, cpara); //vscp = new vscPrimitive(100, GraphicsDevice, disk, Services, "Content",cpara); timer = new SLTimer(); timer.Start(); }
public override int CaptureWithCursor(FrameInfo frame) { try { new System.Security.Permissions.UIPermission(System.Security.Permissions.UIPermissionWindow.AllWindows).Demand(); //var success = Native.BitBlt(CompatibleDeviceContext, 0, 0, Width, Height, WindowDeviceContext, Left, Top, Native.CopyPixelOperation.SourceCopy | Native.CopyPixelOperation.CaptureBlt); var success = Native.StretchBlt(CompatibleDeviceContext, 0, 0, StartWidth, StartHeight, WindowDeviceContext, Left, Top, Width, Height, Native.CopyPixelOperation.SourceCopy | Native.CopyPixelOperation.CaptureBlt); if (!success) { return(FrameCount); } #region Cursor try { var cursorInfo = new Native.CursorInfo(); cursorInfo.cbSize = Marshal.SizeOf(cursorInfo); if (Native.GetCursorInfo(out cursorInfo)) { if (cursorInfo.flags == Native.CursorShowing) { var hicon = Native.CopyIcon(cursorInfo.hCursor); if (hicon != IntPtr.Zero) { if (Native.GetIconInfo(hicon, out var iconInfo)) { frame.CursorX = cursorInfo.ptScreenPos.X - Left; frame.CursorY = cursorInfo.ptScreenPos.Y - Top; //(int)(SystemParameters.CursorHeight * Scale) //(int)(SystemParameters.CursorHeight * Scale) var ok = Native.DrawIconEx(CompatibleDeviceContext, frame.CursorX - iconInfo.xHotspot, frame.CursorY - iconInfo.yHotspot, cursorInfo.hCursor, 0, 0, CursorStep, IntPtr.Zero, 0x0003); if (!ok) { CursorStep = 0; Native.DrawIconEx(CompatibleDeviceContext, frame.CursorX - iconInfo.xHotspot, frame.CursorY - iconInfo.yHotspot, cursorInfo.hCursor, 0, 0, CursorStep, IntPtr.Zero, 0x0003); } else { CursorStep++; } } Native.DeleteObject(iconInfo.hbmColor); Native.DeleteObject(iconInfo.hbmMask); } Native.DestroyIcon(hicon); } Native.DeleteObject(cursorInfo.hCursor); } } catch (Exception) { //LogWriter.Log(e, "Impossible to get the cursor"); } #endregion //Set frame details. FrameCount++; frame.Path = $"{Project.FullPath}{FrameCount}.png"; frame.Delay = FrameRate.GetMilliseconds(SnapDelay); frame.Image = Image.FromHbitmap(CompatibleBitmap); BlockingCollection.Add(frame); } catch (Exception) { //LogWriter.Log(ex, "Impossible to get the screenshot of the screen"); } return(FrameCount); }
public static DatFileDesc ParseTextWithErrorsReturn(string text, string path, ref List<gfErrors> errors, cProject cp = null) { DatFileDesc result = null; try { Stopwatch sw = new Stopwatch(); sw.Start(); if (text.Trim().Length == 0) return null; result = new DatFileDesc() { header = new Header(), frames = new List<FrameInfo>(), regions = new List<RegionInfo>() }; errors = new List<gfErrors>(); StringReader sr = new StringReader(text); string line; int nline = 0; string oTag = ""; string cTag = ""; RegionInfo cri = null; WeaponStrListInfoEntry wsl = null; bool isRegion = false; bool isRegionend = false; while ((line = sr.ReadLine()) != null) { nline++; line = line.Trim(); if (line.Length == 0) continue; //--------------------------------------------------------------------------------------------------------------------------------- if (line.Contains("#region")) { cri = new RegionInfo(); isRegion = true; oTag = "#region"; string[] astr = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (astr.Length > 1) cri.caption = astr[1]; cri.oline = nline; result.regions.Add(cri); // continue; } if (line.Contains("#endregion")) { cTag = "#endregion"; if (oTag != "#region") errors.Add(new gfErrors("Closing tag #endregion found, but where opening tag?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; cri.cline = nline; continue; } if (line == "<bmp_begin>") { result.header.foldcaption = line; result.header.oline = nline; oTag = "<bmp_begin>"; continue; } if (line == "<weapon_strength_list>") { result.wsl_oline = nline; if (cTag != "<bmp_end>") errors.Add(new gfErrors("Closing tag <bmp_end> expected", nline, path, Utils.Project.GetNameProject(cp))); oTag = "<weapon_strength_list>"; continue; } if (line.Contains("<frame>") || line == "<frame_end>") { if (oTag == "<bmp_begin>") errors.Add(new gfErrors("Closing tag <bmp_end> expected", nline, path, Utils.Project.GetNameProject(cp))); if (oTag == "<weapon_strength_list>") errors.Add(new gfErrors("Closing tag <weapon_strength_list_end> expected", nline, path, Utils.Project.GetNameProject(cp))); oTag = "frame"; break; } //--------------------------------------------------------------------------------------------------------------------------------- if (line == "<bmp_end>") { if (result.header.cline==-1) result.header.cline = nline; cTag = "<bmp_end>"; if (oTag != "<bmp_begin>" && oTag != "#region") errors.Add(new gfErrors("Closing tag <bmp_end> found, but where opening tag?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } if (line == "<weapon_strength_list_end>") { result.wsl_cline = nline; cTag = "<weapon_strength_list_end>"; if (oTag != "<weapon_strength_list>") errors.Add(new gfErrors("Closing tag <weapon_strength_list_end> found, but where opening tag?", nline, path, Utils.Project.GetNameProject(cp))); if (oTag == "<bmp_begin>") errors.Add(new gfErrors("Closing tag <bmp_end> expected", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; break; } //----------------------------------------Parsing----------------------------------------------------------------------------------------- if (oTag == "<bmp_begin>") { #region Parse bmp_begin if (line.Contains("file")) { FileDesc fd = new FileDesc(); string st = GetTextBetweenBraces(line); string[] s2 = st.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); if (s2.Length > 1) { try { fd.firstFrame = Convert.ToInt32(s2[0]); fd.lastFrame = Convert.ToInt32(s2[1]); } catch { } } List<PropDesc> pd = GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag); if (pd.Count > 0) fd.path = pd[0].value; for (int i = 1; i < pd.Count; i++) { try { switch (pd[i].name) { case "w:": fd.width = Convert.ToInt32(pd[i].value); break; case "h:": fd.height = Convert.ToInt32(pd[i].value); break; case "row:": fd.col = Convert.ToInt32(pd[i].value); break; case "col:": fd.row = Convert.ToInt32(pd[i].value); break; } } catch { } } result.header.files.Add(fd); } else { PropDesc pd = GetProperty(line); result.header.properties.Add(pd); if (pd.name != null && pd.value != null) { if (!pd.name.Contains("sound") && !pd.name.Contains("file") && pd.name != "name:" && pd.name != "head:" && pd.name != "small:") { if (!isStringConsistsDigits(pd.value)) errors.Add(new gfErrors("Number value expected", nline, path, Utils.Project.GetNameProject(cp))); } } } #endregion continue; } if (oTag == "<weapon_strength_list>") { #region Parse weapon_strength_list block if (line.Contains("entry:")) { wsl = new WeaponStrListInfoEntry(); string[] st3 = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); wsl.number = Convert.ToInt32(st3[1]); } else { if (wsl != null) { wsl.props.AddRange(GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag)); result.wsl.Add(wsl); } } #endregion continue; } //--------------------------------------End parsing----------------------------------------------------------------------------------------- if (line == "<bmp_end>") { if (oTag != "<bmp_begin>") errors.Add(new gfErrors("Closing tag <bmp_end> found, but where opening tag?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } if (line == "<weapon_strength_list_end>") { if (oTag != "<weapon_strength_list>") errors.Add(new gfErrors("Closing tag <weapon_strength_list_end> found, but where opening tag?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } } if (line == null) return result; //---------------------------------------End parsing frame_begin and weapon list------------------------------------------------------------------------------------------ if (result.header.files.Count > 0) { firstPic = result.header.files[0].firstFrame; lastPic = result.header.files[0].lastFrame; for (int i = 1; i < result.header.files.Count; i++) { if (result.header.files[i].firstFrame < firstPic) firstPic = result.header.files[i].firstFrame; if (result.header.files[i].lastFrame > lastPic) lastPic = result.header.files[i].lastFrame; } } /////////////////////////////// bool isFrame = false; bool isFrameend = false; FrameInfo cfi = null; /* bool isBpoint = false; bool isBpointend = false; bool isCpoint = false; bool isCpointend = false; bool isWpoint = false; bool isWpointend = false; bool isOpoint = false; bool isOpointend = false; bool isBdy = false; bool isBdyend = false; bool isItr = false; bool isItrend = false;*/ //FrameInfo prev = new FrameInfo(); nline--; do { nline++; line = line.Trim(); if (line.Length == 0) continue; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (line.Contains("#region") || line.Contains("<frame>") || line == "bpoint:" || line == "wpoint:" || line == "cpoint:" || line == "opoint:" || line == "bdy:" || line == "itr:" || line == "<frame_end>") { if (oTag == "bpoint:") if (cTag != "bpoint_end:") { cfi.lnst.cl_bpoint = nline - 1; errors.Add(new gfErrors("Closing tag \"bpoint_end:\" expected", nline, path, Utils.Project.GetNameProject(cp))); } if (oTag == "wpoint:") if (cTag != "wpoint_end:") { cfi.lnst.cl_wpoint = nline - 1; errors.Add(new gfErrors("Closing tag \"wpoint_end:\" expected", nline, path, Utils.Project.GetNameProject(cp))); } if (oTag == "cpoint:") if (cTag != "cpoint_end:") { cfi.lnst.cl_cpoint = nline - 1; errors.Add(new gfErrors("Closing tag \"cpoint_end:\" expected", nline, path, Utils.Project.GetNameProject(cp))); } if (oTag == "opoint:") if (cTag != "opoint_end:") { cfi.lnst.cl_opoint = nline - 1; errors.Add(new gfErrors("Closing tag \"opoint_end:\" expected", nline, path, Utils.Project.GetNameProject(cp))); } if (oTag == "bdy:") if (cTag != "bdy_end:") { cfi.lnst.cl_bdy.Add(nline - 1); errors.Add(new gfErrors("Closing tag \"bdy_end:\" expected", nline, path, Utils.Project.GetNameProject(cp))); } if (oTag == "itr:") if (cTag != "itr_end:") { cfi.lnst.cl_itr.Add(nline - 1); errors.Add(new gfErrors("Closing tag \"itr_end:\" expected", nline, path, Utils.Project.GetNameProject(cp))); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (line.Contains("#region")) { if (isRegion && !isRegionend) errors.Add(new gfErrors("Closing tag #endregion expected", nline, path, Utils.Project.GetNameProject(cp))); isRegion = true; isRegionend = false; oTag = "#region"; // if (cri != null) // result.regions.Add(cri); cri = new RegionInfo(); string[] astr = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (astr.Length > 1) cri.caption = astr[1]; cri.oline = nline; result.regions.Add(cri); continue; } if (line.Contains("<frame>")) { if (line.Contains("dummy")) { } if (isFrame == true && isFrameend == false) { cfi.cline = nline - 1; errors.Add(new gfErrors("Closing tag <frame_end> expected", nline, path, Utils.Project.GetNameProject(cp))); } isFrame = true; isFrameend = false; oTag = "<frame>"; if (cfi != null) { //prev = cfi; result.frames.Add(cfi); } cfi = new FrameInfo(); string[] astr = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (astr.Length > 1) try { cfi.number = Convert.ToInt32(astr[1]); } catch { cfi.number = -1; } //////////////// for (int i = 0; i < result.frames.Count; i++) { if (cfi.number == result.frames[i].number) { errors.Add(new gfErrors("Frame with this number value already exists", nline, path, Utils.Project.GetNameProject(cp))); break; } } //if (cfi.number < prev.number) // errors.Add(new gfErrors("Frame number value must be greater than number value in previous frames", nline, path, Utils.Project.GetNameProject(cp))); //////////////// if (astr.Length > 2) cfi.caption = astr[2]; else cfi.number = null; cfi.oline = nline; cfi.foldcaption = line; continue; } if (line == "bpoint:") { if (oTag == "<frame>") cfi.lastheaderline = nline - 1; oTag = "bpoint:"; cfi.lnst.ol_bpoint = nline; continue; } if (line == "wpoint:") { if (oTag == "<frame>") cfi.lastheaderline = nline - 1; oTag = "wpoint:"; cfi.lnst.ol_wpoint = nline; continue; } if (line == "bdy:") { if (oTag == "<frame>") cfi.lastheaderline = nline - 1; oTag = "bdy:"; cfi.lnst.ol_bdy.Add(nline); cfi.bdy.Add(new List<PropDesc>()); continue; } if (line == "itr:") { if (oTag == "<frame>") cfi.lastheaderline = nline - 1; oTag = "itr:"; cfi.lnst.ol_itr.Add(nline); cfi.itr.Add(new List<PropDesc>()); continue; } if (line == "cpoint:") { if (oTag == "<frame>") cfi.lastheaderline = nline - 1; oTag = "cpoint:"; cfi.lnst.ol_cpoint = nline; continue; } if (line == "opoint:") { if (oTag == "<frame>") cfi.lastheaderline = nline - 1; oTag = "opoint:"; cfi.lnst.ol_opoint = nline; continue; } ////////////////////////////////////////////////////////// #region Check errors (if open tag miss) if (line == "#endregion") { if (isRegion == false) errors.Add(new gfErrors("Found #endregion tag but where opening tag #region?", nline, path, Utils.Project.GetNameProject(cp))); isRegionend = true; oTag = ""; if (isRegion == true && isRegion == true) isRegion = false; if (cri != null) cri.cline = nline; continue; } if (line == "<frame_end>") { if (cfi.lastheaderline==-1) cfi.lastheaderline = nline - 1; if (isFrame == false) errors.Add(new gfErrors("Found <frame_end> tag but where opening tag <frame>?", nline, path, Utils.Project.GetNameProject(cp))); isFrameend = true; oTag = ""; if (isFrame == true && isFrameend == true) isFrame = false; if (cfi != null) cfi.cline = nline; // continue; } if (line == "bpoint_end:") { cfi.lnst.cl_bpoint = nline; if (oTag != "bpoint:") errors.Add(new gfErrors("Found \"bpoint_end:\" tag but where opening tag \"bpoint:\"?", nline, path, Utils.Project.GetNameProject(cp))); //isBpoint = true; //oTag = ""; cTag = "bpoint_end:"; continue; } if (line == "wpoint_end:") { cfi.lnst.cl_wpoint = nline; if (oTag != "wpoint:") errors.Add(new gfErrors("Found \"wpoint_end:\" tag but where opening tag \"wpoint:\"?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } if (line == "bdy_end:") { cfi.lnst.cl_bdy.Add(nline); if (oTag != "bdy:") errors.Add(new gfErrors("Found \"bdy_end:\" tag but where opening tag \"bdy:\"?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } if (line == "itr_end:") { cfi.lnst.cl_itr.Add(nline); if (oTag != "itr:") errors.Add(new gfErrors("Found \"itr_end:\" tag but where opening tag \"itr:\"?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } if (line == "cpoint_end:") { cfi.lnst.cl_cpoint = nline; if (oTag != "cpoint:") errors.Add(new gfErrors("Found \"cpoint_end:\" tag but where opening tag \"cpoint:\"?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } if (line == "opoint_end:") { cfi.lnst.cl_opoint = nline; if (oTag != "opoint:") errors.Add(new gfErrors("Found \"opoint_end:\" tag but where opening tag \"opoint:\"?", nline, path, Utils.Project.GetNameProject(cp))); oTag = ""; continue; } #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (oTag == "<frame>") { if (cfi.firstheaderline == -1) cfi.firstheaderline = nline; cfi.header.AddRange(GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag)); continue; } if (oTag == "bpoint:" && cfi != null) { cfi.bpoint.AddRange((GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag))); continue; } if (oTag == "wpoint:" && cfi != null) { cfi.wpoint.AddRange((GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag))); continue; } if (oTag == "bdy:" && cfi != null) { cfi.bdy[cfi.bdy.Count - 1].AddRange((GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag))); continue; } if (oTag == "itr:" && cfi != null) { cfi.itr[cfi.itr.Count - 1].AddRange((GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag))); continue; } if (oTag == "cpoint:" && cfi != null) { cfi.cpoint.AddRange((GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag))); continue; } if (oTag == "opoint:" && cfi != null) { cfi.opoint.AddRange((GetPropertiesFromString(line, ref errors, nline, path, Utils.Project.GetNameProject(cp), oTag))); continue; } } while ((line = sr.ReadLine()) != null); if (isRegion == true && isRegionend == false) errors.Add(new gfErrors("Closing tag #endregion expected", nline, path, Utils.Project.GetNameProject(cp))); if (isFrame == true && isFrameend == false) errors.Add(new gfErrors("Closing tag <frame_end> expected", nline, path, Utils.Project.GetNameProject(cp))); sw.Stop(); result.frames.Add(cfi); // G.mainWindow.teOutput.AppendText // ("ParseDatFileFromString-время прошло: " + sw.ElapsedMilliseconds + " миллисекунд" + Environment.NewLine); // G.mainWindow.teOutput.ScrollToEnd(); } catch (Exception ex) { new wException(ex).ShowDialog(); } return result; }
/// <summary> /// Calculates the difference between one given frame and another. /// </summary> /// <param name="first">The first frame to compare.</param> /// <param name="second">The second frame to compare.</param> /// <returns>The similarity between the two frames in percentage.</returns> public static double CalculateDifference(FrameInfo first, FrameInfo second) { #region Get Image Info var imageAux1 = first.Path.From(); var imageAux2 = second.Path.From(); var image1 = new PixelUtilOld(imageAux1); //First image var image2 = new PixelUtilOld(imageAux2); //Last image image1.LockBits(); image2.LockBits(); var height = imageAux1.Height; var width = imageAux1.Width; var equalCount = 0; #endregion //Only use Parallel if the image is big enough. if (width * height > 150000) { #region Parallel Loop //x - width - sides Parallel.For(0, width, x => { //y - height - up/down for (var y = 0; y < height; y++) { if (image1.GetPixel(x, y) == image2.GetPixel(x, y)) { Interlocked.Increment(ref equalCount); } //equalCount = equalCount + (image1.GetPixel(x, y) == image2.GetPixel(x, y) ? 1 : 0); } }); #endregion } else { #region Sequential Loop //x - width - sides for (var x = 0; x < width; x++) { //y - height - up/down for (var y = 0; y < height; y++) { equalCount = equalCount + (image1.GetPixel(x, y) == image2.GetPixel(x, y) ? 1 : 0); } } #endregion } image1.UnlockBits(); image2.UnlockBits(); GC.Collect(1); return(Other.CrossMultiplication(width * height, equalCount, null)); }
/// <summary> /// Creates the render elements of all threads over one frame. /// </summary> /// <param name="frame">Instance that stores all thread data.</param> /// <returns>Returns a <c>Panel</c> (<c>Canvas</c>) containing rendered thread elements for the given frame.</returns> private FrameworkElement CreateFrameElement(FrameInfo frame) { if (frame == null) throw new ArgumentNullException("frame"); if (frame.ThreadItems.Count == 0) return null; if (frame.ThreadItems.Count > maxThreadCount) { maxThreadCount = frame.ThreadItems.Count; InvalidateVisual(); } Canvas canvas = new Canvas(); int threadIndex = 0; foreach (ThreadInfo thread in frame.ThreadItems) { UIElement frameThread = CreateFrameThreadElement(frame.BeginTime, thread); if (frameThread != null) { frameThread.SetValue(Canvas.TopProperty, threadIndex * ThreadLineHeight); canvas.Children.Add(frameThread); } threadIndex++; } VisualElement frameDelimiter = new VisualElement(CreateLine(maxThreadCount * ThreadLineHeight)); frameDelimiter.SetValue(Canvas.LeftProperty, -(delimiterPen.Thickness / 2.0)); canvas.Children.Add(frameDelimiter); double w = (frame.EndTime - frame.BeginTime) * PixelsPerSecond; canvas.Children.Add(new VisualElement(CreateText(frame.FrameNumber.ToString(), w, ThreadLineHeight))); return canvas; }
public static extern void GetFrameInfo(out FrameInfo frameInfo);
private void allocUnwindInfo(byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind) { // The unwind info blob are followed by byte that identifies the type of the funclet // and other optional data that follows const int extraBlobData = 1; byte[] blobData = new byte[unwindSize + extraBlobData]; for (uint i = 0; i < unwindSize; i++) { blobData[i] = pUnwindBlock[i]; } // Capture the type of the funclet in unwind info blob blobData[unwindSize] = (byte)funcKind; _frameInfos[_usedFrameInfos++] = new FrameInfo((int)startOffset, (int)endOffset, blobData); }
protected internal void GetCursor(Texture2D screenTexture, OutputDuplicateFrameInformation info, FrameInfo frame) { //Prepare buffer array to hold the cursor shape. if (CursorShapeBuffer == null || info.PointerShapeBufferSize > CursorShapeBuffer.Length) { CursorShapeBuffer = new byte[info.PointerShapeBufferSize]; } //If there's a cursor shape available to be captured. if (info.PointerShapeBufferSize > 0) { //Pin the buffer in order to pass the address as parameter later. var pinnedBuffer = GCHandle.Alloc(CursorShapeBuffer, GCHandleType.Pinned); var cursorBufferAddress = pinnedBuffer.AddrOfPinnedObject(); //Load the cursor shape into the buffer. DuplicatedOutput.GetFramePointerShape(info.PointerShapeBufferSize, cursorBufferAddress, out _, out CursorShapeInfo); //If the cursor is monochrome, it will return the cursor shape twice, one is the mask. if (CursorShapeInfo.Type == 1) { CursorShapeInfo.Height /= 2; } //The buffer must be unpinned, to free resources. pinnedBuffer.Free(); } //Store the current cursor position, if it was moved. if (info.LastMouseUpdateTime != 0) { PreviousPosition = info.PointerPosition; } //TODO: In a future version, don't merge the cursor image in here, let the editor do that. //Saves the position of the cursor, so the editor can add the mouse clicks overlay later. frame.CursorX = PreviousPosition.Position.X - Left; frame.CursorY = PreviousPosition.Position.Y - Top; //If the method is supposed to simply the get the cursor shape no shape was loaded before, there's nothing else to do. //if (CursorShapeBuffer?.Length == 0 || (info.LastPresentTime == 0 && info.LastMouseUpdateTime == 0) || !info.PointerPosition.Visible) if (screenTexture == null || CursorShapeBuffer?.Length == 0)// || !info.PointerPosition.Visible) { return; } //Don't let it bleed beyond the top-left corner. var left = Math.Max(frame.CursorX, 0); var top = Math.Max(frame.CursorY, 0); var offsetX = Math.Abs(Math.Min(0, frame.CursorX)); var offsetY = Math.Abs(Math.Min(0, frame.CursorY)); //Adjust the offset, so it's possible to add the highlight correctly later. frame.CursorX += CursorShapeInfo.HotSpot.X; frame.CursorY += CursorShapeInfo.HotSpot.Y; if (CursorShapeInfo.Width - offsetX < 0 || CursorShapeInfo.Height - offsetY < 0) { return; } //The staging texture must be able to hold all pixels. if (CursorStagingTexture == null || CursorStagingTexture.Description.Width < CursorShapeInfo.Width - offsetX || CursorStagingTexture.Description.Height < CursorShapeInfo.Height - offsetY) { //In order to change the size of the texture, I need to instantiate it again with the new size. CursorStagingTexture?.Dispose(); CursorStagingTexture = new Texture2D(Device, new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Write, Height = CursorShapeInfo.Height - offsetY, Format = Format.B8G8R8A8_UNorm, Width = CursorShapeInfo.Width - offsetX, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Staging }); } //The region where the cursor is located is copied to the staging texture to act as the background when dealing with masks and transparency. var region = new ResourceRegion { Left = left, Top = top, Front = 0, Right = left + CursorStagingTexture.Description.Width, Bottom = top + CursorStagingTexture.Description.Height, Back = 1 }; //Copy from the screen the region in which the cursor is located. Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, region, CursorStagingTexture, 0); //Get cursor details and draw it to the staging texture. DrawCursorShape(CursorStagingTexture, CursorShapeInfo, CursorShapeBuffer, offsetX, offsetY); //Copy back the cursor texture to the screen texture. Device.ImmediateContext.CopySubresourceRegion(CursorStagingTexture, 0, null, screenTexture, 0, left, top); }
public void ShowFrame(FrameInfo frameItem) { UIGraphics.BeginImageContextWithOptions (this.Bounds.Size, false, UIScreen.MainScreen.Scale); using (CGContext context = UIGraphics.GetCurrentContext()) { context.SetLineJoin (CGLineJoin.Round); context.SetLineCap (CGLineCap.Round); context.SetShouldAntialias (true); foreach (LayerInfo eachLayerInfo in frameItem.Layers.Values.OrderBy(s => s.ID)) { if (eachLayerInfo.DrawingItems.Count > 0) { foreach (KeyValuePair<int, DrawingInfo> eachItem in eachLayerInfo.DrawingItems) { if (eachItem.Value.DrawingType == DrawingLayerType.Drawing) { if (eachItem.Value.Brush.BrushType == BrushType.Normal) { context.SetStrokeColor (eachLayerInfo.IsCanvasActive ? eachItem.Value.LineColor : this.inactiveColor); context.SetLineWidth (eachItem.Value.Brush.Thickness); for (int i = 0; i < eachItem.Value.PathPoints.Count; i++) { PointF eachPoint = eachItem.Value.PathPoints [i]; if (i == 0) { context.MoveTo (eachPoint.X, eachPoint.Y); context.AddLineToPoint (eachPoint.X, eachPoint.Y); } else { PointF prevPoint = eachItem.Value.PathPoints [i - 1]; PointF midPoint = new PointF ((prevPoint.X + eachPoint.X) / 2f, (prevPoint.Y + eachPoint.Y) / 2f); context.MoveTo (prevPoint.X, prevPoint.Y); context.AddCurveToPoint (prevPoint.X, prevPoint.Y, midPoint.X, midPoint.Y, eachPoint.X, eachPoint.Y); }//end if else }//end for context.DrawPath (CGPathDrawingMode.Stroke); } else { SizeF brushImageSize = eachItem.Value.Brush.BrushImage.Size; if (eachItem.Value.Brush.IsSprayBrushActive != eachLayerInfo.IsCanvasActive) { eachItem.Value.Brush.SetBrushActive (eachLayerInfo.IsCanvasActive); }//end if for (int i = 0; i < eachItem.Value.PathPoints.Count; i++) { PointF eachPoint = eachItem.Value.PathPoints [i]; RectangleF rect = new RectangleF (eachPoint.X - (brushImageSize.Width / 2f), eachPoint.Y - (brushImageSize.Height / 2f), brushImageSize.Width, brushImageSize.Height); eachItem.Value.Brush.BrushImage.Draw (rect.Location); // context.SaveState(); // // context.SetBlendMode(eachLayerInfo.IsCanvasActive ? // CGBlendMode.SourceIn : // CGBlendMode.SourceAtop); // context.SetFillColor(eachLayerInfo.IsCanvasActive ? // eachItem.Value.LineColor : // this.inactiveColor); // context.FillRect(rect); // // context.RestoreState(); }//end for }//end if else } else if (eachItem.Value.DrawingType == DrawingLayerType.Image || eachItem.Value.DrawingType == DrawingLayerType.Comix || eachItem.Value.DrawingType == DrawingLayerType.Stamp || eachItem.Value.DrawingType == DrawingLayerType.Callout) { if (eachItem.Value.RotationAngle == 0) { if (!eachLayerInfo.IsCanvasActive) { UIImage imgToDraw = eachItem.Value.GetInactiveImage (this.inactiveColor); imgToDraw.Draw (eachItem.Value.ImageFrame); imgToDraw.Dispose (); } else { eachItem.Value.Image.Draw (eachItem.Value.ImageFrame); }//end if else if (eachItem.Value.DrawingType == DrawingLayerType.Callout && !string.IsNullOrEmpty (eachItem.Value.CalloutText)) { Pair<UIFont, SizeF> calloutTextParams = AnimationUtils.GetTextParamsForCallout (eachItem.Value.CalloutTextRect, eachItem.Value.CalloutText); context.SaveState (); context.SetFillColor (eachLayerInfo.IsCanvasActive ? eachItem.Value.LineColor : this.inactiveTextColor); context.SetTextDrawingMode (CGTextDrawingMode.Fill); context.SetShouldSmoothFonts (true); context.SetAllowsFontSmoothing (true); context.SetShouldAntialias (true); using (NSString nsText = new NSString(eachItem.Value.CalloutText)) { nsText.DrawString (eachItem.Value.CalloutTextRect.CenterInRect (calloutTextParams.ItemB), calloutTextParams.ItemA, UILineBreakMode.WordWrap, UITextAlignment.Center); }//end using nsText context.RestoreState (); }//end if } else { using (UIImage rotatedImage = AnimationUtils.RotateImage(eachLayerInfo.IsCanvasActive ? eachItem.Value.Image : eachItem.Value.GetInactiveImage(this.inactiveColor), eachItem.Value.ImageFrame, eachItem.Value.RotatedImageBox, eachItem.Value.RotationAngle, !eachLayerInfo.IsCanvasActive)) { rotatedImage.Draw (eachItem.Value.RotatedImageBox); }//end using rotatedImage if (eachItem.Value.DrawingType == DrawingLayerType.Callout && !string.IsNullOrEmpty (eachItem.Value.CalloutText)) { Pair<UIFont, SizeF> textParams = AnimationUtils.GetTextParamsForCallout (eachItem.Value.CalloutTextRect, eachItem.Value.CalloutText); context.SaveState (); context.SetFillColor (eachLayerInfo.IsCanvasActive ? eachItem.Value.LineColor : this.inactiveTextColor); context.SetTextDrawingMode (CGTextDrawingMode.Fill); context.SetShouldSmoothFonts (true); context.SetAllowsFontSmoothing (true); context.SetShouldAntialias (true); List<PointF> calloutTextCorners = eachItem.Value.CalloutTextRect.CenterInRect (textParams.ItemB).GetCorners (); List<PointF> rotatedCalloutTextCorners = calloutTextCorners.RotatePoints (eachItem.Value.RotationAngle, new PointF (eachItem.Value.RotatedImageBox.GetMidX (), eachItem.Value.RotatedImageBox.GetMidY ())); context.TranslateCTM (rotatedCalloutTextCorners [0].X, rotatedCalloutTextCorners [0].Y); context.RotateCTM (((float)eachItem.Value.RotationAngle * (float)LOLConstants.DegToRad)); context.TranslateCTM (-rotatedCalloutTextCorners [0].X, -rotatedCalloutTextCorners [0].Y); using (NSString nsText = new NSString(eachItem.Value.CalloutText)) { nsText.DrawString (new RectangleF (rotatedCalloutTextCorners [0].X, rotatedCalloutTextCorners [0].Y, textParams.ItemB.Width, textParams.ItemB.Height), textParams.ItemA, UILineBreakMode.WordWrap, UITextAlignment.Center); }//end using nsText context.RestoreState (); }//end if }//end if else }//end if else if }//end foreach }//end if }//end foreach if (null != this.imgDrawDisplay.Image) { this.imgDrawDisplay.Image.Dispose (); this.imgDrawDisplay.Image = null; }//end if this.imgDrawDisplay.Image = UIGraphics.GetImageFromCurrentImageContext (); }//end using context UIGraphics.EndImageContext (); }
private void CursorCapture(FrameInfo frame) { //if (_justStarted && (CursorShapeBuffer?.Length ?? 0) == 0) { //_justStarted = false; //https://stackoverflow.com/a/6374151/1735672 //Bitmap struct, is used to get the cursor shape when SharpDX fails to do so. var _infoHeader = new Native.BitmapInfoHeader(); _infoHeader.biSize = (uint)Marshal.SizeOf(_infoHeader); _infoHeader.biBitCount = 32; _infoHeader.biClrUsed = 0; _infoHeader.biClrImportant = 0; _infoHeader.biCompression = 0; _infoHeader.biHeight = -Height; //Negative, so the Y-axis will be positioned correctly. _infoHeader.biWidth = Width; _infoHeader.biPlanes = 1; try { var cursorInfo = new Native.CursorInfo(); cursorInfo.cbSize = Marshal.SizeOf(cursorInfo); if (Native.GetCursorInfo(out cursorInfo)) { if (cursorInfo.flags == Native.CursorShowing) { var hicon = Native.CopyIcon(cursorInfo.hCursor); if (hicon != IntPtr.Zero) { if (Native.GetIconInfo(hicon, out var iconInfo)) { frame.CursorX = cursorInfo.ptScreenPos.X - Left; frame.CursorY = cursorInfo.ptScreenPos.Y - Top; var bitmap = new Native.Bitmap(); var hndl = GCHandle.Alloc(bitmap, GCHandleType.Pinned); var ptrToBitmap = hndl.AddrOfPinnedObject(); Native.GetObject(iconInfo.hbmColor, Marshal.SizeOf <Native.Bitmap>(), ptrToBitmap); bitmap = Marshal.PtrToStructure <Native.Bitmap>(ptrToBitmap); hndl.Free(); //https://microsoft.public.vc.mfc.narkive.com/H1CZeqUk/how-can-i-get-bitmapinfo-object-from-bitmap-or-hbitmap _infoHeader.biHeight = bitmap.bmHeight; _infoHeader.biWidth = bitmap.bmWidth; _infoHeader.biBitCount = (ushort)bitmap.bmBitsPixel; var w = (bitmap.bmWidth * bitmap.bmBitsPixel + 31) / 8; CursorShapeBuffer = new byte[w * bitmap.bmHeight]; var windowDeviceContext = Native.GetWindowDC(IntPtr.Zero); var compatibleBitmap = Native.CreateCompatibleBitmap(windowDeviceContext, Width, Height); Native.GetDIBits(windowDeviceContext, compatibleBitmap, 0, (uint)_infoHeader.biHeight, CursorShapeBuffer, ref _infoHeader, Native.DibColorMode.DibRgbColors); //if (frame.CursorX > 0 && frame.CursorY > 0) // Native.DrawIconEx(_compatibleDeviceContext, frame.CursorX - iconInfo.xHotspot, frame.CursorY - iconInfo.yHotspot, cursorInfo.hCursor, 0, 0, 0, IntPtr.Zero, 0x0003); //Clean objects here. } Native.DeleteObject(iconInfo.hbmColor); Native.DeleteObject(iconInfo.hbmMask); } Native.DestroyIcon(hicon); } Native.DeleteObject(cursorInfo.hCursor); } } catch (Exception e) { LogWriter.Log(e, "Impossible to get the cursor"); } } }
public override void UpdateFrame(ViewportBase viewport, FrameInfo frame) { // }
/// <summary> /// Add Frame information to where it must store /// </summary> /// <param name="Data">FileStream contain Frame</param> /// <param name="FrameID">FrameID of frame</param> /// <param name="Length">Maximum available length to read</param> /// <param name="Flags">Flags of frame</param> private bool AddFrame(string FrameID, int Length, FrameFlags Flags, Stream FS) { // NOTE: All FrameIDs must be capital letters if (!FramesInfo.IsValidFrameID(FrameID)) { AddError(new ID3Exception("nonValid Frame found and dropped", FrameID, ExceptionLevels.Repaired)); return(false); } int IsText = FramesInfo.IsTextFrame(FrameID, _Version.Minor); if (IsText == 1) { TextFrame TempTextFrame = new TextFrame(FrameID, Flags, Length, FS); if (TempTextFrame.IsValid && !TextFrames.ContainsKey(FrameID)) { TextFrames.Add(FrameID, TempTextFrame); return(true); } return(false); } else if (IsText == 2) { UserTextFrame TempUserTextFrame = new UserTextFrame(FrameID, Flags, Length, FS); if (TempUserTextFrame.IsValid && FrameID != "TXXX" && !UserTextFrames.ContainsKey(FrameID)) { UserTextFrames.Add(FrameID, TempUserTextFrame); return(true); } return(false); } else if (FrameID == "LINK") { LinkFrame LF = new LinkFrame(FrameID, Flags, Length, FS); if (LF.IsValid && !LinkFrames.ContainsKey(FrameID)) { LinkFrames.Add(FrameID, LF); if (_LoadLinkedFrames) { LoadFrameFromFile(LF.FrameIdentifier, LF.URL); return(true); } } else { AddError(LF.Exception); } } Frame F = null; if (!FramesInfo.ExcludedList.Any(t => t == FrameID)) { FrameInfo Info = FramesInfo.GetFrame(FrameID); if (Info == null || Info.ClassType == null) { AddError(new ID3Exception("Unknown Frame found and dropped according to setting", FrameID, ExceptionLevels.Warning)); return(true); } try { F = Info.Constuctor(FrameID, Flags, Length, TStream.FS); } catch { } try { if (Info.IsSingle) { if (_SingleFrames.Contains(FrameID)) { _SingleFrames.Remove(FrameID); } _SingleFrames.Add(FrameID, F); return(true); } else { foreach (FrameCollectionBase Coll in _CollectionFrames.Values) { if (Coll.CollectionType == Info.ClassType) { Coll.Remove(F.FrameID); Coll.Add(F.FrameID, F); return(true); } } } AddError(new ID3Exception("ClassType not found in Collection list", FrameID, ExceptionLevels.Error)); } catch {} } return(false); }
public unsafe bool TryGetCaptured(IDeviceContext context, IntRectangle clientRectangle, FrameType frameType, int colorDiffThreshold, int mostDetailedMip, out GpuRawFrame capturedFrame) { stopwatch.Restart(); var result = texturePool.Extract(clientRectangle.Width, clientRectangle.Height); var resultTexture = result.Item; d3dDevice.GetFrontBufferData(0, d3dSurface1); var sdxRectangle = new Rectangle(clientRectangle.X, clientRectangle.Y, clientRectangle.X + clientRectangle.Width, clientRectangle.Y + clientRectangle.Height); var lockedRectangle = d3dSurface1.LockRectangle(sdxRectangle, LockFlags.ReadOnly); var mappedSubresource = context.Map(resultTexture, 0, MapType.WriteDiscard, MapFlags.None); { int commonRowPitch = Math.Min(mappedSubresource.RowPitch, lockedRectangle.Pitch); Parallel.For(0, clientRectangle.Height, i => Memory.CopyBulk( (byte*)mappedSubresource.Data + i * mappedSubresource.RowPitch, (byte*)lockedRectangle.DataPointer + i * lockedRectangle.Pitch, commonRowPitch)); } context.Unmap(resultTexture, 0); d3dSurface1.UnlockRectangle(); var frameInfo = new FrameInfo(frameType, (float)Stopwatch.GetTimestamp() / Stopwatch.Frequency, mostDetailedMip, colorDiffThreshold, clientRectangle.Width, clientRectangle.Height, Cursor.Position.X - clientRectangle.X, Cursor.Position.Y - clientRectangle.Y); capturedFrame = new GpuRawFrame(frameInfo, result); stopwatch.Stop(); statistics.OnCapture(stopwatch.Elapsed.TotalMilliseconds); return true; }
private double ComputeCaracteristicFunction(FrameInfo frameInfo) { return frameInfo.Power*(1 - frameInfo.ZeroCrossingRate)*ScaleFactor; }