ByChance.Levels2D.Chunk2D.Rotate C# (CSharp) Method

Rotate() private method

Rotates this chunk clock-wise by 90°, changing the positions of all contexts and switching width and height.
private Rotate ( ) : bool
return bool
        internal override bool Rotate()
        {
            var center = this.Extents / 2;

            foreach (Context2D context in this.ChunkContexts)
            {
                // Translate context position to chunk origin.
                var origin = context.RelativePosition - center;

                /*
                 * Each point (x, y) in a cartesian coordinate system can be written as
                 *
                 * x = r * cos q
                 * y = r * sin q
                 *
                 * with an initial angle q.
                 *
                 * Rotating that point around the origin by the angle f results in
                 *
                 * x' = r * cos (q + f) = r * cos q * cos f - r * sin q * sin f
                 * y' = r * sin (q + w) = r * sin q * cos f + r * cos q * sin f
                 *
                 * Applying the original definition of x and y leads to
                 *
                 * x' = x * cos f - y * sin f
                 * y' = y * cos f + x * sin f
                 *
                 * Rotating by 90° gives us
                 *
                 * x' = x * 0 - y * 1 = -y
                 * y' = y * 0 + x * 1 = x
                 *
                 * After that, we have to translate the context position back in the rotated chunk's coordinate system.
                 */
                var contextRelativePosX = -origin.Y + center.Y;
                var contextRelativePosY = origin.X + center.X;

                context.RelativePosition = new Vector2F(contextRelativePosX, contextRelativePosY);
            }

            // Switch width and height.
            this.Extents = new Vector2F(this.Extents.Y, this.Extents.X);

            // Update rotation.
            this.Rotation += 90;
            return this.Rotation < 360;
        }