
    jH                        d Z 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	Z	 ddl
mZ ddl	mZmZ  e	j                  d      Z ej                   d	g d
      Zd ZddZd ZddZddZddZddZ G d d      ZddZdeiZy)z
Parsing functions for Binvox files.

https://www.patrickmin.com/binvox/binvox.html

Exporting meshes as binvox files requires the
`binvox` executable to be in your path.
    N)TemporaryDirectory   )util)Trimesh)comment_stripdecode_textbinvoxBinvox)rle_datashape	translatescalec                 H   t        | j                               j                         }d|j                         vrt	        d      i }d}t        d      D ]u  }t        t        | j                               j                         d      j                         j                         }t        |      dk(  r_|d   dk(  rd} n|d	d
 ||d   <   w |st	        d      d|j                         vrt	        d|j                          d      t        j                  |d   t        j                        }t        j                  |j                  dg d      t        j                        }t        j                  |j                  dd	g      t        j                        }|||d   fS )a  
    Read the header from a binvox file.
    Spec available:
    https://www.patrickmin.com/binvox/binvox.html

    Parameters
    ------------
    fp: file-object
      File like object with binvox file

    Returns
    ----------
    shape : tuple
      Shape of binvox according to binvox spec
    translate : tuple
      Translation
    scale : float
      Scale of voxels

    Raises
    ------------
    IOError
      If invalid binvox file.
    r	   z!File is not in the binvox format!Fd   #r   dataT   Nz1Didn't reach header termination magic word `data`dimz;Malformed binvox header: `dim` is required, only received ``dtyper   r   r   r   r   )r   readlinestriplower
ValueErrorranger   splitlenkeysnparrayint64getfloat64)	file_objfirstheaderreached_data_liner   r   r   s	            D/DATA/.local/lib/python3.12/site-packages/trimesh/exchange/binvox.py_parse_binvox_headerr-      ss   6 ))+,224Eu{{}$<==FL3Z +h&7&7&9:@@BCHNNPVVX 	 t9>!W  L qr(tAw! $ LMMFKKM!I&++-XYZ
 	

 HHVE]"((3E K;RZZHIHHVZZ!-RZZ@E)U1X%%    c                     t        |       \  }}}| j                         }t        j                  |t        j                        }|r|j                         }t        ||||      S )ax  
    Read a binvox file, spec at
    https://www.patrickmin.com/binvox/binvox.html

    Parameters
    ------------
    fp: file-object
      File like object with binvox file

    Returns
    ----------
    binvox : namedtuple
      Containing data
    rle : numpy array
      Run length encoded data

    Raises
    ------------
    IOError
      If invalid binvox file
    r   )r-   readr!   
