Advertisement
Guest User

RPython Blender2.5 bridge

a guest
Jul 27th, 2010
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.90 KB | None | 0 0
  1. '''
  2. PyPy Pipe v0.3
  3. Brett Hartshorn 2010 - License BSD
  4. goatman.py@gmail.com
  5.  
  6. Run "./blender -P pypypipe.py"
  7.  
  8. Use CPython as a host for external libs, tested with PyGTK, PyODE, and Pygame
  9. return types limited: bool, tuple, object   # TODO add more
  10. no keyword arguments can be used from RPython, unless you define a custom wrapper.
  11. only simple lambda callbacks are working (these operate in CPython space)
  12. TODO: callback from CPython to RPython
  13.  
  14. Getting Started:
  15.     make sure this file is named pypypipe.py
  16.     copy this file to your pypy trunk folder, or add the path to pypy below PATH2PYPY
  17.     make sure you have pygame, pygtk, and pyode
  18.  
  19. Hacking:
  20.     Dynamic attribute access is not possible, but function calls are ok.
  21.     This is wrapper incomplete, any class with unique init args, or functions with unique
  22.     args must be hand wrapped.  Even the return type may need to be defined.
  23.     See below:
  24.         gen_func_response
  25.         genRPC
  26.         INIT_GROUPS
  27.  
  28.  
  29. pypy hacking notes:
  30.     s = s[1:len(s)-1]       # pypy.rpython.error.TyperError: slice stop must be proved non-negative
  31.     s = s.replace('<','').replace('>','')   # pypy.rpython.error.TyperError: replace only works for char args
  32.     long(string, 16) not allowed
  33.     globals() not allowed
  34.     function return types can not be mixed (required generated return functions per incompatible types)
  35.  
  36. '''
  37. ## Set your PyPy root ##
  38. PATH2PYPY = 'pypy'
  39.  
  40. def pypy_entry_point_test_bpy():
  41.     ops = bpy_ops_wrapped()
  42.     #debug( ops )
  43.     mesh = ops.mesh()
  44.     mesh.primitive_plane_add()
  45.     debug('bpy ops test complete')
  46.  
  47. def pypy_entry_point():
  48.     ## init module level proxies ##
  49.     gtk = gtk_wrapped()
  50.     #pygame = pygame_wrapped()
  51.     #pygame.display = pygame_display_wrapped()
  52.     #pygame.draw = pygame_draw_wrapped()
  53.     #ode = ode_wrapped()
  54.  
  55.     #world = ode.World()
  56.     #world.setERP( 0.8 )
  57.     #world.setCFM( 0.1 )
  58.     #world.setGravity( ( 0, -0.6*10000, 0 ) )
  59.     #body = ode.Body( world )
  60.     #body.addForce( (1,0,0) )       # not having dynamic attribute access is a good thing!?
  61.  
  62.     w = gtk.Window()
  63.     w.set_size_request( 320,200 )
  64.     w.set_title('PyPyGTK v0.1b')
  65.     root = gtk.VBox(); w.add( root )
  66.     root.set_border_width(50)
  67.     lab = gtk.Label()
  68.     lab.set_text( 'hello world' )
  69.     root.pack_start( lab )
  70.     b = gtk.Button( 'click me' )
  71.     b.connect('clicked', "lambda b,l: l.set_text('clicked test')", lab )        # note lambdas are passed as strings
  72.     root.pack_start( b )
  73.     root2 = b.get_parent()
  74.     root2.pack_start( gtk.Label('return instance from CPython works') )
  75.     b = gtk.Button('exit demo')
  76.     b.connect('clicked', 'lambda b: gtk.main_quit()' )
  77.     root2.pack_start( b )
  78.     frame = gtk.Frame('PyODE body position')
  79.     root2.pack_start( frame )
  80.     bodylab = gtk.Label('body pos')
  81.     frame.add( bodylab )
  82.     w.show_all()
  83.  
  84.     w2 = gtk.Window( gtk.WINDOW_POPUP )
  85.     w2.move( 20,240 )
  86.     w2.set_size_request( 320,100 )
  87.     r2 = gtk.VBox(); w2.add( r2 )
  88.     lab2 = gtk.Label('enum values work (this is a popup window)' )
  89.     r2.pack_start( lab2 )
  90.     b2 = gtk.Button('close')
  91.     b2.connect('clicked', "lambda b,w: w.destroy()", w2)
  92.     r2.pack_start( b2 )
  93.     w2.show_all()
  94.  
  95.     #pygame.init()
  96.     #surf = pygame.display.set_mode( (320,240) )
  97.     i = 0
  98.     while True:     # does not block gtk because we have a glib timeout in the other process
  99.         #x = math.sin( radians(i) ) * 100
  100.         #y = math.cos( radians(i) ) * 100
  101.         #pygame.draw.aaline( surf, (255,255,255,255), (160,120), (int(160+x),int(120+y)) )
  102.         #pygame.display.flip()
  103.  
  104.         #world.quickStep( 0.001 )
  105.         #pos = body.getPosition()
  106.         #bodylab.set_text( str(pos) )
  107.  
  108.         i += 1
  109.         if i == 360: raise SystemExit
  110.  
  111.  
  112.  
  113. def pypy_entry_point_test_simple():
  114.     os = os_wrapper()
  115.     print( os.system )
  116.  
  117.  
  118.  
  119.  
  120.  
  121.  
  122.  
  123. ## Reserved Characters, can not be passed from rpython to Cpython by function call in a string
  124. ## you can change them if you need ##
  125. INSTANCE_SEP = '|'
  126. FUNCTION_SEP = '$'
  127. FUNC_ARG_SEP = '^'
  128. ARGUMENT_SEP = '~'
  129. MODULE_SEP = '!'
  130. DO_NOT_CREATE = b'DO_NOT_CREATE'
  131.  
  132. import os, sys, time, inspect, types, select, subprocess, math, pickle
  133. if '.' not in sys.path: sys.path.append( '.' )      # blender253 pickle bug
  134. sys.path.append(PATH2PYPY)      # assumes you have pypy dist in a subfolder, you may need to rename this pypy-trunk
  135. #import pypy.tool.error
  136.  
  137. bpy = glib = gtk = ode = pygame = None
  138. try:
  139.     import glib, gtk
  140.     import pygame, ode
  141. except:
  142.     try:
  143.         import bpy
  144.         ops = bpy.ops
  145.     except: pass
  146.  
  147. DEBUG = False
  148.  
  149. def debug( string ):
  150.     stderr.write( '\t[debug][%s]\n' %string )
  151.     stderr.flush()
  152.  
  153. degToRad = math.pi / 180.0
  154. def radians(x):
  155.     """radians(x) -> converts angle x from degrees to radians
  156.     """
  157.     return x * degToRad
  158.  
  159. def loop():
  160.     #time.sleep(0.01)
  161.     rlist,wlist,xlist = select.select( [read], [write], [], 0.01 )     
  162.     if rlist and wlist: # must wait for both read and write, because read can be selected by itself, but we must also respond
  163.         a = read.readline().decode().strip()
  164.         if a: print( a )
  165.         if a and a.startswith('>'):
  166.             print('ok')
  167.             cname = header = a.split('>')[-1].strip()
  168.             mod = globals()
  169.             if MODULE_SEP in header:
  170.                 mname, cname = header.split( MODULE_SEP )   # should raise syntax error if ! was in arg string
  171.                 mod = mod[ mname ]
  172.  
  173.                 if FUNC_ARG_SEP in cname:
  174.                     cname, args = cname.split( FUNC_ARG_SEP )
  175.                     nargs = string2args( args )
  176.                     cls = getattr( mod, cname )
  177.                     # workaround for functions that return objects
  178.                     if DO_NOT_CREATE in nargs:
  179.                         if DEBUG: print( 'not creating instance' )
  180.                         ID = nargs[-1]; o = INSTANCES[ int(ID) ]
  181.                     else: o = cls( *nargs )
  182.                 else:
  183.                     cls = getattr( mod, cname )
  184.                     try: o = cls()
  185.                     except: o = cls
  186.  
  187.             else: ## module ##
  188.                 #if cname not in mod:   ## this is not useful because it needs to be wrapped beforehand
  189.                 #   print '------importing-------'
  190.                 #   o = __import__( cname, mod )
  191.                 #else:
  192.                 if DEBUG: print( '-----getting module------' )
  193.                 if '.' in cname:
  194.                     x,y = cname.split('.')
  195.                     o = getattr(mod[ x ], y )
  196.                 else: o = mod[ cname ]
  197.  
  198.             ID = id( o )        # cpython object
  199.             INSTANCES[ ID ] = o
  200.             if DEBUG:
  201.                 print( '$cpython instance', o )
  202.                 print( '$instance ID', ID )
  203.             #write.write( b'%s\n' %ID )
  204.             write.write( bytes( str(ID), 'utf-8' ) + b'\n' )
  205.             write.flush()
  206.  
  207.         elif a and a.startswith('@'):
  208.             ID, b = a.split( FUNCTION_SEP )
  209.             ID = int(ID[1:])        # strip the @
  210.             o = INSTANCES[ID]
  211.             if DEBUG: print( '$got instance', o)
  212.             fname,args = b.split(FUNC_ARG_SEP)
  213.             func = getattr( o, fname )
  214.             nargs = string2args( args )
  215.             if DEBUG: print( 'calling', func)
  216.             res = func( *nargs )        # call the function
  217.             ## check the output of the function ##
  218.             r = ''
  219.             if gtk and isinstance(res,gtk.Object):
  220.                 sID = id(res)
  221.                 if sID not in INSTANCES: INSTANCES[ sID ] = res
  222.                 r += '<gtk.%s%s%s>' %(res.__class__.__name__, INSTANCE_SEP, sID)
  223.             elif pygame and isinstance( res, pygame.Surface ):
  224.                 sID = id(res)
  225.                 if sID not in INSTANCES: INSTANCES[ sID ] = res
  226.                 r += '<pygame.%s%s%s>' %(res.__class__.__name__, INSTANCE_SEP, sID)
  227.             elif ode and isinstance( res, (ode.World,ode.Body) ):
  228.                 sID = id(res)
  229.                 if sID not in INSTANCES: INSTANCES[ sID ] = res
  230.                 r += '<ode.%s%s%s>' %(res.__class__.__name__, INSTANCE_SEP, sID)
  231.  
  232.  
  233.             else: r = str( res )
  234.             #sres = sres.replace(' instance at ', INSTANCE_SEP)
  235.             #if type(res) in (tuple,list):
  236.             if DEBUG: print( 'piping back ->', r )
  237.             #write.write( '%s\n' %r )
  238.             write.write( bytes( r, 'utf-8' ) + b'\n' )
  239.             write.flush()
  240.  
  241.     return True
  242.  
  243.  
  244. def pipe( string ): # the types of *args can not change in pypy, convert to strings first
  245.     rl,wl,xl = rpoll.select( [], [1], [], 0 )
  246.     if wl:
  247.         stdout.write( '%s\n' %string )
  248.         stdout.flush()
  249.  
  250. def string2args( string ):
  251.     nargs = []
  252.     for arg in string.split(ARGUMENT_SEP):
  253.         if arg.strip():
  254.             if arg.startswith('@'): nargs.append( INSTANCES[int(arg[1:])] )
  255.             else: nargs.append( eval(arg) )
  256.     return nargs
  257.  
  258. GeneratedResponses = {}
  259. GeneratedClasses = {}
  260. GeneratedRPC = {}
  261.  
  262. def gen_func_response( rtype=object ):
  263.     if rtype is bool:
  264.         def get_function_response(dummy):
  265.             if DEBUG: debug( 'waiting for function response' )
  266.             rl,wl,xl = rpoll.select( [0], [], [], 60 )  # wait 10 seconds, subprocess only needs to wait for reading
  267.             if rl:
  268.                 if DEBUG: debug( 'readline ready' )
  269.                 s = string = stdin.readline().strip('\n').strip(' ')
  270.                 if DEBUG: debug( '^got function response: %s' %string )
  271.                 if s == 'True': return True
  272.                 elif s == 'False': return False
  273.             else:
  274.                 debug( '^^ lost contact with parent process ^^' )
  275.                 raise SystemExit
  276.     elif rtype is tuple:
  277.         def get_function_response(dummy):
  278.             if DEBUG: debug( 'waiting for function response' )
  279.             rl,wl,xl = rpoll.select( [0], [], [], 60 )  # wait 10 seconds, subprocess only needs to wait for reading
  280.             if rl:
  281.                 if DEBUG: debug( 'readline ready' )
  282.                 s = string = stdin.readline().strip('\n').strip(' ')
  283.                 if DEBUG: debug( '^got function response: %s' %string )
  284.                 s = s.replace('(',' ').replace(')',' ').strip(' ')
  285.                 return [ float(x) for x in s.split(',') ]
  286.             else:
  287.                 debug( '^^ lost contact with parent process ^^' )
  288.                 raise SystemExit
  289.  
  290.     elif rtype is object:
  291.         def get_function_response(dummy):
  292.             if DEBUG: debug( 'waiting for function response' )
  293.             rl,wl,xl = rpoll.select( [0], [], [], 60 )  # wait 10 seconds, subprocess only needs to wait for reading
  294.             if rl:
  295.                 if DEBUG: debug( 'readline ready' )
  296.                 s = string = stdin.readline().strip('\n').strip(' ')
  297.                 if DEBUG: debug( '^got function response: %s' %string )
  298.                 if s.startswith('<') and s.endswith('>'):
  299.                     s = s.replace('<',' ').replace('>',' ').strip(' ')
  300.                     if INSTANCE_SEP in s:
  301.                         a,b = s.split( INSTANCE_SEP )       # pypy only splits on a single char
  302.                         ID = int( b )
  303.                         if ID in Cache.instances:
  304.                             if DEBUG: debug( 'proxy already exists' )
  305.                             return Cache.instances[ID]
  306.                         else:
  307.                             if DEBUG: debug( 'creating new rproxy' )
  308.                             cls = GeneratedClasses[ a ]
  309.                             return cls( DO_NOT_CREATE, str(ID) )
  310.             else:
  311.                 debug( '^^ lost contact with parent process ^^' )
  312.                 raise SystemExit
  313.  
  314.     return get_function_response
  315.  
  316. class RCache(object):
  317.     def __init__(self):
  318.         self.instances = {}
  319. Cache = RCache()
  320.  
  321.  
  322. class Proxy(object):        ## pypy only allows __init__ and __del__
  323.     pass
  324. def geninit():      # generating init for each class is too slow
  325.     def __init__(self, *args):
  326.         if self._modulename_: header = '%s%s%s' %(str(self._modulename_), MODULE_SEP, str(self._classname_))
  327.         else: header = self._classname_
  328.         if args:
  329.             a = ''
  330.             for arg in list(args):
  331.                 if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  332.                 elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  333.                     a += '"%s"%s' %(arg, ARGUMENT_SEP)
  334.                 else: a += '%s%s' %(arg, ARGUMENT_SEP)
  335.             pipe( '>create>%s%s%s' %(header, FUNC_ARG_SEP, a) )
  336.         else: pipe( '>create>%s' %str(header) )
  337.         self._ID = 0
  338.         rl,wl,xl = rpoll.select( [0], [], [], 10.0 )    # wait 10 seconds, subprocess only needs to wait for reading
  339.         if rl:
  340.             ID = stdin.readline().strip('\n').strip(' ')
  341.             self._ID = int(ID)
  342.             Cache.instances[ self._ID ] = self
  343.         else:
  344.             pipe( '^^ lost contact with parent process ^^' )
  345.             raise SystemExit
  346.     return __init__
  347. Proxy.__init__ = geninit()
  348.  
  349.  
  350. INSTANCES = {}
  351.  
  352. CALL_GROUPS = { 'tag lambda *args': [], 'pygame.draw.line': [] }
  353. if gtk:
  354.     CALL_GROUPS[ 'tag lambda *args' ].append( gtk.Object.connect )
  355. if pygame:
  356.     CALL_GROUPS[ 'pygame.draw.line' ].append( pygame.draw.line )
  357.     CALL_GROUPS[ 'pygame.draw.line' ].append( pygame.draw.aaline )
  358.  
  359. RETURN_GROUPS = { tuple : [] }
  360. if ode:
  361.     RETURN_GROUPS[ tuple ].append(ode.Body.getPosition)
  362.  
  363.  
  364. class WrapFunction(object):
  365.     def __init__(self, fname, func ):
  366.         self._func_name = fname
  367.         self._call_group = None
  368.         self._return_group = None
  369.         for group in CALL_GROUPS:
  370.             if func in CALL_GROUPS[group]:
  371.                 self._call_group = group
  372.                 break
  373.         for group in RETURN_GROUPS:
  374.             if func in RETURN_GROUPS[group]:
  375.                 self._return_group = group
  376.                 break
  377.  
  378.     def unpack( self ):     ## interesting pypy needs generated functions so that *args can work properly
  379.         fname = self._func_name
  380.         index = len( GeneratedResponses )
  381.         gupdate = {}
  382.         genres_name = '_generated_RPC_closure%s'%index
  383.         if self._return_group:
  384.             gupdate[ genres_name ] = genres_func = gen_func_response( self._return_group )
  385.         else:
  386.             gupdate[ genres_name ] = genres_func = gen_func_response()      # defaults to object
  387.  
  388.         GeneratedResponses[ genres_name ] = genres_func
  389.         genres_func.func_name = genres_name
  390.  
  391.         rpc_name = '_generated_RPC%s'%index
  392.  
  393.         if self._call_group == 'tag lambda *args':
  394.             def rpc( self, name, tag, callback, *args ):
  395.                 if DEBUG: debug( '-rpc %s %s' %(self, name) )
  396.                 a = '"%s"%s' %(tag, ARGUMENT_SEP)
  397.                 a += '%s%s' %(callback, ARGUMENT_SEP)
  398.                 for arg in list(args):
  399.                     if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  400.                     elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  401.                         a += '"%s"%s' %(arg, ARGUMENT_SEP)
  402.                     else: a += '%s%s' %(arg, ARGUMENT_SEP)
  403.                 pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SEP, name, FUNC_ARG_SEP, a) )
  404.             wrap = eval( 'lambda self,tag,cb,*args: %s(%s(self,"%s",tag,cb,*args))' %(genres_name, rpc_name, fname) )
  405.  
  406.         elif self._call_group == 'pygame.draw.line':
  407.             def rpc( self, name, surf, color, start, end, width=1 ):
  408.                 if DEBUG: debug( '-rpc %s %s' %(self, name) )
  409.                 a = '@%s%s' %(surf._ID,ARGUMENT_SEP)
  410.                 a += '%s%s' %(color,ARGUMENT_SEP)
  411.                 a += '%s%s' %(start,ARGUMENT_SEP)
  412.                 a += '%s%s' %(end,ARGUMENT_SEP)
  413.                 a += '%s%s' %(width,ARGUMENT_SEP)
  414.                 pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SEP, name, FUNC_ARG_SEP, a) )
  415.             wrap = eval( 'lambda self,surf,color,start,end,width=1: %s(%s(self,"%s",surf,color,start,end,width))' %(genres_name, rpc_name, fname) )
  416.  
  417.         else:
  418.             def rpc( self, name, *args ):
  419.                 if DEBUG: debug( '-rpc %s %s' %(self, name) )
  420.                 a = ''
  421.                 for arg in list(args):
  422.                     if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  423.                     elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  424.                         a += '"%s"%s' %(arg, ARGUMENT_SEP)
  425.                     else: a += '%s%s' %(arg, ARGUMENT_SEP)
  426.                 pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SEP, name, FUNC_ARG_SEP, a) )
  427.             wrap = eval( 'lambda self,*args: %s(%s(self,"%s",*args))' %(genres_name, rpc_name, fname) )
  428.  
  429.         rpc.func_name = rpc_name
  430.         GeneratedRPC[ rpc_name ] = rpc
  431.         gupdate[ rpc_name ] = rpc
  432.         globals().update( gupdate )
  433.         return wrap
  434.  
  435.  
  436. ## these are considered constants ##
  437. WrappableAttributesTypes = (
  438.     bool,
  439.     int,
  440.     #long,
  441.     float,
  442.     str,
  443.     #unicode,
  444. )
  445. INIT_GROUPS = { int:[], object:[] }
  446. if gtk:
  447.     INIT_GROUPS[ int ].append( gtk.Window )
  448. if ode:
  449.     INIT_GROUPS[ object ].append( ode.Body )
  450.  
  451. INIT_GROUPS_gen = {}
  452. for tag in INIT_GROUPS: INIT_GROUPS_gen[ tag ] = geninit()
  453. del tag
  454.  
  455. class WrapClass(object):
  456.     def __init__( self, cls, classname, modulename, items={} ):
  457.         if modulename: modulename = str(modulename)
  458.         self._classname = str(classname)
  459.         self._modulename = modulename
  460.         self._items = items
  461.         self._init_type = None
  462.         for group in INIT_GROUPS:
  463.             if cls in INIT_GROUPS[group]:
  464.                 self._init_type = group
  465.  
  466.     def unpack( self ):
  467.         classitems = {}
  468.         for key in self._items:
  469.             #debug( key )
  470.             v = self._items[key]
  471.             if isinstance( v, (WrapClass,WrapFunction) ): v = v.unpack()
  472.             classitems[ key ] = v
  473.  
  474.         if self._init_type in INIT_GROUPS_gen:
  475.             classitems['__init__'] = INIT_GROUPS_gen[ self._init_type ] # classes that have the same init vars
  476.  
  477.         self._classname = str(self._classname)
  478.         classitems['_classname_'] = self._classname
  479.         if self._modulename:
  480.             self._modulename = str(self._modulename)
  481.             classitems['_modulename_'] = self._modulename
  482.  
  483.         metaclass = types.ClassType(self._classname, bases=(Proxy,), dict=classitems)
  484.         if self._modulename: key = '%s.%s' %(self._modulename, self._classname)
  485.         else: key = self._classname
  486.         GeneratedClasses[ key ] = metaclass
  487.         return metaclass
  488.  
  489. def wrap_class( cls, classes=False ):
  490.     print( 'wrapping', cls )
  491.     if cls.__class__.__name__ == 'bpy_ops':
  492.         name = 'ops'
  493.         mname = None
  494.     elif cls.__class__.__name__ == 'bpy_ops_submodule':
  495.         name = cls.module       # name of submod "mesh" etc..
  496.         mname = 'ops'
  497.     else:
  498.         name = cls.__name__
  499.         if inspect.ismodule( cls ): mname = None
  500.         else: mname = cls.__module__
  501.     if mname: mname = str(mname)
  502.     name = str(name)
  503.     funcs = {}
  504.     fnames = ''
  505.     d = { '_classname_':str(name), '_modulename_':mname }
  506.  
  507.     for n in dir(cls):
  508.         if n.startswith('_'): continue
  509.         a = getattr( cls, n )
  510.         if inspect.isroutine( a ) or ( isinstance(a,object) and a.__class__.__name__ == 'bpy_ops_submodule_op' ):
  511.             #print( '\tFUNCTION: ', n )
  512.             d[n] = WrapFunction(n,a)
  513.         elif inspect.isclass( a ) and classes:
  514.             #if classes: print '\tCLASS: ', n
  515.             if a.__module__ == 'gtk._gtk': continue
  516.             else: d[ n ] = wrap_class( a )
  517.         elif isinstance(a,object) and a.__class__.__name__ == 'bpy_ops_submodule':
  518.             d[ n ] = wrap_class( a )
  519.         elif type(a) in WrappableAttributesTypes:
  520.             d[ n ] = a
  521.         elif type(a) in (list,tuple):
  522.             safe = True
  523.             for item in a:
  524.                 if type(item) not in WrappableAttributesTypes:
  525.                     safe = False; break
  526.             if safe:
  527.                 d[ n ] = a
  528.         else:
  529.             ## check for gtk enum
  530.             items = dir(a)
  531.             enum = True
  532.             for test in 'conjugate denominator imag numerator real'.split():
  533.                 if test not in items: enum = False; break
  534.             if enum:
  535.                 d[ n ] = a.real
  536.  
  537.     #mclass = types.ClassType(name, bases=(Proxy,), dict=d)
  538.     #if mname: key = '%s.%s' %(mname,name)
  539.     #else: key = name
  540.     #GeneratedClasses[ key ] = mclass
  541.     #globals()[ name ] = mclass
  542.     #return mclass
  543.     wrapped = WrapClass( cls, name, mname, items=d )
  544.     #globals()[ 'wrapped_%s' %time.time() ] = wrapped
  545.     return wrapped
  546.  
  547. if '--pypy' in sys.argv:
  548.     from pypy.rlib import streamio
  549.     from pypy.rlib import rpoll
  550.     from pypy.translator.interactive import Translation
  551.  
  552.     stdin = streamio.fdopen_as_stream(0, 'r', 0)        # fd, mode, buffering
  553.     stdout = streamio.fdopen_as_stream(1, 'w', 0)
  554.     stderr = streamio.fdopen_as_stream(2, 'w', 0)
  555.  
  556.     dump = pickle.load( open('/tmp/genwrapper.pickle','rb') )
  557.     D = globals()
  558.     for key in dump:
  559.         debug( key )
  560.         metaclass = dump[key].unpack()
  561.         debug( metaclass )
  562.         D[ key ] = metaclass
  563.     for k in globals().keys():
  564.         if not k.startswith('_'):
  565.             debug('global %s' %k )
  566.  
  567.     if '--bpy' in sys.argv: t = Translation( pypy_entry_point_test_bpy )
  568.     elif '--gtk' in sys.argv: t = Translation( pypy_entry_point )
  569.     else: t = Translation( pypy_entry_point_simple )
  570.     t.annotate(); t.rtype()
  571.     f = t.compile_c()
  572.     f()
  573.     print( 'subprocess exit' )
  574.  
  575.  
  576. elif __name__ == '__main__':
  577.     import pypypipe     # blender253 pickle bug
  578.     pypypipe.dump()
  579.     test = ''
  580.     if bpy: test = '--bpy'
  581.     elif gtk: test = '--gtk'
  582.     process = subprocess.Popen( 'python pypypipe.py --pypy %s' %test, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0, shell=True )
  583.     write = process.stdin
  584.     read = process.stdout
  585.     print( 'read pipe', read )
  586.     print( 'read write', write )
  587.     if glib:
  588.         glib.timeout_add( 33, loop )
  589.         gtk.main()
  590.     elif bpy:
  591.         bpy.ops.screen.animation_play('EXEC_DEFAULT')
  592.         def draw_callback( area, region ): loop()
  593.         for area in bpy.context.window.screen.areas:
  594.             print(area.type)
  595.             if area.type == 'VIEW_3D':
  596.                 for reg in area.regions:
  597.                     print( '\tregion: ', reg.type )
  598.                     if reg.type == 'WINDOW':
  599.                         print( 'adding callback' )
  600.                         reg.callback_add(draw_callback, (area,reg), 'POST_PIXEL')   # sneaky! unlisted function!!!
  601.  
  602.  
  603.     print( 'toplevel exit' )
  604.  
  605. #else:      # import pypypipe  (blender253 pickle bug)
  606. def dump():
  607.     ## save wrap ##
  608.     D = {}
  609.     if gtk:
  610.         w = wrap_class( gtk, classes=True )
  611.         D['gtk_wrapped'] = w
  612.         #D['pygame_wrapped'] = wrap_class( pygame, classes=True )
  613.         #D['pygame_display_wrapped'] = wrap_class( pygame.display, classes=True )
  614.         #D['pygame_draw_wrapped'] = wrap_class( pygame.draw, classes=True )
  615.         D['ode_wrapped'] = wrap_class( ode, classes=True )
  616.     elif bpy:
  617.         D['bpy_ops_wrapped'] = wrap_class( bpy.ops, classes=True )
  618.  
  619.     else:
  620.         D['os_wrapped'] = wrap_class( os, classes=True )
  621.  
  622.     f = open('/tmp/genwrapper.pickle','wb')
  623.     pickle.dump( D, f, protocol=2)      #,fix_imports=False )
  624.     f.close()
  625.     print( 'genwrapper.pickle dumped' )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement