Compare commits

...
1 Commits
Author SHA1 Message Date
Leonid Pershin 08381703f7 Add WorldCenter property to CameraState for effective camera positioning
CI / build-test (push) Successful in 1m19s
Enhanced the CameraState struct with a new WorldCenter property that calculates the effective position of the camera after bounds-clamping. This property is intended to be used for zoom-to-cursor functionality, ensuring that the repositioning aligns with what is rendered.

Added unit tests to verify that WorldCenter reflects the unclamped camera position and correctly accounts for bounds clamping, distinguishing it from the raw camera position.

Tests: WorldCenter_EqualsUnclampedCameraPosition, WorldCenter_ReflectsBoundsClamp_UnlikeRawPosition.
2026-06-13 05:21:24 +03:00
2 changed files with 32 additions and 0 deletions
+9
View File
@@ -33,6 +33,15 @@ public readonly struct CameraState
/// <summary>Physical-screen to virtual-pixel mapping.</summary>
public required ViewportMapping Mapping { get; init; }
/// <summary>
/// World point at the centre of the virtual screen — the camera's <em>effective</em> position
/// after bounds-clamping, i.e. what the view is actually built around. Prefer this over the raw
/// <see cref="Camera.Position"/> when anchoring zoom-to-cursor, so the reposition matches what is
/// rendered even while the camera is clamped against <see cref="Camera.Bounds"/>.
/// </summary>
public Vector2 WorldCenter =>
Vector2.Transform(new Vector2(VirtualWidth / 2f, VirtualHeight / 2f), InverseView);
/// <summary>Converts a physical screen point to world coordinates.</summary>
public Vector2 ScreenToWorld(Vector2 screen)
{
@@ -83,6 +83,29 @@ public class CameraMathTests
AssertVector(new Vector2(0f, 200f), state.ScreenToWorld(Vector2.Zero));
}
[Fact]
public void WorldCenter_EqualsUnclampedCameraPosition()
{
var camera = new Camera(new Vector2(640f, 360f), zoom: 2f);
var state = CameraMath.Compute(camera, 1280, 720, ViewportMapping.Identity);
AssertVector(camera.Position, state.WorldCenter);
}
[Fact]
public void WorldCenter_ReflectsBoundsClamp_UnlikeRawPosition()
{
var bounds = new RectF(0f, 0f, 2000f, 1000f);
var camera = new Camera(new Vector2(-500f, 500f), bounds: bounds);
var state = CameraMath.Compute(camera, 800, 600, ViewportMapping.Identity);
// Raw position is (-500, 500); only X clamps (to half-width 400 from the left world edge),
// Y (500) is already inside [300, 700]. The effective centre the view is built around is (400, 500).
AssertVector(new Vector2(400f, 500f), state.WorldCenter);
}
[Fact]
public void Mapping_CentersVirtualResolutionInWiderWindow()
{