a
    ijL                  
   @   sZ  d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZmZ ddlZddlZedZdd	l	mZmZ ddlZd
ZG dd deZejZddlmZ dZejrzddlmZmZmZmZ W n. ey Z  ze!d W Y dZ [ n
dZ [ 0 0 edu r@G dd deZG dd deZG dd deZG dd deZi Z"dd Z#dddZ$dS )a  VertexBufferObject helper class

Basic usage:

    my_data = numpy.array( data, 'f')
    my_vbo = vbo.VBO( my_data )
    ...
    my_vbo.bind()
    try:
        ...
        glVertexPointer( my_vbo, ... )
        ...
        glNormalPointer( my_vbo + 12, ... )
    finally:
        my_vbo.unbind()
    
    or 
    
    with my_vbo:
        ...
        glVertexPointer( my_vbo, ... )
        ...
        glNormalPointer( my_vbo + 12, ... )        

See the OpenGLContext shader tutorials for a gentle introduction on the 
usage of VBO objects:

    http://pyopengl.sourceforge.net/context/tutorials/shader_intro.xhtml

This implementation will choose either the ARB or Core (OpenGL 1.5) 
implementation of the VBO functions.
    )ArrayDatatype)FormatHandler)_types)error)bytesunicodeas_8_bitNzOpenGL.arrays.vbo)longinteger_types)VBO
VBOHandlermapVBOc                   @   sd   e Zd ZdZg ZdZedd Zedd Zd	 Z
dZd	d
 Zdd Zdd ZeZdd Zi ZdS )ImplementationzBAbstraction point for the various implementations that can be usedNc                 C   s   | j |  d S N)IMPLEMENTATION_CLASSESappend)cls r   O/home/ghrups/robot-bench/.venv/lib/python3.9/site-packages/OpenGL/arrays/vbo.pyregister7   s    zImplementation.registerc                 G   s0   | j d u r*| jD ]}| }|r|t_  q*q| j S r   )CHOSENr   r   )r   argspossibleimplementationr   r   r   get_implementation;   s    

z!Implementation.get_implementationa  glGenBuffers
    glBindBuffer 
    glBufferData 
    glBufferSubData 
    glDeleteBuffers
    glMapBuffer
    glUnmapBuffer
    GL_STATIC_DRAW
    GL_STATIC_READ
    GL_STATIC_COPY
    GL_DYNAMIC_DRAW
    GL_DYNAMIC_READ
    GL_DYNAMIC_COPY
    GL_STREAM_DRAW
    GL_STREAM_READ
    GL_STREAM_COPY
    GL_ARRAY_BUFFER
    GL_ELEMENT_ARRAY_BUFFER
    GL_UNIFORM_BUFFER
    GL_TEXTURE_BUFFER
    GL_TRANSFORM_FEEDBACK_BUFFERFc                 C   s0   | dr|ds(| do.|do.|dkS )NglARBZGL_ZglInitVertexBufferObjectARB)
startswithendswithselfnamer   r   r   _arbname\   s
    zImplementation._arbnamec                 C   s4   | dr|d d S | dr,|d d S |S d S )NZ_ARBr   )r   r   r   r   r   basenameb   s
    

zImplementation.basenamec                 C   s   | j S r   )	availabler    r   r   r   __nonzero__j   s    zImplementation.__nonzero__c                    s$   t jtj fdd}|S )z5Produce a deleter callback to delete the given bufferc               
      s    rz   }W n0 ty@ } zW Y d }~qW Y d }~q d }~0 0 z|}d| W q  ttfy } zW Y d }~q d }~0 0 q zj  W n$ ty } zW Y d }~n
d }~0 0 d S )N   )pop
IndexErrorglDeleteBuffersAttributeError	TypeError
_DELETERS_KeyError)r   namedbuffererrbufbuffersZgluintkeyZnfer    r   r   doBufferDeletionv   s    "z0Implementation.deleter.<locals>.doBufferDeletion)r   NullFunctionErrorr   ZGLuint)r    r6   r7   r8   r   r5   r   deletero   s    zImplementation.deleter)__name__
__module____qualname____doc__r   r   classmethodr   r   splitZEXPORTED_NAMESr&   r"   r%   r(   __bool__r:   r/   r   r   r   r   r   1   s   

	r   )acceleratesupport)r   	VBOOffsetr   VBOOffsetHandlerz5Unable to load VBO accelerator from OpenGL_acceleratec                   @   s   e Zd ZdZdZdZd#ddZdZee	Z
