home *** CD-ROM | disk | FTP | other *** search
/ Hackers Magazine 57 / CdHackersMagazineNr57.iso / Software / Multimedia / k3d-setup-0.7.11.0.exe / lib / site-packages / OpenGL / arrays / formathandler.py < prev    next >
Encoding:
Python Source  |  2008-12-20  |  5.1 KB  |  163 lines

  1. """Base class for the various Python data-format storage type APIs
  2.  
  3. Data-type handlers are specified using OpenGL.plugins module
  4. """
  5. import ctypes
  6. from OpenGL import plugins
  7.  
  8. try:
  9. #    raise ImportError( 'Testing without wrapper' )
  10.     from OpenGL_accelerate.wrapper import HandlerRegistry
  11. except ImportError, err:
  12.     class HandlerRegistry( dict ):
  13.         def __init__( self, match ):
  14.             self.match = match 
  15.         def __call__( self, value ):
  16.             typ = value.__class__
  17.             handler = self.get( typ )
  18.             if handler is None:
  19.                 if hasattr( typ, '__mro__' ):
  20.                     for base in typ.__mro__:
  21.                         handler = self.get( base )
  22.                         if handler is None:
  23.                             handler = self.match( base )
  24.                             if handler:
  25.                                 handler = handler.load()
  26.                         if handler:
  27.                             self[ base ] = handler
  28.                             handler.registerEquivalent( typ, base )
  29.                             self[ typ ] = handler 
  30.                             return handler
  31.                 raise TypeError(
  32.                     """No array-type handler for type %r (value: %s) registered"""%(
  33.                         typ, repr(value)[:50]
  34.                     )
  35.                 )
  36.             return handler
  37.  
  38. class FormatHandler( object ):
  39.     """Abstract class describing the handler interface
  40.     
  41.     Each data-type handler is responsible for providing a number of methods
  42.     which allow it to manipulate (and create) instances of the data-type 
  43.     it represents.
  44.     """
  45.     TYPE_REGISTRY = HandlerRegistry(plugins.FormatHandler.match)
  46.     LAZY_TYPE_REGISTRY = {}  # more registrations
  47.     HANDLER_REGISTRY = {}
  48.     baseType = None
  49.     typeConstant = None
  50.     HANDLED_TYPES = ()
  51.     preferredOutput = None
  52.     isOutput = False
  53.     GENERIC_OUTPUT_PREFERENCES = ['numpy','numeric','ctypesarrays']
  54.     ALL_OUTPUT_HANDLERS = []
  55.     def loadAll( cls ):
  56.         """Load all setuptools-registered FormatHandler classes
  57.         
  58.         register a new datatype with code similar to this in your
  59.         package's setup.py for setuptools:
  60.         
  61.         entry_points = {
  62.             'OpenGL.arrays.formathandler':[
  63.                 'numpy = OpenGL.arrays.numpymodule.NumpyHandler',
  64.             ],
  65.         }
  66.         """
  67.         for entrypoint in plugins.FormatHandler.all():
  68.             cls.loadPlugin( entrypoint )
  69.     @classmethod
  70.     def loadPlugin( cls, entrypoint ):
  71.         """Load a single entry-point via plugins module"""
  72.         if not entrypoint.loaded:
  73.             try:
  74.                 plugin_class = entrypoint.load()
  75.             except ImportError, err:
  76.                 from OpenGL import logs,WARN_ON_FORMAT_UNAVAILABLE
  77.                 log = logs.getLog( 'OpenGL.formathandler' )
  78.                 if WARN_ON_FORMAT_UNAVAILABLE:
  79.                     logFunc = log.warn
  80.                 else:
  81.                     logFunc = log.info 
  82.                 logFunc(
  83.                     'Unable to load registered array format handler %s:\n%s', 
  84.                     entrypoint.name, log.getException( err )
  85.                 )
  86.             else:
  87.                 handler = plugin_class()
  88.                 handler.register( handler.HANDLED_TYPES )
  89.                 cls.HANDLER_REGISTRY[ entrypoint.name ] = handler
  90.                 if handler.isOutput:
  91.                     cls.ALL_OUTPUT_HANDLERS.append( handler )
  92.             entrypoint.loaded = True
  93.     @classmethod
  94.     def typeLookup( cls, type ):
  95.         """Lookup handler by data-type"""
  96.         try:
  97.             return cls.TYPE_REGISTRY[ type ]
  98.         except KeyError, err:
  99.             key = '%s.%s'%(type.__module__,type.__name__)
  100.             plugin = cls.LAZY_TYPE_REGISTRY.get( key )
  101.             if plugin:
  102.                 cls.loadPlugin( plugin )
  103.                 return cls.TYPE_REGISTRY[ type ]
  104.             raise KeyError( """Unable to find data-format handler for %s"""%( type,))
  105.     loadAll = classmethod( loadAll )
  106.     @classmethod
  107.     def chooseOutput( cls, preferred=None ):
  108.         """Initialize and setup our output type"""
  109.         cls.loadAll()
  110.         cls.chooseOutput = cls.chooseOutput_final
  111.         return cls.chooseOutput( preferred )
  112.     @classmethod
  113.     def chooseOutput_final( cls, preferred=None ):
  114.         """Choose our output-capable plugin"""
  115.         if preferred is not None:
  116.             cls.preferredOutput = preferred
  117.         handler = None
  118.         handler = cls.HANDLER_REGISTRY.get( cls.preferredOutput )
  119.         if not handler:
  120.             for preferred in cls.GENERIC_OUTPUT_PREFERENCES:
  121.                 handler = cls.HANDLER_REGISTRY.get( preferred )
  122.                 if handler:
  123.                     break
  124.         if not handler:
  125.             # look for anything that can do output...
  126.             for handler in cls.ALL_OUTPUT_HANDLERS:
  127.                 break
  128.         if not handler:
  129.             raise RuntimeError(
  130.                 """Unable to find any output handler at all (not even ctypes/numpy ones!)"""
  131.             )
  132.         handler.registerReturn()
  133.         return handler
  134.     
  135.     def register( self, types=None ):
  136.         """Register this class as handler for given set of types"""
  137.         if not isinstance( types, (list,tuple)):
  138.             types = [ types ]
  139.         for type in types:
  140.             self.TYPE_REGISTRY[ type ] = self
  141.     def registerReturn( self ):
  142.         """Register this handler as the default return-type handler"""
  143.         FormatHandler.RETURN_HANDLER = self
  144.     def registerEquivalent( self, typ, base ):
  145.         """Register a sub-class for handling as the base-type"""
  146.         
  147.     def from_param( self, value, typeCode=None  ):
  148.         """Convert to a ctypes pointer value"""
  149.     def dataPointer( self, value ):
  150.         """return long for pointer value"""
  151.     def asArray( self, value, typeCode=None ):
  152.         """Given a value, convert to array representation"""
  153.     def arrayToGLType( self, value ):
  154.         """Given a value, guess OpenGL type of the corresponding pointer"""
  155.     def arraySize( self, value, typeCode = None ):
  156.         """Given a data-value, calculate dimensions for the array"""
  157.     def unitSize( self, value, typeCode=None ):
  158.         """Determine unit size of an array (if possible)"""
  159.         if self.baseType is not None:
  160.             return 
  161.     def dimensions( self, value, typeCode=None ):
  162.         """Determine dimensions of the passed array value (if possible)"""
  163.