frombufferuint8copyr
   )fp	writeabler   r   r   r   r   s          r,   parse_binvoxr6   `   sS    . 326E9e779D}}T2H==?(E9e44r.   c                 X    d | D        \  }}}|\  }}}d| d| d| d| d| d| d| dS )a/  
    Get a binvox header string.

    Parameters
    --------
    shape: length 3 iterable of ints denoting shape of voxel grid.
    translate: length 3 iterable of floats denoting translation.
    scale: num length of entire voxel grid.

    Returns
    --------
    string including "data
" line.
    c              3   2   K   | ]  }t        |        y wN)int).0ss     r,   	<genexpr>z binvox_header.<locals>.<genexpr>   s     (%Q#a&%   z'#binvox 1
# generated in `trimesh`
dim  z
translate z
scale z
data
 )	r   r   r   sxsysztxtytzs	            r,   binvox_headerrG      sd     )%(JBBJBBD"Qrd $at1RD g 	 r.   c                     | j                   t        j                  k7  rt        d| j                          t	        |||      j                         }|| j                         z   S )a  Get a binary representation of binvox data.

    Parameters
    --------
    rle_data : numpy array
      Run-length encoded numpy array.
    shape : (3,) int
      Shape of voxel grid.
    translate : (3,) float
      Translation of voxels
    scale : float
      Length of entire voxel grid.

    Returns
    --------
    data : bytes
      Suitable for writing to binary file
    z%rle_data.dtype must be np.uint8, got )r   r!   r2   r   rG   encodetobytes)r   r   r   r   r(   s        r,   binvox_bytesrK      sW    & ~~!@@PQRR5)U3::<FH$$&&&r.   c                    ddl m} ddlm} ddlm} t        | |j                        r| }n|j                  | t              }|j                  |t        j                        dz
  z  |      }	|dk(  r7d	}
t        fd
|
D              |j                        j                  |
      }n%||dk(  r|j                        }nt        d|      |j                   k(  sJ  |||	      S )a  
    Factory for building from data associated with binvox files.

    Parameters
    ---------
    rle_data : numpy
      Run-length-encoded of flat voxel
      values, or a `trimesh.rle.RunLengthEncoding` object.
      See `trimesh.rle` documentation for description of encoding
    shape : (3,) int
      Shape of voxel grid.
    translate : (3,) float
      Translation of voxels
    scale : float
      Length of entire voxel grid.
    encoded_axes : iterable
      With values in ('x', 'y', 'z', 0, 1, 2),
      where x => 0, y => 1, z => 2
      denoting the order of axes in the encoded data. binvox by
      default saves in xzy order, but using `xyz` (or (0, 1, 2)) will
      be faster in some circumstances.

    Returns
    ---------
    result : VoxelGrid
      Loaded voxels
    r   )transformations)encoding)	VoxelGridr   r   )r   r   xzyr   r   r   c              3   (   K   | ]	  }|     y wr9   r@   )r;   pr   s     r,   r=   z$voxel_from_binvox.<locals>.<genexpr>   s     -1eAhs   xyzz5Invalid axis_order '%s': must be None, 'xyz' or 'xzy') rM   voxelrN   
voxel.baserO   
isinstanceRunLengthEncodingboolscale_and_translater!   r"   tuplereshape	transposer   r   )r   r   r   r   
axis_orderrM   encrO   rN   	transformperms    `         r,   voxel_from_binvoxrc      s    : #'&(C112(((>  33rxx*+y 4 I U---##E*44T:		zU2##E*CZ
 	
 >>U"""Xy))r.   c                     ||dk7  rt        d|       t        | d      }t        |j                  |j                  |j
                  |j                  |      S )a  
    Load trimesh `VoxelGrid` instance from file.

    Parameters
    -----------
    file_obj : file-like object
      Contains binvox data
    resolver : unused
    axis_order : str
      Order of axes in encoded data.
      Binvox default is 'xzy', but 'xyz' may be faster
      where this is not relevant.

    Returns
    ---------
    result : trimesh.voxel.VoxelGrid
      Loaded voxel data
    r	   z&file_type must be None or binvox, got T)r5   )r   r   r   r   r_   )r   r6   rc   r   r   r   r   )r&   resolverr_   	file_typer   s        r,   load_binvoxrg      s\    & h!6A)MNND1Djj..jj r.   c                 L   | j                   }| j                  t        j                  | j                        dz
  z  }t        j
                  |dk        \  }| j                  j                  |      }t        j                  |      }t        j                  |d   |dd d|d   z  dz         st        d      |d   }|dk(  r|j                  d      }n|d	k7  rt        d
      |j                  j                  t        j                        }t!        || j                  ||      S )a  
    Export `trimesh.voxel.VoxelGrid` instance to bytes

    Parameters
    ------------
    voxel : `trimesh.voxel.VoxelGrid`
      Assumes axis ordering of `xyz` and encodes
      in binvox default `xzy` ordering.
    axis_order : str
      Eements in ('x', 'y', 'z', 0, 1, 2), the order
      of axes to encode data (standard is 'xzy' for binvox). `voxel`
      data is assumed to be in order 'xyz'.

    Returns
    -----------
    result : bytes
      Representation according to binvox spec
    r   r   Ngư>g:0yE>z)Can only export binvox with uniform scalerP   rQ   rT   z1Invalid axis_order: must be one of ("xyz", "xzy")r   )r   r   r   )translationr   r!   r"   r   whererN   flipabsr   allcloser   r^   flatrun_length_datar2   rK   )rV   r_   r   r   	neg_scalerN   r   s          r,   export_binvoxrq     s    & !!IKK288EKK0145E88EAI&LY~~""9-HFF5ME==q59dU1Xo.DEDEE!HEU%%i0	u	LMM}},,288,<HyPUVVr.   c                   `    e Zd ZdZdZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZed        Zd	dZ	y)
Binvoxerae  
    Interface for binvox CL tool.

    This class is responsible purely for making calls to the CL tool. It
    makes no attempt to integrate with the rest of trimesh at all.

    Constructor args configure command line options.

    `Binvoxer.__call__` operates on the path to a mode file.

    If using this interface in published works, please cite the references
    below.

    See CL tool website for further details.

    https://www.patrickmin.com/binvox/

    @article{nooruddin03,
        author = {Fakir S. Nooruddin and Greg Turk},
        title = {Simplification and Repair of Polygonal Models Using Volumetric
                 Techniques},
        journal = {IEEE Transactions on Visualization and Computer Graphics},
        volume = {9},
        number = {2},
        pages = {191--205},
        year = {2003}
    }

    @Misc{binvox,
        author = {Patrick Min},
        title =  {binvox},
        howpublished = {{	t http://www.patrickmin.com/binvox} or
                        {	t https://www.google.com/search?q=binvox}},
        year =  {2004 - 2019},
        note = {Accessed: yyyy-mm-dd}
    }
    )	ugobjoffdfxxglpovbrepplyjot)r	   hipsmiravtkraw	schematicmshNc                    |t         }n|}|t        dj                  g d            |dkD  r|st        d|      |t        j
                  vrt        d| dt        j
                        |dt        |      d	|g}|r|j                  d
       |r|rn1|j                  d       n|r|j                  d       nt        d      |r|j                  d       |Bt        |      dk7  rt        d      |j                  d       |j                  d |D               |r|j                  d       |	r|j                  d       |j                  d|
z         |j                  d|z         |r|j                  d       |r|j                  d       ||j                  d|f       |r|j                  d       |r|j                  d       |Lt        j                  |      }t        |      |k7  rt        d|      |j                  dt        |      z         ||j                  dt        |      f       |j                  d       || _        || _        || _        y) a  
        Configure the voxelizer.

        Parameters
        ------------
        dimension: voxel grid size (max 1024 when not using exact)
        file_type: str
          Output file type, supported types are:
            'binvox'
            'hips'
            'mira'
            'vtk'
            'raw'
            'schematic'
            'msh'
        z_buffer_carving : use z buffer based carving. At least one of
            `z_buffer_carving` and `z_buffer_voting` must be True.
        z_buffer_voting: use z-buffer based parity voting method.
        dilated_carving: stop carving 1 voxel before intersection.
        exact: any voxel with part of a triangle gets set. Does not use
            graphics card.
        bounding_box: 6-element float list/tuple of min, max values,
            (minx, miny, minz, maxx, maxy, maxz)
        remove_internal: remove internal voxels if True. Note there is some odd
            behaviour if boundary voxels are occupied.
        center: center model inside unit cube.
        rotate_x: number of 90 degree ccw rotations around x-axis before
            voxelizing.
        rotate_z: number of 90 degree cw rotations around z-axis before
            voxelizing.
        wireframe: also render the model in wireframe (helps with thin parts).
        fit: only write voxels in the voxel bounding box.
        block_id: when converting to schematic, use this as the block ID.
        use_matrial_block_id: when converting from obj to schematic, parse
            block ID from material spec "usemtl blockid_<id>" (ids 1-255 only).
        use_offscreen_pbuffer: use offscreen pbuffer instead of onscreen
            window.
        downsample_factor: downsample voxels by this factor in each dimension.
            Must be a power of 2 or None. If not None/1 and `core dumped`
            errors occur, try slightly adjusting dimensions.
        downsample_threshold: when downsampling, destination voxel is on if
            more than this number of voxels are on.
        verbose : bool
          If False, silences stdout/stderr from subprocess call.
        binvox_path : str
          Path to binvox executable. The default looks for an
          executable called `binvox` on your `PATH`.
        Nr?   )z8No `binvox_path` provided and no binvox executable foundz<on PATH, please go to https://www.patrickmin.com/binvox/ andz!download the appropriate version.i   z-Maximum dimension using exact is 1024, got %d
file_type z& not in set of supported output types z-dz-tz-ez-cz-vz;One of `z_buffer_carving` or `z_buffer_voting` must be Truez-dc   z!bounding_box must have 6 elementsz-bbc              3   2   K   | ]  }t        |        y wr9   )str)r;   bs     r,   r=   z$Binvoxer.__init__.<locals>.<genexpr>  s     51Ar>   z-riz-cb)z-rotx)z-rotzz-awz-fitz-biz-mbz-pbz.downsample_factor must be a power of 2, got %d)z-downz-dminPATH)binvox_encoderOSErrorjoinr   rs   SUPPORTED_OUTPUT_TYPESr   appendr   extendr!   log2r:   _args
_file_typeverbose)self	dimensionrf   z_buffer_carvingz_buffer_votingdilated_carvingexactbounding_boxremove_internalcenterrotate_xrotate_z	wireframefitblock_iduse_material_block_iduse_offscreen_pbufferdownsample_factordownsample_thresholdr   binvox_pathencoderargstimess                           r,   __init__zBinvoxer.__init__q  sJ   N $G!G?  tELiXXH;;;YK'MhNmNmMpq  s9~tY?KKD!KKM  KK #< A% !DEEKKKK555KKKKJ)*J)*KKKKKK)* KK KK(GG-.E5zU" DFW  KK
SZ/0+KK#&:";<=F
#r.   c                     | j                   S r9   )r   )r   s    r,   rf   zBinvoxer.file_type  s    r.   c                    t         j                  j                  |      \  }}|dd j                         }|t        j
                  vrt        d| dt        j
                        | d| j                   }t         j                  j                  |      r|st        d      || j                  d<   t        j                  | j                  t        j                        }| j                  rt        j                   j#                  |       |S )	as  
        Create an voxel file in the same directory as model at `path`.

        Parameters
        ------------
        path: string path to model file. Supported types:
            'ug'
            'obj'
            'off'
            'dfx'
            'xgl'
            'pov'
            'brep'
            'ply'
            'jot' (polygongs only)
        overwrite: if False, checks the output path (head.file_type) is empty
            before running. If True and a file exists, raises an IOError.

        Returns
        ------------
        string path to voxel file. File type give by file_type in constructor.
        r   Nr   z% not in set of supported input types .z-Attempted to voxelize object at existing path)stderr)ospathsplitextr   rs   SUPPORTED_INPUT_TYPESr   r   isfiler   r   
subprocesscheck_outputSTDOUTr   r   logdebug)r   r   	overwriteheadextout_path	verbositys          r,   __call__zBinvoxer.__call__  s    . GG$$T*	c!"gmmoh444SE!FxGeGeFhi  V1T__-.77>>(#IIJJ

2 ++DJJz?P?PQ	 <<HHNN9%r.   )    r	   TTFTNFFr   r   FFNFFNNFNF)
__name__
__module____qualname____doc__r   r   r   propertyrf   r   r@   r.   r,   rs   rs   4  sv    $L
 ##!+Qf  *r.   rs   c                    t        | t              st        d|       |t        di |}nt	        |      dkD  rt        d      |j
                  dk7  rt        d      t               5 }t        j                  j                  |d|       }t        |d      5 }| j                  ||	       ddd        ||      }t        |d
      5 }t        |      }ddd       ddd       S # 1 sw Y   ;xY w# 1 sw Y   xY w# 1 sw Y   S xY w)a  
    Interface for voxelizing Trimesh object via the binvox tool.

    Implementation simply saved the mesh in the specified export_type then
    runs the `Binvoxer.__call__` (using either the supplied `binvoxer` or
    creating one via `binvoxer_kwargs`)

    Parameters
    ------------
    mesh: Trimesh object to voxelize.
    binvoxer: optional Binvoxer instance.
    export_type: file type to export mesh as temporarily for Binvoxer to
        operate on.
    **binvoxer_kwargs: kwargs for creating a new Binvoxer instance. If binvoxer
        if provided, this must be empty.

    Returns
    ------------
    `VoxelGrid` object resulting.
    z#mesh must be Trimesh instance, got Nr   z+Cannot provide binvoxer and binvoxer_kwargsr	   z6Only "binvox" binvoxer `file_type` currently supportedzmodel.wb)rf   rbr@   )rX   r   r   rs   r   rf   r   r   r   r   openexportrg   )	meshbinvoxerexport_typebinvoxer_kwargsfolder
model_pathr4   r   	out_models	            r,   voxelize_meshr   5  s    * dG$>thGHH.o.	_		!FGGX%QRR		WW\\&F;-*@A
*d#rKKkK2 $J'(D!R#BI " 
  $# "! 
 s<   *0D C(.D 
C4D (C1	-D 4C=	9D  D
r   )r   r   )Ng      ?rP   )NrP   N)rP   )Nrv   )r   collectionsr   r   tempfiler   numpyr!   rU   r   baser   r   r   whichr   
namedtupler
   r-   r6   rG   rK   rc   rg   rq   rs   r   _binvox_loadersr@   r.   r,   <module>r      s     	  '    - H%			*U	VC&L5D4'49*x> WF~ ~B%P [)r.   