d	d
 Zd$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d Zdd Zdd  ZeZd%d!d"ZdS )&r   a'  Instances can be passed into array-handling routines

        You can check for whether VBOs are supported by accessing the implementation:

            if bool(vbo.get_implementation()):
                # vbo version of code
            else:
                # fallback version of code
        FTGL_DYNAMIC_DRAWGL_ARRAY_BUFFERNc                 C   s(   || _ | || || _g | _g | _dS )a  Initialize the VBO object

            data -- PyOpenGL-compatible array-data structure, numpy arrays, ctypes arrays, etc.
            usage -- OpenGL usage constant describing expected data-flow patterns (this is a hint
                to the GL about where/how to cache the data)

                GL_STATIC_DRAW_ARB
                GL_STATIC_READ_ARB
                GL_STATIC_COPY_ARB
                GL_DYNAMIC_DRAW_ARB
                GL_DYNAMIC_READ_ARB
                GL_DYNAMIC_COPY_ARB
                GL_STREAM_DRAW_ARB
                GL_STREAM_READ_ARB
                GL_STREAM_COPY_ARB

                DRAW constants suggest to the card that the data will be primarily used to draw
                on the card.  READ that the data will be read back into the GL.  COPY means that
                the data will be used both for DRAW and READ operations.

                STATIC suggests that the data will only be written once (or a small number of times).
                DYNAMIC suggests that the data will be used a small number of times before being
                discarded.
                STREAM suggests that the data will be updated approximately every time that it is
                used (that is, it will likely only be used once).

            target -- VBO target to which to bind (array or indices)
                GL_ARRAY_BUFFER -- array-data binding
                GL_ELEMENT_ARRAY_BUFFER -- index-data binding
                GL_UNIFORM_BUFFER -- used to pass mid-size arrays of data packed into a buffer
                GL_TEXTURE_BUFFER -- used to pass large arrays of data as a pseudo-texture
                GL_TRANSFORM_FEEDBACK_BUFFER -- used to receive transformed vertices for processing

            size -- if not provided, will use arrayByteCount to determine the size of the data-array,
                thus this value (number of bytes) is required when using opaque data-structures,
                (such as ctypes pointers) as the array data-source.
            N)usage	set_arraytargetr6   _copy_segments)r    datarG   rI   sizer   r   r   __init__   s
    ,zVBO.__init__c                 C   s&   t |ttfr"t| j| j|S |S )z#Resolve string constant to constant)
isinstancer   r   getattrr   r%   r    valuer   r   r   resolve   s    zVBO.resolvec                 C   s8   || _ d| _|dur|| _n| j dur4t| j | _dS )a  Update our entire array with new data

            data -- PyOpenGL-compatible array-data structure, numpy arrays, ctypes arrays, etc.
            size -- if not provided, will use arrayByteCount to determine the size of the data-array,
                thus this value (number of bytes) is required when using opaque data-structures,
                (such as ctypes pointers) as the array data-source.
            FN)rK   copiedrL   r   arrayByteCount)r    rK   rL   r   r   r   rH      s    
zVBO.set_arrayc                 C   s   |j r|j dkstdt|}|jp*d}|jp:t| j}|dk r^|t| j7 }t|df}|dk r|t| j7 }t|df}|| j|< | j	r| j
r|| t| jkrd| _	n>t|rt| jd }||9 }||9 }| j||| |f dS )a  Set slice of data on the array and vbo (if copied already)

            slice -- the Python slice object determining how the data should
                be copied into the vbo/array
            array -- something array-compatible that will be used as the
                source of the data, note that the data-format will have to
                be the same as the internal data-array to work properly, if
                not, the amount of data copied will be wrong.

            This is a reasonably complex operation, it has to have all sorts
            of state-aware changes to correctly map the source into the low-level
            OpenGL view of the buffer (which is just bytes as far as the GL
            is concerned).
            r)   z(Don't know how to map stepped arrays yetr   FN)stepNotImplementedErrorr   asArraystartstoplenrK   maxrS   r6   rT   rJ   r   )r    slicearrayrK   rX   rY   rL   r   r   r   __setitem__   s,    


zVBO.__setitem__c                 C   s
   t | jS )z.Delegate length/truth checks to our data-array)rZ   rK   r'   r   r   r   __len__,  s    zVBO.__len__c                 C   s    |dvrt | j|S t|dS )z4Delegate failing attribute lookups to our data-array)rK   rG   rI   r6   rS   _I_r   rJ   N)rO   rK   r-   r    r7   r   r   r   __getattr__0  s    
