using System; using Azimuth; using Blacklight.Core; using Blacklight.Core.Cameras; using Blacklight.Core.Drawables; namespace Konis.Testbed { /// /// Fills the part of the world the camera sees with a backdrop's cells. /// public class BackdropPainter { /// /// The side of a cell in world units, which are pixels at the camera's starting zoom. /// public const double CellSide = 32; /// /// The most cells painted in a frame. Zoomed far out the cells double in size until they fit. /// public const int MaxCells = 4000; private Backdrop paintedBackdrop; private Rectangle[] swatches = Array.Empty(); private void UseSwatchesOf(Backdrop backdrop) { if (backdrop == paintedBackdrop) { return; } swatches = new Rectangle[backdrop.Swatches.Length]; for (int i = 0; i < swatches.Length; i++) { swatches[i] = new Rectangle { InsideColor = backdrop.Swatches[i] }; } paintedBackdrop = backdrop; } /// /// Adds the backdrop's cells for the part of the world the camera shows in a window of by . /// public void Paint(Cel cel, Backdrop backdrop, Camera camera, double pixelWidth, double pixelHeight) { if (backdrop.Swatches.Length == 0) { return; } UseSwatchesOf(backdrop); // The corners bound the view even if the camera is turned. double halfWidth = pixelWidth / 2; double halfHeight = pixelHeight / 2; Vector first = camera.ProjectionToWorld.TransformPoint(new Vector(-halfWidth, -halfHeight)); double left = first.X; double right = first.X; double top = first.Y; double bottom = first.Y; for (int i = 1; i < 4; i++) { Vector corner = camera.ProjectionToWorld.TransformPoint( new Vector((i & 1) == 0 ? -halfWidth : halfWidth, (i & 2) == 0 ? -halfHeight : halfHeight)); left = Math.Min(left, corner.X); right = Math.Max(right, corner.X); top = Math.Min(top, corner.Y); bottom = Math.Max(bottom, corner.Y); } double side = CellSide; while (((right - left) / side + 2) * ((bottom - top) / side + 2) > MaxCells) { side *= 2; } int firstColumn = (int)Math.Floor(left / side); int lastColumn = (int)Math.Floor(right / side); int firstRow = (int)Math.Floor(top / side); int lastRow = (int)Math.Floor(bottom / side); var size = new Vector(side, side); for (int row = firstRow; row <= lastRow; row++) { for (int column = firstColumn; column <= lastColumn; column++) { int swatch = backdrop.SwatchAt(column, row); if (swatch < 0) { continue; } cel.AddEntity(swatches[swatch], Rectangle.ModelToWorld( size, position: new Vector(column * side, row * side), anchor: Rectangle.TopLeft)); } } } } }