import torch
import math


def get_rotate_quad(quad, ctr_x, ctr_y, theta):
    """
    when theta > 0， quad will rotate ccw about the center point(ctr_x, ctr_y)
    :param quad: (x1, y1, ..., x4, y4) (n, 8)，Absolute coordinates
           rbbox: (ctr_x, ctr_y, w, h, theta)
    :return: boxes: (rotate_x1, rotate_y1, ..., rotate_x4, rotate_y4) (n, 8)，Absolute coordinates
    """
    device = quad.device
    boxes = torch.zeros_like(quad, dtype=torch.float, device=device)
    ctr_x = ctr_x.view(-1, 1)
    ctr_y = ctr_y.view(-1, 1)
    theta = theta * math.pi / 180
    cos = torch.cos(theta).view(-1, 1)
    sin = torch.sin(theta).view(-1, 1)
    xx = quad[:, 0::2]
    xx -= ctr_x
    yy = quad[:, 1::2]
    yy -= ctr_y
    x = yy * sin + xx * cos + ctr_x
    y = yy * cos - xx * sin + ctr_y
    boxes[:, 0::2] = x
    boxes[:, 1::2] = y
    return boxes