zVBO.__getattr__c                 C   sl   | j rJ dt| jdg| _ | | j| _| | j| _t| | j	| j t
| | jjt
| < | j S )zCreate the internal buffer(s)zAlready created the bufferr)   )r6   r	   r   ZglGenBuffersrR   rI   rG   weakrefrefr:   idr/   r'   r   r   r   create_buffers@  s    zVBO.create_buffersc                 C   s   | j sJ d| jrT| jr| jr| jd\}}}t|}| j| j||| qnB| j	durv| j
du rvt| j	| _
| j| j| j
| j	| j d| _dS )aS  Copy our data into the buffer on the GL side (if required)

            Ensures that the GL's version of the data in the VBO matches our
            internal view of the data, either by copying the entire data-set
            over with glBufferData or by updating the already-transferred
            data with glBufferSubData.
            z)Should do create_buffers before copy_datar   NT)r6   rS   rJ   r*   r   ZvoidDataPointerr   ZglBufferSubDatarI   rK   rL   rT   ZglBufferDatarG   )r    rX   rL   rK   Zdataptrr   r   r   	copy_dataK  s$    

zVBO.copy_datac              
   C   sX   | j rT| j rTz| jd| j d W q ttjfyP } zW Y d}~qd}~0 0 qdS )zDelete this buffer explicitlyr)   r   N)r6   r   r,   r*   r-   r   r9   )r    r3   r   r   r   deleteg  s    z
VBO.deletec                 C   s   | j s|   | j d S )zGet our VBO idr   )r6   rf   r'   r   r   r   __int__p  s    zVBO.__int__c                 C   s0   | j s|   | j| j| j d  |   dS )zBind this buffer for use in vertex calls

            If we have not yet created our implementation-level VBO, then we
            will create it before binding.  Once bound, calls self.copy_data()
            r   N)r6   rf   r   glBindBufferrI   rg   r'   r   r   r   bindv  s    zVBO.bindc                 C   s   | j | jd dS )z7Unbind the buffer (make normal array operations active)r   N)r   rj   rI   r'   r   r   r   unbind  s    z
VBO.unbindc                 C   s,   t |dr|j}t|ts"J dt| |S )z/Add an integer to this VBO (create a VBOOffset)offsetz)Only know how to add integer/long offsets)hasattrrm   rN   r
   rC   r    otherr   r   r   __add__  s    
