o
    *ju1                     @   s4  d dl Z d dlZd dlZd dlmZ d dlZd dlm  m	Z
 d1ddZdd Zd2d
dZdd Zdd Zdd ZdejdejdejfddZdejdejdejfddZd3dejdedejfddZd3dejdedejfddZd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.ejdejfd/d0ZdS )4    NFc                 C   sF  t | d}| }W d    n1 sw   Y  g }g }g }g }g }g }	d}
|D ]}|d d dkrHdd | ddd  D }|| |d d d	kr| ddd  }d
d |D }t|
t|}
|| d|d v rt|d dd dkrdd |D }|| d|d v rt|d ddkrt|d dd dkrdd |D }|	| |d d dkr| ddd  }dd |D }|| |d d dkr| ddd  }dd |D }|| q)t|	tj
}|
dkrt|	tj}ntd |jd dkr ||d}n|d d d df |d d dd f |d}t|dkrJt|	tj
}||d< t|dkr^t|	tj
}||d< t|dkrw|
dkrst|	tj}||d< t|	dkr|
dkrt|		tj}	|	|d< |rtdt| tdt| |S )Nrr      zv c                 S       g | ]}t |d krt|qS r   lenfloat.0a r   m/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/models/cv/human3d_animation/utils.py
<listcomp>   s    zread_obj.<locals>.<listcomp>    f c                 S   s*   g | ]}t |d krt|dd  qS )r   /r   intsplitr	   r   r   r   r          * r   c                 S   *   g | ]}t |d krt|dd qS )r   r   r   r   r	   r   r   r   r   %   r      c                 S   r   )r   r   r   r   r	   r   r   r   r   *   s    $zvt c                 S   r   r   r   r	   r   r   r   r   1        zvn c                 S   r   r   r   r	   r   r   r   r   6   r   znot a triangle face mesh!)verticesfaces)r   colorsr   uvsnormalsfaces_uvfaces_normalznum of verticesznum of faces)open	readlinesstripr   appendmaxr   nparrayastypefloat32Zint32printshape)Zobj_pathZprint_shapefZ	bfm_linesr   r   r   Zvnsr   r    Zmax_face_lengthlineZvertexitemsfaceface_uvface_normaluvvnmeshr   r   r   read_obj   s   


&
$





r5   c                    s  t j| }t jt j| d }d|v rntt j||d |d  tt j||d d5}|	d |	d |	d |	d	 |	d
 |	d |	d |	d
|d  W d    n1 siw   Y  t| d	}d|v r|	d |	d
| d|v rt|d D ])\}}|	d
|d |d |d |d | d |d | d |d | d  qn|d D ]}|	d
|d |d |d  qd|v r|d D ]}|	d
|d |d  qd|v r|d D ]}|	d
|d |d |d  qd|v rmt|d D ]c\}	 d|v sd|v rRd|v r+|d |	 n d|v r9|d |	 n dd fdd tt D  d! }
ndd fd"d tt D  d! }
|	|
 qW d    d S W d    d S 1 sw   Y  d S )#Nr   Ztexture_mapz.pngz.mtlwznewmtl material_0
zKa 1.000000 0.000000 0.000000
zKd 1.000000 1.000000 1.000000
zKs 0.000000 0.000000 0.000000
zTr 0.000000
zillum 0
zNs 0.000000
z
map_Kd {}
z# Create by ModelScope
zmtllib ./{}.mtl
r   r   zv {} {} {} {} {} {}
r   r   zv {} {} {}
r   z	vt {} {}
r   zvn {} {} {}
r   r   r    r   r   c                    s&   g | ]}d   | | | qS )z{}/{}/{}formatr
   ir/   r1   r0   r   r   r      s    zwrite_obj.<locals>.<listcomp>
c                    s   g | ]	}d   | qS )z{}r7   r9   )r/   r   r   r      s    )ospathdirnamesplitextbasenamecv2Zimwritejoinr!   writer8   	enumerateranger   )Z	save_pathr4   save_dirZ	save_nameZwfr:   vr2   r3   indrowr   r;   r   	write_objc   sz   








 "
"





$rK   皙?      ?      I@c              
   C   s^   t ||  dddgd||  ddgdd||  ||  d| |  ||  gg dgt jS )Nr   r   )r   r   r   r&   r'   r(   r)   )xnr,   r   r   r   
projection   s    *rS   c                 C   s6   t ddd| gddd|gddd|gg dgt jS )Nr   r   r   r   r   r   rP   )rQ   yzr   r   r   	translate   s
   "rW   c                 C   sJ   t | t | }}t g dd||dgd| |dgg dgt jS )N)r   r   r   r   r   rT   r&   sincosr'   r(   r)   r   scr   r   r   rotate_x       r^   c                 C   sJ   t | t | }}t |d|dgg d| d|dgg dgt jS )Nr   )r   r   r   r   rT   rX   r[   r   r   r   rotate_y   r_   r`   rQ   rU   returnc                 C   s   t j| | dddS )NrO   Tkeepdim)torchsum)rQ   rU   r   r   r   dot   s   rf   rR   c                 C   s   dt | | | |  S )Nr   )rf   )rQ   rR   r   r   r   reflect   s   rg   #B;epsc                 C   s   t t jt| | |dS )N)min)rd   sqrtclamprf   rQ   ri   r   r   r   length   s   rn   c                 C   s   | t | | S )N)rn   rm   r   r   r   safe_normalize   s   ro   c                 C   sX   t | tjrt|  n| }tj|t|jd dg gdd}t	||
 d S )Nr   r   )ZaxisN.)
