From 5499f35ecaf6426d5140956afecfad63a50715d6 Mon Sep 17 00:00:00 2001 From: Finn Lindig Date: Tue, 10 Jun 2025 17:44:21 +0200 Subject: [PATCH] Fix viewport bug (#7 #5) --- OpenTKAvalonia/BaseTkOpenGlControl.cs | 32 +++++++++++++++++++-------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/OpenTKAvalonia/BaseTkOpenGlControl.cs b/OpenTKAvalonia/BaseTkOpenGlControl.cs index be1782f..7b3fea2 100644 --- a/OpenTKAvalonia/BaseTkOpenGlControl.cs +++ b/OpenTKAvalonia/BaseTkOpenGlControl.cs @@ -1,4 +1,6 @@ -using Avalonia; +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Controls; using Avalonia.Input; using Avalonia.OpenGL; using Avalonia.OpenGL.Controls; @@ -24,7 +26,7 @@ public abstract class BaseTkOpenGlControl : OpenGlControlBase, ICustomHitTest /// protected virtual void OpenTkRender() { - + } /// @@ -34,7 +36,7 @@ protected virtual void OpenTkRender() /// protected virtual void OpenTkInit() { - + } /// @@ -45,16 +47,17 @@ protected virtual void OpenTkInit() /// protected virtual void OpenTkTeardown() { - + } protected sealed override void OnOpenGlRender(GlInterface gl, int fb) { //Update last key states KeyboardState.OnFrame(); - + //Set up the aspect ratio so shapes aren't stretched. - GL.Viewport(0, 0, (int) Bounds.Width, (int) Bounds.Height); + var (w, h) = GetPlatformSpecificBounds(); + GL.Viewport(0, 0, w, h); //Tell our subclass to render if (Bounds.Width != 0 && Bounds.Height != 0) @@ -66,6 +69,17 @@ protected sealed override void OnOpenGlRender(GlInterface gl, int fb) Dispatcher.UIThread.Post(RequestNextFrameRendering, DispatcherPriority.Background); } + private static readonly bool OnLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + private double? _renderScaling = null; + private double RenderScaling => (_renderScaling ??= TopLevel.GetTopLevel(this)?.RenderScaling) + ?? throw new PlatformNotSupportedException("Could not obtain TopLevel"); + private (int width, int height) GetPlatformSpecificBounds() + => OnLinux + ? ((int)Bounds.Width, (int)Bounds.Height) + : (Math.Max(1, (int)(Bounds.Width * RenderScaling)), + Math.Max(1, (int)(Bounds.Height * RenderScaling))); + protected sealed override void OnOpenGlInit(GlInterface gl) { @@ -87,15 +101,15 @@ protected override void OnKeyDown(KeyEventArgs e) { if (!IsEffectivelyVisible) return; - + KeyboardState.SetKey(e.Key, true); } - + protected override void OnKeyUp(KeyEventArgs e) { if (!IsEffectivelyVisible) return; - + KeyboardState.SetKey(e.Key, false); }