zVBO.__add__c                 C   s   |    dS )zContext manager exitF)rl   )r    exc_typeexc_valexc_tbr   r   r   __exit__  s    zVBO.__exit__)rE   rF   N)N)NNN)r;   r<   r=   r>   rS   Z
_no_cache_rM   r`   propertyr   r   rR   rH   r^   r_   rb   rf   rg   rh   ri   rk   rl   rq   	__enter__ru   r   r   r   r   r      s2   
   
2
3		r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	rC   zOffset into a VBO instance

        This class is normally instantiated by doing a my_vbo + int operation,
        it can be passed to VBO requiring operations and will generate the
        appropriate integer offset value to be passed in.
        c                 C   s   || _ || _dS )z<Initialize the offset with vbo and offset (unsigned integer)N)vborm   )r    rx   rm   r   r   r   rM     s    zVBOOffset.__init__c                 C   s&   |dkrt | j|S td|f dS )z4Delegate any undefined attribute save vbo to our vborx   zNo %r key in VBOOffsetN)rO   rx   r-   ra   r   r   r   rb     s    zVBOOffset.__getattr__c                 C   s"   t |dr|j}t| j| j| S )zAllow adding integers or other VBOOffset instances

            returns a VBOOffset to the this VBO with other.offset + self.offset
            or, if other has no offset, returns VBOOffset with self.offset + other
            rm   )rn   rm   rC   rx   ro   r   r   r   rq     s    
zVBOOffset.__add__N)r;   r<   r=   r>   rM   rb   rq   r   r   r   r   rC     s   rC   c                   @   sp   e Zd ZdZedZdd ZdddZdd	 Z	e	Z
dd
dZdd Zdd ZdddZdddZdddZdS )r   zHandles VBO instances passed in as array data

        This FormatHandler is registered with PyOpenGL on import of this module
        to provide handling of VBO objects as array data-sources
        r   c                 C   s   dS )z}Retrieve data-pointer from the instance's data

            Is always NULL, to indicate use of the bound pointer
            r   r   r    instancer   r   r   dataPointer  s    zVBOHandler.dataPointerNc                 C   s   | j S )zAlways returns c_void_p(0))vp0r    rz   typeCoder   r   r   
from_param  s    zVBOHandler.from_paramc                 C   s   t ddS )zNot implementedz!Don't have VBO output support yetN)rV   )r    dimsr~   r   r   r   zeros  s    zVBOHandler.zerosc                 C   s   |S )z.Given a value, convert to array representationr   r    rQ   r~   r   r   r   rW     s    zVBOHandler.asArrayc                 C   s   t |jS )z=Given a value, guess OpenGL type of the corresponding pointer)r   arrayToGLTyperK   rP   r   r   r   r     s    zVBOHandler.arrayToGLTypec                 C   s   t |jS r   )r   rT   rK   rP   r   r   r   rT     s    zVBOHandler.arrayByteCountc                 C   s   t |jS )z6Given a data-value, calculate dimensions for the array)r   	arraySizerK   r   r   r   r   r     s    zVBOHandler.arraySizec                 C   s   t |jS )z-Determine unit size of an array (if possible))r   unitSizerK   r   r   r   r   r     s    zVBOHandler.unitSizec                 C   s   t |jS )z<Determine dimensions of the passed array value (if possible))r   
dimensionsrK   r   r   r   r   r     s    zVBOHandler.dimensions)N)N)N)N)N)r;   r<   r=   r>   ctypesc_void_pr|   r{   r   r   ZonesrW   r   rT   r   r   r   r   r   r   r   r     s   




r   c                   @   s"   e Zd ZdZdd ZdddZdS )rD   zHandles VBOOffset instances passed in as array data

        Registered on module import to provide support for VBOOffset instances
        as sources for array data.
        c                 C   s   |j S )zaRetrieve data-pointer from the instance's data

            returns instance' offset
            )rm   ry   r   r   r   r{     s    zVBOOffsetHandler.dataPointerNc                 C   s   t |jS )z%Returns a c_void_p( instance.offset ))r   r   rm   r}   r   r   r   r     s    zVBOOffsetHandler.from_param)N)r;   r<   r=   r>   r{   r   r   r   r   r   rD     s   rD   c                    s    fdd}|S )z=Construct a mapped-array cleaner function to unmap vbo.targetc              
      sF   zt   W n$ ty2 } zW Y d }~nd }~0 0  j j d S r   )	_cleanersr*   	Exceptionr   ZglUnmapBufferrI   )rd   r3   rx   r   r   clean  s
    z_cleaner.<locals>.cleanr   )rx   r   r   r   r   _cleaner  s    r   麈  c                 C   sX   ddl m} | j| j|}t|ttj| j	 }||d}t
|t| t| < |S )at  Map the given buffer into a numpy array...

    Method taken from:
     http://www.mail-archive.com/numpy-discussion@lists.sourceforge.net/msg01161.html

    This should be considered an *experimental* API,
    it is not guaranteed to be available in future revisions
    of this library!

    Simplification to use ctypes cast from comment by 'sashimi' on my blog...
    r   )
frombufferB)numpyr   r   ZglMapBufferrI   r   castZPOINTERZc_byterL   rc   rd   r   r   )rx   accessr   ZvpZvp_arrayr]   r   r   r   r     s    
r   )r   )%r>   ZOpenGL.arrays.arraydatatyper   ZOpenGL.arrays.formathandlerr   ZOpenGL.raw.GLr   ZOpenGLr   ZOpenGL._bytesr   r   r   r   logging	getLogger_logr	   r
   rc   __all__objectr   r   rB   r   ZACCELERATE_AVAILABLEZOpenGL_accelerate.vborC   r   rD   ImportErrorr3   warningr   r   r   r   r   r   r   <module>   s8   !
] 
 w1