o
    }oi/                      @   s4  d dl mZmZ d dlZd dlZd dlm  mZ	 dej
dej
dededej
f
dd	Zd"dej
dee dejfddZdej
dej
dej
dej
dejdej
fddZejjjdd			
d#dej
dej
dededee deej
 dejdeeej
f fddZ	
d$dej
dededededejdej
fd d!ZdS )%    )DictOptionalNthetasphisoverheadfrontreturnc                 C   s   | j d }tj|tjd}|dtj  }d|||d k |dtj |d  kB < d|||d k|tj|d  k @ < d||tj|d  k|tj|d  k @ < d||tj|d  k|dtj |d  k @ < d|| |k< d|| tj| k< |S )az  
    Get the view direction based on given theta and phi values.

    Parameters:
    - thetas (torch.Tensor): Array of theta values with shape [B,]
    - phis (torch.Tensor): Array of phi values with shape [B,]
    - overhead (float): Threshold for determining top and bottom views.
    - front (float): Threshold for determining front, back and side views.

    Returns:
    - torch.Tensor: Array of view directions. Values can be:
        0: front
        1: side (camera left)
        2: back
        3: side (camera right)
        4: top
        5: bottom

    Notes:
    - Phi and theta values are assumed to be in radians.
    r   )dtype               )shapetorchzeroslongnppi)r   r   r   r   num_samplesres r   _/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/multimodal/data/nerf/utils.pyget_view_direction   s   
&"(,r   cudacenters	jitter_updevicec                 C   s   t | }tg d|dt| d}t tj||dd}|dur.t	|| nd}t tj||dd| }|||fS )a  
    Compute the look-at vectors for camera poses.

    Parameters:
        centers: The centers of the cameras.
        jitter_up: The noise range for the up vector of the camera.
        device: Device to allocate the output tensor.

    Returns:
        Tuple: Contains the following:
            - forward_vector: The forward vectors of the cameras, shape [B, 3].
            - up_vector: The up vectors of the cameras, shape [B, 3].
            - right_vector: The right vectors of the cameras, shape [B, 3].
    )r   r   r   r   r   dimN)
F	normalizer   FloatTensorto	unsqueezerepeatlencross
randn_like)r   r   r   forward_vector	up_vectorright_vectorup_noiser   r   r   compute_look_at_vectors@   s   
&
r.   r,   r+   r*   c                 C   sj   t jdt j|ddt| dd}t j|||gdd|ddddddf< | |dddddf< |S )	a  
    Construct the 4x4 pose matrices.

    Args:
        size (int): Number of pose matrices to construct.
        centers (torch.Tensor): The Cartesian coordinates of the camera centers.
        right_vector (torch.Tensor): The right vectors of the cameras.
        up_vector (torch.Tensor): The up vectors of the cameras.
        forward_vector (torch.Tensor): The forward vectors of the cameras.
        device (torch.device): Device to allocate tensors on.

    Returns:
        torch.Tensor: The pose matrices, shape [size, 4, 4].
    r   )r	   r   r   r   r   r   Nr   )r   eyefloat32r%   r&   r'   stack)r   r,   r+   r*   r   posesr   r   r   construct_posesX   s   &*r3   F)enabledr2   
intrinsicsheightwidthr   	error_mapc                 C   s  | j d }|\}}	}
}tjtjd|d ||dtjd|d ||ddd\}}| d|| g||| gd }| d|| g||| gd }i }|durt||| }|du rttjd|| |g|d}|||g}nt	|||||d	\}}||d
< t
|d|}t
|d|}||d< ntj|| |d||| g}t|d}||
  | | }|| |	 | }tj|||fdd}|| ddddddf dd }| ddddf d|}|d||d}|d||d}||fS )a  
    Generates rays from camera poses and intrinsics.

    Args:
        poses (torch.Tensor): Camera poses, shape [B, 4, 4] (cam2world).
        intrinsics (torch.Tensor): Intrinsic camera parameters [fx, fy, cx, cy].
        height (int): Height of the image.
        width (int): Width of the image.
        num_samples: Number of rays to sample, default is None for all rays.
        error_map: Optional tensor to use for non-uniform sampling of rays.
        device (torch.device): Device on which to generate the rays.

    Returns:
        Dict[str, torch.Tensor]: A dictionary containing the following keys:
            - 'rays_o': Origin of the rays, shape [B, N, 3]
            - 'rays_d': Directions of the rays, shape [B, N, 3]
            - 'inds': Indices of the rays, shape [B, N] (if N > 0)
            - 'inds_coarse': Coarse indices of the rays, shape [B, N] (if error_map is not None)
    r   r   r   ij)indexingg      ?N)sizer   )r8   r   r6   r7   r   sampled_indices_coarser   sampled_indicesg      r   r   .)r   r   meshgridlinspacetreshapeexpandminrandintnon_uniform_samplinggatherarange	full_liker1   	transposer%   	expand_asview)r2   r5   r6   r7   r   r8   r   
batch_sizefxfycxcyijresultsr>   r=   zsxsys
directionsrays_drays_or   r   r   get_rayst   s@   

((


 &r\   rN   c                 C   s   t j| ||dd}|d |d }}|d |d }	}
||	 t j|||d|	   j|d d}||
 t j|||d|
   j|d d}|| | }||fS )a  
    Perform non-uniform sampling based on the provided error_map.

    Parameters:
        error_map: The error map for non-uniform sampling.
        batch_size (int): Batch size of the generated samples.
        num_samples (int): Number of samples to pick.
        height (int): Height of the image.
        width (int): Width of the image.
        device: Device on which tensors are stored.

    Returns:
        A tensor containing the sampled indices.
    F)replacement   r9   r   )max)r   multinomialr$   randr   clamp)r8   rN   r   r6   r7   r   r=   inds_xinds_ysxsyr>   r   r   r   rG      s   ,,rG   )Nr   )NNr   )r   )typingr   r   numpyr   r   torch.nn.functionalnn
functionalr!   Tensorfloatr   r   r.   r3   r   ampautocastintstrr\   rG   r   r   r   r   <module>   sp   $ *
K