isinstancer&   Zndarrayrd   Z
from_numpycudacatZonesr+   matmult)mtxposZt_mtxZposwr   r   r   transform_pos   s   &rx   c
                 C   s  t ||}
tj| |
|||gd\}}|r/tj|d |||dd\}}tj|d ||d|	d}nt|d ||\}}tj|d |dd}|tj}||d d d	f d d f }||d d d
f d d f }||d d df d d f }tt	|| || }tj
d	|jd	 tjddd d d f d
d}t|d || \}}|d
 d }t|ddd f d	d
}|| d
| t|  }|| d
| t|  }|||fS )N)
resolutionrp   all)Zrast_dbZ
diff_attrszlinear-mipmap-linear)filter_modemax_mip_levelZlinear)r{   r   r   r   rr   )ZdtypeZdevicer         ?.rO   )rx   drZ	rasterizeZinterpolateZtexturetyperd   longro   crossZaranger+   Zint64repeatr   rl   Z	ones_like)Zglctxrv   rw   Zpos_idxr2   Zuv_idxtexry   Z
enable_mipr|   Zpos_clipZrast_outZrast_out_dbZtexcZtexdcolor_Zv0Zv1Zv2Zface_normalsZface_normal_indicesZgb_geometric_normalnormalmaskr   r   r   render   sT   




r   c                 C   s    | dk |dk k}t ||  | S )a  
    Return a tensor where each element has the absolute value taken from the,
    corresponding element of a, with sign taken from the corresponding
    element of b. This is like the standard copysign floating-point operation,
    but is not careful about negative 0 and NaN.

    Args:
        a: source tensor.
        b: tensor whose signs will be used, of the same shape as a.

    Returns:
        Tensor of the same shape as a with the signs of b.
    r   )rd   where)r   bZsigns_differr   r   r   	_copysign   s   r   c                 C   s(   t | }| dk}t | | ||< |S )z[
    Returns torch.sqrt(torch.max(0, x))
    but with a zero subgradient where x is 0.
    r   )rd   Z
zeros_likerk   )rQ   retZpositive_maskr   r   r   _sqrt_positive_part  s   
r   c                 C   s   |  ddks|  ddkrtd| j d| d }| d }| d }d	td
| | |  }d	td
| | |  }d	td
| | |  }d	td
| | |  }t|| d | d  }t|| d | d  }	t|| d | d  }
t|||	|
fdS )z
    Convert rotations given as rotation matrices to quaternions.

    Args:
        matrix: Rotation matrices as tensor of shape (..., 3, 3).

    Returns:
        quaternions with real part first, as tensor of shape (..., 4).
    rO   r   z Invalid rotation matrix  shape f.).r   r   ).r   r   ).r   r   r}   r   ).r   r   ).r   r   ).r   r   ).r   r   ).r   r   ).r   r   )size
ValueErrorr+   r   r   rd   stack)matrixZm00Zm11Zm22Zo0rQ   rU   rV   Zo1o2Zo3r   r   r   matrix_to_quaternion  s   
r   c                 C   s   t j| dddf dddd}t || dddf }d| }d}| |k }t |}t ||  ||   || < d	|| ||  d
  ||< | dddf | S )a  
    Convert rotations given as quaternions to axis/angle.

    Args:
        quaternions: quaternions with real part first,
            as tensor of shape (..., 4).

    Returns:
        Rotations given as a vector in axis angle form, as a tensor
            of shape (..., 3), where the magnitude is the angle
            turned anticlockwise in radians around the vector's
            direction.
    .r   Nr   rO   T)pdimrc   gư>r}   0   )rd   Znormatan2absZ
empty_likerY   )ZquaternionsZnormsZhalf_anglesZanglesri   Zsmall_anglesZsin_half_angles_over_anglesr   r   r   quaternion_to_axis_angle5  s   
r   c                 C   s   t t| S )a{  
    Convert rotations given as rotation matrices to axis/angle.

    Args:
        matrix: Rotation matrices as tensor of shape (..., 3, 3).

    Returns:
        Rotations given as a vector in axis angle form, as a tensor
            of shape (..., 3), where the magnitude is the angle
            turned anticlockwise in radians around the vector's
            direction.
    )r   r   )r   r   r   r   matrix_to_axis_angleR  s   r   d6c                 C   s|   | dddf | dddf }}t j|dd}||| jddd|  }t j|dd}tj||dd}tj|||fddS )	a  
    Converts 6D rotation representation by Zhou et al. [1] to rotation matrix
    using Gram--Schmidt orthogonalisation per Section B of [1].
    Args:
        d6: 6D rotation representation, of size (*, 6)

    Returns:
        batch of rotation matrices of size (*, 3, 3)

    [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H.
    On the Continuity of Rotation Representations in Neural Networks.
    IEEE Conference on Computer Vision and Pattern Recognition, 2019.
    Retrieved from http://arxiv.org/abs/1812.07035
    .Nr   rO   )r   Trb   r   )F	normalizere   rd   r   r   )r   Za1Za2b1b2Zb3r   r   r   rotation_6d_to_matrixb  s   "r   )F)rL   rM   rN   )rh   )r=   rB   numpyr&   Znvdiffrast.torchrd   r~   Ztorch.nn.functionalnnZ
functionalr   r5   rK   rS   rW   r^   r`   ZTensorrf   rg   r   rn   ro   rx   r   r   r   r   r   r   r   r   r   r   r   <module>   s0   
W
>.