protected override void OnRender(UpdateEventArgs e) { if (resizeNeeded) { GL.Viewport(0, 0, width, height); using (var target = texture.Bind()) { target.Resize(width, height); } resizeNeeded = false; } using (renderTarget.Bind()) { prepareForFrame(); shapeRenderer.Render(); } postProcessor.Render(); SwapBuffers(); }
protected override void OnLoad() { texture = Texture.Empty(1, 1, PixelInternalFormat.Rgba); renderTarget = new RenderTarget(); // ReSharper disable once ConvertToUsingDeclaration using (var target = renderTarget.Bind()) { target.SetColorAttachments(texture); } shapeShaderProgram = ShaderProgram.FromShaders( ShaderFactory.Vertex.FromFile("geometry.vs"), ShaderFactory.Fragment.FromFile("geometry.fs")); meshBuilder = new IndexedTrianglesMeshBuilder <ColorVertexData>(); var shapeDrawer = new ShapeDrawer3 <ColorVertexData, Color>(meshBuilder, (xyz, color) => new ColorVertexData(xyz, color)); shapeDrawer.DrawCube(Vector3.Zero, 1f, Color.Aqua); var shapeRenderable = meshBuilder.ToRenderable(); shapeRenderer = Renderer.From(shapeRenderable, shapeShaderProgram, viewMatrix, projectionMatrix); viewMatrix.Value = Matrix4.LookAt(new Vector3(0, 1, -2), Vector3.Zero, Vector3.UnitY); postProcessShader = ShaderProgram.FromShaders( ShaderFactory.Vertex.FromFile("postprocess.vs"), ShaderFactory.Fragment.FromFile("postprocess.fs")); postProcessor = PostProcessor.From(postProcessShader, new TextureUniform("inTexture", TextureUnit.Texture0, texture), pixelSizeUniform); }
/// <summary> /// Renders the current <see cref="Duality.Resources.Scene"/>. /// </summary> /// <param name="viewportRect">The viewport area to which will be rendered.</param> public void Render(Rect viewportRect) { this.MakeAvailable(); this.UpdateDeviceConfig(); string counterName = Path.Combine("Cameras", this.gameobj.Name); Profile.BeginMeasure(counterName); Profile.TimeRender.BeginMeasure(); foreach (Pass t in this.passes) { this.RenderSinglePass(viewportRect, t); OnPassRendered(t); } OnFrameRendered(); RenderTarget.Bind(RenderTarget.None); this.drawDevice.VisibilityMask = this.visibilityMask; this.drawDevice.RenderMode = RenderMatrix.PerspectiveWorld; this.drawDevice.UpdateMatrices(); // Reset matrices for projection calculations during update Profile.TimeRender.EndMeasure(); Profile.EndMeasure(counterName); }
private Pixmap.Layer RenderToTexture(int width, int height, Action <Canvas> renderMethod) { Pixmap.Layer pixelData; using (Texture texture = new Texture(width, height, Texture.SizeMode.NonPowerOfTwo)) using (RenderTarget renderTarget = new RenderTarget(AAQuality.Off, texture)) using (DrawDevice device = new DrawDevice()) { device.Perspective = PerspectiveMode.Flat; device.VisibilityMask = VisibilityFlag.AllGroups | VisibilityFlag.ScreenOverlay; device.RenderMode = RenderMatrix.OrthoScreen; device.Target = renderTarget; device.ViewportRect = new Rect(renderTarget.Width, renderTarget.Height); device.BeginRendering(ClearFlag.All, ColorRgba.TransparentBlack, 1.0f); { Canvas canvas = new Canvas(device); renderMethod(canvas); } device.EndRendering(); RenderTarget.Bind(RenderTarget.None); pixelData = texture.RetrievePixelData(); } return(pixelData); }
public void DrawFromCamera(Camera camera, RenderTarget renderTarget) { //GlowingPass( camera ); ShadowMappingPass(camera); camera.SetCurrentView(); renderTarget.Clear(); renderTarget.Bind(); DeviceContext.OutputMerger.BlendState = mainBlend; SetViewport(camera.GetViewport()); LightManager.Instance.Update(View.Current); if (!turnOffSceneRendering) { //ProjectorManager.Instance.Bind(); scene_.Render(); //ProjectorManager.Instance.UnBind(); } //renderTarget.DepthStencil.SetDepthComparison( Comparison.Greater ); // On vérifie si la camera possède une skybox if (camera.Skybox != null) { // Dans ce cas, on affiche la skybox // On l'affiche en dernier pour éviter d'effectuer les test du Stencil buffer inutilement camera.Skybox.Render(); } // if (Isglowing){ // GlowingManager.Instance.DrawQuadOnTop(); // } }
public void BeginRendering(ClearFlag clearFlags, ColorRgba clearColor, float clearDepth) { RenderTarget.Bind(this.renderTarget); // Setup viewport Vector2 refSize = this.TargetSize; Rect viewportAbs = new Rect(refSize); GL.Viewport((int)viewportAbs.X, (int)refSize.Y - (int)viewportAbs.H - (int)viewportAbs.Y, (int)viewportAbs.W, (int)viewportAbs.H); GL.Scissor((int)viewportAbs.X, (int)refSize.Y - (int)viewportAbs.H - (int)viewportAbs.Y, (int)viewportAbs.W, (int)viewportAbs.H); // Clear buffers ClearBufferMask glClearMask = 0; if ((clearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((clearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor((OpenTK.Graphics.Color4)clearColor); GL.ClearDepth((double)clearDepth); // The "float version" is from OpenGL 4.1.. GL.Clear(glClearMask); // Configure Rendering params if (this.renderMode == RenderMatrix.OrthoScreen) { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Always); } else { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); } // Upload and adjust matrices this.UpdateMatrices(); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref this.matModelView); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref this.matProjection); if (this.renderTarget.IsAvailable) { if (this.renderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, RenderTarget.BoundRT.Res.Height * 0.5f, 0.0f); } GL.Scale(1.0f, -1.0f, 1.0f); if (this.renderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, -RenderTarget.BoundRT.Res.Height * 0.5f, 0.0f); } } }
public static void RenderVoid(Rect viewportRect) { RenderTarget.Bind(ContentRef <RenderTarget> .Null); GL.Viewport((int)viewportRect.X, (int)viewportRect.Y, (int)viewportRect.W, (int)viewportRect.H); GL.Scissor((int)viewportRect.X, (int)viewportRect.Y, (int)viewportRect.W, (int)viewportRect.H); GL.ClearDepth(1.0d); GL.ClearColor((OpenTK.Graphics.Color4)ColorRgba.TransparentBlack); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); }
/// <summary> /// Renders a picking map of the current <see cref="Duality.Resources.Scene"/>. /// If picking is required, this will be (automatically) done each frame a picking operation needs to /// be performed. /// </summary> /// <param name="viewportSize">Sife of the viewport area to which will be rendered.</param> /// <returns>True, if the picking map has been rendered. False, if this frames cached version is used.</returns> public bool RenderPickingMap(Vector2 viewportSize) { if (this.pickingLast == Time.FrameCount) { return(false); } this.pickingLast = Time.FrameCount; Profile.TimeVisualPicking.BeginMeasure(); // Render picking map { this.MakeAvailable(); this.UpdateDeviceConfig(); this.SetupPickingRT(viewportSize); // Setup DrawDevice this.drawDevice.PickingIndex = 1; this.drawDevice.Target = this.pickingRT; this.drawDevice.VisibilityMask = this.visibilityMask & VisibilityFlag.AllGroups; this.drawDevice.RenderMode = RenderMatrix.PerspectiveWorld; this.drawDevice.ViewportRect = new Rect(this.pickingTex.PixelWidth, this.pickingTex.PixelHeight); // Render Scene this.drawDevice.BeginRendering(ClearFlag.All, ColorRgba.Black, 1.0f); this.CollectDrawcalls(); this.drawDevice.EndRendering(); this.drawDevice.PickingIndex = 0; GL.Finish(); RenderTarget.Bind(RenderTarget.None); } // Move data to local buffer int pxNum = this.pickingTex.PixelWidth * this.pickingTex.PixelHeight; int pxByteNum = pxNum * 4; if (pxByteNum > this.pickingBuffer.Length) { Array.Resize(ref this.pickingBuffer, Math.Max(this.pickingBuffer.Length * 2, pxByteNum)); } ContentRef <RenderTarget> lastTex = RenderTarget.BoundRT; RenderTarget.Bind(this.pickingRT); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.ReadPixels(0, 0, this.pickingTex.PixelWidth, this.pickingTex.PixelHeight, PixelFormat.Rgba, PixelType.UnsignedByte, this.pickingBuffer); RenderTarget.Bind(lastTex); GL.ReadBuffer(ReadBufferMode.Back); Profile.TimeVisualPicking.EndMeasure(); return(true); }
public void Draw() { if (!IsEnabled) { return; } shadowMapTarget.Bind(1); Draw(modelRenderer); Draw(spriteBatch3D); Draw(skeletonRenderer); }
public void Draw() { if (!IsDrawEnabled) { return; } shadowMapTarget.Bind(Constants.TextureLimit); Draw(modelRenderer); Draw(spriteBatch3D); Draw(skeletonRenderer); }
public static void RenderVoid() { RenderTarget.Bind(ContentRef <RenderTarget> .Null); Vector2 refSize = DualityApp.TargetResolution; Rect viewportAbs = new Rect(refSize); GL.Viewport((int)viewportAbs.X, (int)refSize.Y - (int)viewportAbs.H - (int)viewportAbs.Y, (int)viewportAbs.W, (int)viewportAbs.H); GL.Scissor((int)viewportAbs.X, (int)refSize.Y - (int)viewportAbs.H - (int)viewportAbs.Y, (int)viewportAbs.W, (int)viewportAbs.H); GL.ClearDepth(1.0d); GL.ClearColor((OpenTK.Graphics.Color4)ColorRgba.TransparentBlack); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); }
public void DrawTargets() { modelTarget.Apply(); // Note that by this point, the scene's shadow map should have already been computed. var renderer = Scene.Renderer; renderer.VpMatrix = viewOrientation; renderer.Draw(); shader.Apply(); Sky.Target.Bind(0); modelTarget.Bind(1); }
public override void Draw() { RenderTarget originalRenderTarget = RenderTarget.Current; RenderTarget.Bind(Surface); Graphics.Clear(Colour.Black); // Shadow Casters Vector2 caster = occlusion.player.Position; //Vector2 caster = Input.Mouse.Position.World.round(); //Vector2 caster = Vector2.Zero; // Falloff Shadow BlendState originalBlendState = Graphics.State.BlendState; Graphics.State.SetBlendState(BlendState.Subtractive); Renderer.Draw.Circle(caster, Resolution.Height * 2f, Colour.White, Colour.White.Alpha(0), 32); Graphics.State.SetBlendState(originalBlendState); //Renderer.SetBlendState(nsBlendState.Subtractive); foreach (Box box in Scene.Entities.FindAll <Box>()) { var block_l = box.X - box.Origin.X; var block_r = box.X - box.Origin.X + box.Size.X; var block_t = box.Y - box.Origin.Y; var block_b = box.Y - box.Origin.Y + box.Size.Y; if (caster.Y > block_t) { DrawShadow(new Vector2(block_l, block_t), new Vector2(block_r, block_t), caster, 700); } if (caster.Y < block_b) { DrawShadow(new Vector2(block_l, block_b), new Vector2(block_r, block_b), caster, 700); } if (caster.X > block_l) { DrawShadow(new Vector2(block_l, block_t), new Vector2(block_l, block_b), caster, 700); } if (caster.X < block_r) { DrawShadow(new Vector2(block_r, block_t), new Vector2(block_r, block_b), caster, 700); } } RenderTarget.Bind(originalRenderTarget); //Graphics.State.SetBlendState(BlendState.Additive); Renderer.Draw.RenderTarget(Surface, Camera.Position.X - Resolution.Half.Width / Camera.Zoom, Camera.Position.Y - Resolution.Half.Height / Camera.Zoom, 1f / Camera.Zoom, Camera.Rotation, Camera.Position, Colour.White); //Renderer.ResetBlendState(); }
private static PipelineRenderTarget renderTarget( Action <RenderTarget.Target>?additionalSetup, params PipelineTexture[] textures) { var renderTarget = new RenderTarget(); using (var target = renderTarget.Bind()) { target.SetColorAttachments(textures.Select(t => t.Texture).ToArray()); additionalSetup?.Invoke(target); var status = target.CheckStatus(); if (status != FramebufferErrorCode.FramebufferComplete) { throw new InvalidOperationException($"Framebuffer incomplete: {status}"); } } return(new PipelineRenderTarget(renderTarget)); }
// tick for OpenGL rendering code public void RenderGL() { HandleInput(); // measure frame duration float frameDuration = timer.ElapsedMilliseconds; timer.Reset(); timer.Start(); UpdateScene(); //update transformations of all objects that are not static // update rotation a += 0.001f * frameDuration; if (a > 1000 * PI) { a -= 1000 * PI; //reset a to prevent stack overflows } if (useRenderTarget) { // enable render target target.Bind(); // render scene to render target sceneGraph.RenderHierarchy(camera); // render quad target.Unbind(); quad.Render(postproc, target.GetTextureID()); } else { // render scene directly to the screen sceneGraph.RenderHierarchy(camera); } }
void UpdateSourceDrawingWork(JobInfo job) { bool vsync = false; bool alternateVsync = false; //only used by alternate vsync IGL_SlimDX9 dx9 = null; if (!job.offscreen) { //apply the vsync setting (should probably try to avoid repeating this) vsync = Global.Config.VSyncThrottle || Global.Config.VSync; //ok, now this is a bit undesireable. //maybe the user wants vsync, but not vsync throttle. //this makes sense... but we dont have the infrastructure to support it now (we'd have to enable triple buffering or something like that) //so what we're gonna do is disable vsync no matter what if throttling is off, and maybe nobody will notice. //update 26-mar-2016: this upsets me. When fastforwarding and skipping frames, vsync should still work. But I'm not changing it yet if (Global.DisableSecondaryThrottling) { vsync = false; } //for now, it's assumed that the presentation panel is the main window, but that may not always be true if (vsync && Global.Config.DispAlternateVsync && Global.Config.VSyncThrottle) { dx9 = GL as IGL_SlimDX9; if (dx9 != null) { alternateVsync = true; //unset normal vsync if we've chosen the alternate vsync vsync = false; } } //TODO - whats so hard about triple buffering anyway? just enable it always, and change api to SetVsync(enable,throttle) //maybe even SetVsync(enable,throttlemethod) or just SetVsync(enable,throttle,advanced) if (LastVsyncSetting != vsync || LastVsyncSettingGraphicsControl != presentationPanel.GraphicsControl) { if (LastVsyncSetting == null && vsync) { // Workaround for vsync not taking effect at startup (Intel graphics related?) presentationPanel.GraphicsControl.SetVsync(false); } presentationPanel.GraphicsControl.SetVsync(vsync); LastVsyncSettingGraphicsControl = presentationPanel.GraphicsControl; LastVsyncSetting = vsync; } } //begin rendering on this context //should this have been done earlier? //do i need to check this on an intel video card to see if running excessively is a problem? (it used to be in the FinalTarget command below, shouldnt be a problem) //GraphicsControl.Begin(); //CRITICAL POINT for yabause+GL //TODO - auto-create and age these (and dispose when old) int rtCounter = 0; CurrentFilterProgram.RenderTargetProvider = new DisplayManagerRenderTargetProvider((size) => ShaderChainFrugalizers[rtCounter++].Get(size)); GL.BeginScene(); //run filter chain Texture2d texCurr = null; RenderTarget rtCurr = null; bool inFinalTarget = false; foreach (var step in CurrentFilterProgram.Program) { switch (step.Type) { case FilterProgram.ProgramStepType.Run: { int fi = (int)step.Args; var f = CurrentFilterProgram.Filters[fi]; f.SetInput(texCurr); f.Run(); var orec = f.FindOutput(); if (orec != null) { if (orec.SurfaceDisposition == SurfaceDisposition.Texture) { texCurr = f.GetOutput(); rtCurr = null; } } break; } case FilterProgram.ProgramStepType.NewTarget: { var size = (Size)step.Args; rtCurr = ShaderChainFrugalizers[rtCounter++].Get(size); rtCurr.Bind(); CurrentFilterProgram.CurrRenderTarget = rtCurr; break; } case FilterProgram.ProgramStepType.FinalTarget: { var size = (Size)step.Args; inFinalTarget = true; rtCurr = null; CurrentFilterProgram.CurrRenderTarget = null; GL.BindRenderTarget(null); break; } } } GL.EndScene(); if (job.offscreen) { job.offscreenBB = rtCurr.Texture2d.Resolve(); job.offscreenBB.DiscardAlpha(); } else { Debug.Assert(inFinalTarget); //wait for vsync to begin if (alternateVsync) { dx9.AlternateVsyncPass(0); } //present and conclude drawing presentationPanel.GraphicsControl.SwapBuffers(); //wait for vsync to end if (alternateVsync) { dx9.AlternateVsyncPass(1); } //nope. dont do this. workaround for slow context switching on intel GPUs. just switch to another context when necessary before doing anything //presentationPanel.GraphicsControl.End(); } }
public void Render() { // measure frame duration float frameDuration = (float)timer.Elapsed.TotalSeconds; //timer.ElapsedMilliseconds; timer.Reset(); timer.Start(); CameraControls(frameDuration); //prepare matrices for vertex shader Vector3 campos3 = -cameraM.Row3.Xyz; camID = GL.GetUniformLocation(shader.programID, "campos"); GL.UseProgram(shader.programID); GL.Uniform3(camID, campos3); Vector3 newlightpos3 = lightpos3; lightID = GL.GetUniformLocation(shader.programID, "lightPos"); GL.UseProgram(shader.programID); GL.Uniform3(lightID, newlightpos3); Matrix4 teapotT = Matrix4.CreateFromAxisAngle(new Vector3(0, 1, 0), -a); teapotN.localM = teapotT; Matrix4 smallteapotT = Matrix4.CreateFromAxisAngle(new Vector3(0, 1, 0), -b); smallteapotT *= Matrix4.CreateScale(0.6f); smallteapotT *= Matrix4.CreateTranslation(8f, 7f, 0); smallteapot.localM = smallteapotT; Matrix4 carT = Matrix4.CreateScale(0.8f); carT *= Matrix4.CreateFromAxisAngle(new Vector3(0, 1, 0), 0.8f * (float)Math.PI);; carT *= Matrix4.CreateTranslation(4f, -2.2f, 0); carT *= Matrix4.CreateFromAxisAngle(new Vector3(0, 1, 0), b); carN.localM = carT; Matrix4 carT2 = Matrix4.CreateScale(0.8f); carT2 *= Matrix4.CreateFromAxisAngle(new Vector3(0, -1, 0), 0.2f * (float)Math.PI);; carT2 *= Matrix4.CreateTranslation(-3.5f, -2.25f, 0); carT2 *= Matrix4.CreateFromAxisAngle(new Vector3(0, 1, 0), b); carN2.localM = carT2; // update rotation a += 1f * frameDuration; b += 1.5f * frameDuration; if (a > 2 * PI) { a -= 2 * PI; } if (b > 2 * PI) { b -= 2 * PI; } if (useRenderTarget) { // enable render target target.Bind(); // render scene to render target root.Render(ToWorld, cameraM); // render quad target.Unbind(); quad.Render(postproc, target.GetTextureID()); } else { // render scene directly to the screen root.Render(ToWorld, cameraM); } }
void UpdateSourceDrawingWork(JobInfo job) { //begin rendering on this context //should this have been done earlier? //do i need to check this on an intel video card to see if running excessively is a problem? (it used to be in the FinalTarget command below, shouldnt be a problem) //GraphicsControl.Begin(); //run filter chain Texture2d texCurr = null; RenderTarget rtCurr = null; int rtCounter = 0; bool inFinalTarget = false; foreach (var step in CurrentFilterProgram.Program) { switch (step.Type) { case FilterProgram.ProgramStepType.Run: { int fi = (int)step.Args; var f = CurrentFilterProgram.Filters[fi]; f.SetInput(texCurr); f.Run(); var orec = f.FindOutput(); if (orec != null) { if (orec.SurfaceDisposition == SurfaceDisposition.Texture) { texCurr = f.GetOutput(); rtCurr = null; } } break; } case FilterProgram.ProgramStepType.NewTarget: { var size = (Size)step.Args; rtCurr = ShaderChainFrugalizers[rtCounter++].Get(size); rtCurr.Bind(); CurrentFilterProgram.CurrRenderTarget = rtCurr; break; } case FilterProgram.ProgramStepType.FinalTarget: { var size = (Size)step.Args; inFinalTarget = true; rtCurr = null; CurrentFilterProgram.CurrRenderTarget = null; GL.BindRenderTarget(null); break; } } } if (job.offscreen) { job.offscreenBB = rtCurr.Texture2d.Resolve(); } else { Debug.Assert(inFinalTarget); //apply the vsync setting (should probably try to avoid repeating this) bool vsync = Global.Config.VSyncThrottle || Global.Config.VSync; //ok, now this is a bit undesireable. //maybe the user wants vsync, but not vsync throttle. //this makes sense... but we dont have the infrastructure to support it now (we'd have to enable triple buffering or something like that) //so what we're gonna do is disable vsync no matter what if throttling is off, and maybe nobody will notice. if (Global.DisableSecondaryThrottling) { vsync = false; } if (LastVsyncSetting != vsync || LastVsyncSettingGraphicsControl != presentationPanel.GraphicsControl) { if (LastVsyncSetting == null && vsync) { // Workaround for vsync not taking effect at startup (Intel graphics related?) presentationPanel.GraphicsControl.SetVsync(false); } presentationPanel.GraphicsControl.SetVsync(vsync); LastVsyncSettingGraphicsControl = presentationPanel.GraphicsControl; LastVsyncSetting = vsync; } //present and conclude drawing presentationPanel.GraphicsControl.SwapBuffers(); //nope. dont do this. workaround for slow context switching on intel GPUs. just switch to another context when necessary before doing anything //presentationPanel.GraphicsControl.End(); } }
void UpdateSourceDrawingWork(JobInfo job) { //begin rendering on this context //should this have been done earlier? //do i need to check this on an intel video card to see if running excessively is a problem? (it used to be in the FinalTarget command below, shouldnt be a problem) //GraphicsControl.Begin(); //run filter chain Texture2d texCurr = null; RenderTarget rtCurr = null; int rtCounter = 0; bool inFinalTarget = false; foreach (var step in CurrentFilterProgram.Program) { switch (step.Type) { case FilterProgram.ProgramStepType.Run: { int fi = (int)step.Args; var f = CurrentFilterProgram.Filters[fi]; f.SetInput(texCurr); f.Run(); var orec = f.FindOutput(); if (orec != null) { if (orec.SurfaceDisposition == SurfaceDisposition.Texture) { texCurr = f.GetOutput(); rtCurr = null; } } break; } case FilterProgram.ProgramStepType.NewTarget: { var size = (Size)step.Args; rtCurr = ShaderChainFrugalizers[rtCounter++].Get(size); rtCurr.Bind(); CurrentFilterProgram.CurrRenderTarget = rtCurr; break; } case FilterProgram.ProgramStepType.FinalTarget: { var size = (Size)step.Args; inFinalTarget = true; rtCurr = null; CurrentFilterProgram.CurrRenderTarget = null; GL.BindRenderTarget(null); break; } } } if (job.offscreen) { job.offscreenBB = rtCurr.Texture2d.Resolve(); } else { Debug.Assert(inFinalTarget); //apply the vsync setting (should probably try to avoid repeating this) bool vsync = Global.Config.VSyncThrottle || Global.Config.VSync; if (LastVsyncSetting != vsync || LastVsyncSettingGraphicsControl != presentationPanel.GraphicsControl) { presentationPanel.GraphicsControl.SetVsync(vsync); LastVsyncSettingGraphicsControl = presentationPanel.GraphicsControl; LastVsyncSetting = vsync; } //present and conclude drawing presentationPanel.GraphicsControl.SwapBuffers(); //nope. dont do this. workaround for slow context switching on intel GPUs. just switch to another context when necessary before doing anything //presentationPanel.GraphicsControl.End(); NeedsToPaint = false; //?? } }
public void BeginRendering(ClearFlag clearFlags, ColorRgba clearColor, float clearDepth, bool scaleViewport = true) { RenderTarget.Bind(this.renderTarget); // Setup viewport Rect viewport = this.ViewportRect; if (scaleViewport) { float width = this.viewportRect.W; var targetAspectRatio = nominalViewportSize.X / nominalViewportSize.Y; float height = (width / targetAspectRatio + 0.5f); if (height > viewportRect.H) { height = viewportRect.H; width = height * targetAspectRatio + 0.5f; } viewport = new Rect( (viewportRect.W / 2) - (width / 2), (viewportRect.H / 2) - (height / 2), width, height); } GL.Viewport((int)viewport.X, (int)viewport.Y, (int)viewport.W, (int)viewport.H); GL.Scissor((int)this.viewportRect.X, (int)this.viewportRect.Y, (int)this.viewportRect.W, (int)this.viewportRect.H); // Clear buffers ClearBufferMask glClearMask = 0; if ((clearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((clearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor((OpenTK.Graphics.Color4)clearColor); GL.ClearDepth((double)clearDepth); // The "float version" is from OpenGL 4.1.. GL.Clear(glClearMask); // Configure Rendering params if (this.renderMode == RenderMatrix.OrthoScreen) { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Always); } else { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); } // Upload and adjust matrices this.UpdateMatrices(); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref this.matModelView); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref this.matProjection); if (this.renderTarget.IsAvailable) { if (this.renderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, RenderTarget.BoundRT.Res.Height * 0.5f, 0.0f); } GL.Scale(1.0f, -1.0f, 1.0f); if (this.renderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, -RenderTarget.BoundRT.Res.Height * 0.5f, 0.0f); } } }
static unsafe void Main(string[] args) { BizHawk.Bizware.BizwareGL.IGL igl = new BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK(); List <Art> testArts = new List <Art>(); ArtManager am = new ArtManager(igl); foreach (var name in typeof(Program).Assembly.GetManifestResourceNames()) { if (name.Contains("flame")) { testArts.Add(am.LoadArt(typeof(Program).Assembly.GetManifestResourceStream(name))); } } var smile = am.LoadArt(typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.smile.png")); am.Close(true); StringRenderer sr; using (var xml = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.courier16px.fnt")) using (var tex = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.courier16px_0.png")) sr = new StringRenderer(igl, xml, tex); GuiRenderer gr = new GuiRenderer(igl); TestForm tf = new TestForm(); RetainedGraphicsControl c = new RetainedGraphicsControl(igl); tf.Controls.Add(c); c.Dock = System.Windows.Forms.DockStyle.Fill; tf.FormClosing += (object sender, System.Windows.Forms.FormClosingEventArgs e) => { tf.Controls.Remove(c); c.Dispose(); c = null; }; tf.Show(); //tf.Paint += (object sender, PaintEventArgs e) => c.Refresh(); c.SetVsync(false); //create a render target RenderTarget rt = igl.CreateRenderTarget(60, 60); rt.Bind(); igl.SetClearColor(Color.Blue); igl.Clear(ClearBufferMask.ColorBufferBit); gr.Begin(60, 60, true); gr.Draw(smile); gr.End(); rt.Unbind(); Texture2d rttex2d = igl.LoadTexture(rt.Texture2d.Resolve()); //test retroarch shader RenderTarget rt2 = igl.CreateRenderTarget(240, 240); rt2.Bind(); igl.SetClearColor(Color.CornflowerBlue); igl.Clear(ClearBufferMask.ColorBufferBit); RetroShader shader; using (var stream = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.4xSoft.glsl")) shader = new RetroShader(igl, new System.IO.StreamReader(stream).ReadToEnd()); igl.SetBlendState(igl.BlendNone); shader.Run(rttex2d, new Size(60, 60), new Size(240, 240), true); bool running = true; c.MouseClick += (object sender, MouseEventArgs e) => { if (e.Button == MouseButtons.Left) { running ^= true; } if (e.Button == MouseButtons.Right) { c.Retain ^= true; } }; DateTime start = DateTime.Now; int wobble = 0; for (; ;) { if (c == null) { break; } if (running) { c.Begin(); igl.SetClearColor(Color.Red); igl.Clear(ClearBufferMask.ColorBufferBit); int frame = (int)((DateTime.Now - start).TotalSeconds) % testArts.Count; gr.Begin(c.ClientSize.Width, c.ClientSize.Height); gr.SetModulateColor(Color.Green); gr.RectFill(250, 0, 16, 16); gr.SetBlendState(igl.BlendNone); gr.Draw(rttex2d, 0, 20); gr.SetBlendState(igl.BlendNormal); sr.RenderString(gr, 0, 0, "?? fps"); gr.SetModulateColor(Color.FromArgb(255, 255, 255, 255)); gr.SetCornerColor(0, OpenTK.Graphics.Color4.Red); gr.Draw(rt2.Texture2d, 0, 0); gr.SetCornerColor(0, OpenTK.Graphics.Color4.White); gr.SetModulateColorWhite(); gr.Modelview.Translate((float)Math.Sin(wobble / 360.0f) * 50, 0); gr.Modelview.Translate(100, 100); gr.Modelview.Push(); gr.Modelview.Translate(testArts[frame].Width, 0); gr.Modelview.Scale(-1, 1); wobble++; gr.SetModulateColor(Color.Yellow); gr.DrawFlipped(testArts[frame], true, false); gr.SetModulateColorWhite(); gr.Modelview.Pop(); gr.SetBlendState(igl.BlendNormal); gr.Draw(smile); gr.End(); c.SwapBuffers(); c.End(); } System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(0); } }