Beispiel #1
0
def test_FunctionChain():

    f1 = Function("void f1(){}")
    f2 = Function("void f2(){}")
    f3 = Function("float f3(vec3 x){}")
    f4 = Function("vec3 f4(vec3 y){}")
    f5 = Function("vec3 f5(vec4 z){}")

    ch = FunctionChain('chain', [f1, f2])
    assert ch.name == 'chain'
    assert ch.args == []
    assert ch.rtype == 'void'

    assert_in('f1', ch.compile())
    assert_in('f2', ch.compile())

    ch.remove(f2)
    assert_not_in('f2', ch.compile())

    ch.append(f2)
    assert_in('f2', ch.compile())

    ch = FunctionChain(funcs=[f5, f4, f3])
    assert_equal('float', ch.rtype)
    assert_equal([('vec4', 'z')], ch.args)
    assert_in('f3', ch.compile())
    assert_in('f4', ch.compile())
    assert_in('f5', ch.compile())
    assert_in(f3, ch.dependencies())
    assert_in(f4, ch.dependencies())
    assert_in(f5, ch.dependencies())
Beispiel #2
0
def test_FunctionCall():
    fun = Function(transformScale)
    fun['scale'] = '1.0'
    fun2 = Function(transformZOffset)

    # No args
    assert_raises(TypeError, fun)  # need 1 arg
    assert_raises(TypeError, fun, 1, 2)  # need 1 arg
    call = fun('x')
    # Test repr
    exp = call.expression({fun: 'y'})
    assert_equal(exp, 'y(x)')
    # Test sig
    assert len(call._args) == 1
    # Test dependencies
    assert_in(fun, call.dependencies())
    assert_in(call._args[0], call.dependencies())

    # More args
    call = fun(fun2('foo'))
    # Test repr
    exp = call.expression({fun: 'y', fun2: 'z'})
    assert_in('y(z(', exp)
    # Test sig
    assert len(call._args) == 1
    call2 = call._args[0]
    assert len(call2._args) == 1
    # Test dependencies
    assert_in(fun, call.dependencies())
    assert_in(call._args[0], call.dependencies())
    assert_in(fun2, call.dependencies())
    assert_in(call2._args[0], call.dependencies())
Beispiel #3
0
    def __init__(self, texture, texcoords, enabled=True):
        """Apply a texture on a mesh."""
        vfunc = Function("""
            void pass_coords() {
                $v_texcoords = $texcoords;
            }
        """)
        ffunc = Function("""
            void apply_texture() {
                if ($enabled == 1) {
                    gl_FragColor *= texture2D($u_texture, $texcoords);
                }
            }
        """)
        self._texcoord_varying = Varying('v_texcoord', 'vec2')
        vfunc['v_texcoords'] = self._texcoord_varying
        ffunc['texcoords'] = self._texcoord_varying
        self._texcoords_buffer = VertexBuffer(
            np.zeros((0, 2), dtype=np.float32))
        vfunc['texcoords'] = self._texcoords_buffer
        super().__init__(vcode=vfunc, vhook='pre', fcode=ffunc)

        self.enabled = enabled
        self.texture = texture
        self.texcoords = texcoords
Beispiel #4
0
def _build_color_transform(data, cmap, clim=(0., 1.)):
    if data.ndim == 2 and data.shape[1] == 1:
        fun = Function(_clim)
        fun['cmin'] = clim[0]
        fun['cmax'] = clim[1]
        fun = FunctionChain(None, [fun, Function(cmap.glsl_map)])
    else:
        fun = Function(_null_color_transform)
    return fun
Beispiel #5
0
    def __new__(cls, *args, **kwargs):
        self = super(Filter, cls).__new__(cls)

        if hasattr(cls, 'FRAG_SHADER'):
            self.fshader = Function(self.FRAG_SHADER)
            self.fshader_expr = self.fshader()

        if hasattr(cls, 'VERT_SHADER'):
            self.vshader = Function(self.VERT_SHADER)
            self.vshader_expr = self.vshader()

        return self
Beispiel #6
0
def test_StatementList():
    func = Function("void func() {}")
    main = Function("void main() {}")
    main['pre'] = StatementList()
    expr = func()
    main['pre'].append(expr)
    assert main['pre'].items == [expr]
    main['pre'].add(expr)
    assert main['pre'].items == [expr]

    code = main.compile()
    assert " func();" in code

    main['pre'].remove(expr)
    assert main['pre'].items == []
Beispiel #7
0
def test_StatementList():
    func = Function("void func() {}")
    main = Function("void main() {}")
    main['pre'] = StatementList()
    expr = func()
    main['pre'].add(expr, 0)
    assert list(main['pre'].items) == [expr]
    main['pre'].add(expr)
    assert list(main['pre'].items) == [expr]
    
    code = main.compile()
    assert " func();" in code
    
    main['pre'].remove(expr)
    assert list(main['pre'].items) == []
Beispiel #8
0
 def cmap(self, cmap):
     self._cmap = get_colormap(cmap)
     self.shared_program.frag['cmap'] = Function(self._cmap.glsl_map)
     # Colormap change fix
     self.shared_program['texture2D_LUT'] = (self.cmap.texture_lut() if (
         hasattr(self.cmap, 'texture_lut')) else None)
     self.update()
Beispiel #9
0
 def set_cmap(self, label, cmap):
     if isinstance(cmap, str):
         cmap = get_colormap(cmap)
     self.volumes[label]['cmap'] = cmap
     index = self.volumes[label]['index']
     self.shared_program.frag['cmap{0:d}'.format(index)] = Function(
         cmap.glsl_map)
    def __init__(self,
                 n_volume_max=10,
                 threshold=None,
                 relative_step_size=0.8,
                 emulate_texture=False):

        Visual.__init__(self)

        self._n_volume_max = n_volume_max

        # Only show back faces of cuboid. This is required because if we are
        # inside the volume, then the front faces are outside of the clipping
        # box and will not be drawn.
        self.set_gl_state('translucent', cull_face=False)
        tex_cls = TextureEmulated3D if emulate_texture else Texture3D

        # Storage of information of volume
        self._initial_shape = True
        self._vol_shape = ()
        self._vertex_cache_id = ()
        self._clim = None

        # Create gloo objects
        self._vbo = None
        self._tex = tex_cls((10, 10, 10),
                            interpolation='linear',
                            wrapping='clamp_to_edge')

        # Set custom vertex shader
        vert_shader, frag_shader = get_shaders(n_volume_max)
        frag_dict['additive_multi_volume'] = frag_shader

        # Create program
        self._program = ModularProgram(vert_shader)
        self.textures = []
        for i in range(n_volume_max):
            self.textures.append(
                tex_cls((10, 10, 10),
                        interpolation='linear',
                        wrapping='clamp_to_edge'))
            self._program['u_volumetex_{0}'.format(i)] = self.textures[i]
        self._index_buffer = None

        # Set params
        self.method = 'additive_multi_volume'
        self.relative_step_size = relative_step_size

        for i in range(n_volume_max):
            self._program.frag['cmap{0:d}'.format(i)] = Function(
                get_colormap('grays').glsl_map)
            self._program['u_enabled_{0}'.format(i)] = 0
            self._program['u_weight_{0}'.format(i)] = 1

        self.xd = None

        self._block_size = None

        self.volumes = {}

        self._create_vertex_data()
Beispiel #11
0
def test_colormap():
    """Test named colormaps."""
    autumn = get_colormap('autumn')
    assert autumn.glsl_map is not ""
    assert len(autumn[0.]) == 1
    assert len(autumn[0.5]) == 1
    assert len(autumn[1.]) == 1
    assert len(autumn[[0., 0.5, 1.]]) == 3
    assert len(autumn[np.array([0., 0.5, 1.])]) == 3

    fire = get_colormap('fire')
    assert_array_equal(fire[0].rgba, np.ones((1, 4)))
    assert_array_equal(fire[1].rgba, np.array([[1, 0, 0, 1]]))

    grays = get_colormap('grays')
    assert_array_equal(grays[.5].rgb, np.ones((1, 3)) * .5)

    hot = get_colormap('hot')
    assert_allclose(hot[0].rgba, [[0, 0, 0, 1]], 1e-6, 1e-6)
    assert_allclose(hot[0.5].rgba, [[1, .52272022, 0, 1]], 1e-6, 1e-6)
    assert_allclose(hot[1.].rgba, [[1, 1, 1, 1]], 1e-6, 1e-6)

    # Test the GLSL and Python mapping.
    for name in get_colormaps():
        colormap = get_colormap(name)
        Function(colormap.glsl_map)
        colors = colormap[np.linspace(-2., 2., 50)]
        assert colors.rgba.min() >= 0
        assert colors.rgba.max() <= 1
Beispiel #12
0
 def __init__(self, cmap, zrange=(0, 1)):
     if isinstance(cmap, str):
         cmap = colormap.get_colormap(cmap)
     self.cmap = Function(cmap.glsl_map)
     self.fshader['cmap'] = self.cmap
     self.fshader['zrange'] = zrange
     self.vshader['zval'] = Varying('v_zval', dtype='float')
     self.fshader['zval'] = self.vshader['zval']
Beispiel #13
0
    def __init__(self, enabled=True, color='black', width=1.0,
                 wireframe_only=False, faces_only=False):
        self._attached = False
        self._color = Color(color)
        self._width = width
        self._enabled = enabled
        self._wireframe_only = wireframe_only
        self._faces_only = faces_only

        vfunc = Function(wireframe_vertex_template)
        ffunc = Function(wireframe_fragment_template)

        self._bc = VertexBuffer(np.zeros((0, 3), dtype=np.float32))
        vfunc['bc'] = self._bc

        super().__init__(vcode=vfunc, fcode=ffunc)
        self.enabled = enabled
Beispiel #14
0
 def _build_color_transform(self):
     if self.num_channels != 3:
         raise NotImplementedError(
             "MultiChannelimageVisuals only support 3 channels.")
     else:
         # RGB/A image data (no colormap)
         fclim = Function(_apply_clim)
         fgamma = Function(_apply_gamma)
         fun = FunctionChain(
             None, [Function(_null_color_transform), fclim, fgamma])
     fclim['clim_r'] = self._texture.textures[0].clim_normalized
     fclim['clim_g'] = self._texture.textures[1].clim_normalized
     fclim['clim_b'] = self._texture.textures[2].clim_normalized
     fgamma['gamma_r'] = self.gamma[0]
     fgamma['gamma_g'] = self.gamma[1]
     fgamma['gamma_b'] = self.gamma[2]
     return fun
Beispiel #15
0
 def _build_color_transform(self):
     # this first line should be the only difference from the same method in base Image
     if len(self.tile_shape) == 2 or self.tile_shape[2] == 1:
         # luminance data
         fclim = Function(self._func_templates['clim_float'])
         fgamma = Function(self._func_templates['gamma_float'])
         # NOTE: red_to_luminance only uses the red component, fancy internalformats
         #   may need to use the other components or a different function chain
         fun = FunctionChain(
             None,
             [
                 Function(self._func_templates['red_to_luminance']),
                 fclim,
                 fgamma,
                 Function(self.cmap.glsl_map),
             ],
         )
     else:
         # RGB/A image data (no colormap)
         fclim = Function(self._func_templates['clim'])
         fgamma = Function(self._func_templates['gamma'])
         fun = FunctionChain(
             None,
             [
                 Function(self._func_templates['null_color_transform']),
                 fclim,
                 fgamma,
             ],
         )
     fclim['clim'] = self._texture.clim_normalized
     fgamma['gamma'] = self.gamma
     return fun
Beispiel #16
0
    def __init__(self, data):
        super(SignalsVisual, self).__init__()

        self._program = ModularProgram(self.VERTEX_SHADER,
                                       self.FRAGMENT_SHADER)

        nsignals, nsamples = data.shape
        # nsamples, nsignals = data.shape

        self._data = data

        a_index = np.c_[np.repeat(np.arange(nsignals), nsamples),
                        np.tile(np.arange(nsamples), nsignals)].astype(
                            np.float32)

        # Doesn't seem to work nor to be very efficient.
        # indices = nsignals * np.arange(nsamples)
        # indices = indices[None, :] + np.arange(nsignals)[:, None]
        # indices = indices.flatten().astype(np.uint32)
        # self._ibuffer = gloo.IndexBuffer(indices)

        self._buffer = gloo.VertexBuffer(data.reshape(-1, 1))
        self._program['a_position'] = self._buffer
        self._program['a_index'] = a_index

        x_transform = Function(X_TRANSFORM)
        x_transform['nsamples'] = nsamples
        self._program.vert['get_x'] = x_transform

        y_transform = Function(Y_TRANSFORM)
        y_transform['scale'] = Variable('uniform float u_signal_scale', 5.)
        y_transform['nsignals'] = nsignals
        self._program.vert['get_y'] = y_transform
        self._y_transform = y_transform

        colormap = Function(DISCRETE_CMAP)
        cmap = np.random.uniform(size=(1, nsignals, 3), low=.5,
                                 high=.9).astype(np.float32)
        tex = gloo.Texture2D((cmap * 255).astype(np.uint8))
        colormap['colormap'] = Variable('uniform sampler2D u_colormap', tex)
        colormap['ncolors'] = nsignals
        self._program.frag['get_color'] = colormap
 def __init__(self):
     self.shader = Function("""
         void apply_alpha() {
             // perception
             const vec3 w = vec3(1, 1, 1);
             float value = dot(gl_FragColor.rgb, w);
             if ( value == 0) {
                 gl_FragColor.a = 0;
             }
         }
     """)
Beispiel #18
0
 def __init__(self, *args, **kwargs):
     kwargs.update(width = 40)
     visuals.LineVisual.__init__(self, *args, **kwargs)
     self.unfreeze()
     try:
         colormap = get_colormap(self._color)
         color = Function(colormap.glsl_map)
     except KeyError:
         color = Color(self._color).rgba
     self.non_selected_color = color
     self.freeze()
Beispiel #19
0
 def symbol(self, symbol):
     if symbol == self._symbol:
         return
     self._symbol = symbol
     if symbol is None:
         self._marker_fun = None
     else:
         _check_valid('symbol', symbol, marker_types)
         self._marker_fun = Function(_marker_dict[symbol])
         self._marker_fun['v_size'] = self._v_size_var
         self.shared_program.frag['marker'] = self._marker_fun
     self.update()
Beispiel #20
0
    def __init__(self, shading='flat', enabled=True, light_dir=(10, 5, -5),
                 light_color=(1, 1, 1, 1),
                 ambient_color=(.3, .3, .3, 1),
                 diffuse_color=(1, 1, 1, 1),
                 specular_color=(1, 1, 1, 1),
                 shininess=100):
        self._shading = shading
        self._enabled = enabled
        self._light_dir = light_dir
        self._light_color = Color(light_color)
        self._ambient_color = Color(ambient_color)
        self._diffuse_color = Color(diffuse_color)
        self._specular_color = Color(specular_color)
        self._shininess = shininess

        vfunc = Function(shading_vertex_template)
        ffunc = Function(shading_fragment_template)

        self._normals = VertexBuffer(np.zeros((0, 3), dtype=np.float32))
        vfunc['normal'] = self._normals

        super().__init__(vcode=vfunc, fcode=ffunc)
Beispiel #21
0
 def __init__(self, texture, transform, scale):
     self.fshader = Function("""
         void apply_texture_mask() {
             vec4 tex_pos = $transform(gl_FragCoord);
             tex_pos /= tex_pos.w;
             vec4 mask = texture2D($texture, tex_pos.xy);
             mask.w = 1.0;
             gl_FragColor = gl_FragColor * mask;
         }
     """)
     self.fshader['texture'] = texture
     self.scale_tr = STTransform(scale=scale) * STTransform(translate=(0.5,
                                                                       0.5))
     self.fshader['transform'] = self.scale_tr * transform
Beispiel #22
0
def test_example2():
    """ Demonstrate how a transform would work.
    """

    vert_template = Function("""
    void main(void)
    {
        gl_Position = $position;
    }
    """)

    transformScale = Function("""
    vec4 transform_scale(vec4 pos)
    {
        pos.xyz *= $scale;
        return pos;
    }
    """)

    class Transform(object):
        def __init__(self):
            # Equivalent methods to create new function object
            self.func = Function(transformScale)
            self.func['scale'] = 'uniform float'
            #self.func = Function(transformScale)

        def set_scale(self, scale):
            self.func['scale'].value = scale

    transforms = [Transform(), Transform(), Transform()]

    code = Function(vert_template)
    ob = Variable('attribute vec3 a_position')
    for trans in transforms:
        ob = trans.func(ob)
    code['position'] = ob
    print(code)
Beispiel #23
0
    def __init__(self, texture, texcoords, enabled=True):
        """Apply a texture on a mesh.

        Parameters
        ----------
        texture : (M, N) or (M, N, C) array
            The 2D texture image.
        texcoords : (N, 2) array
            The texture coordinates.
        enabled : bool
            Whether the display of the texture is enabled.
        """
        vfunc = Function("""
            void pass_coords() {
                $v_texcoords = $texcoords;
            }
        """)
        ffunc = Function("""
            void apply_texture() {
                if ($enabled == 1) {
                    gl_FragColor *= texture2D($u_texture, $texcoords);
                }
            }
        """)
        self._texcoord_varying = Varying('v_texcoord', 'vec2')
        vfunc['v_texcoords'] = self._texcoord_varying
        ffunc['texcoords'] = self._texcoord_varying
        self._texcoords_buffer = VertexBuffer(
            np.zeros((0, 2), dtype=np.float32)
        )
        vfunc['texcoords'] = self._texcoords_buffer
        super().__init__(vcode=vfunc, vhook='pre', fcode=ffunc)

        self.enabled = enabled
        self.texture = texture
        self.texcoords = texcoords
Beispiel #24
0
 def __init__(self):
     self.shader = Function("""
         void screen_filter() {
             float f = gl_FragCoord.x * 0.4 + gl_FragCoord.y;
             f = mod(f, 20);
             
             if( f < 5.0 ) {
                 discard;
             }
             
             if( f < 20.0 ) {
                 gl_FragColor.g = gl_FragColor.g + 0.05 * (20-f);
             }
         }
     """)
Beispiel #25
0
    def method(self, method):
        # Check and save
        known_methods = list(frag_dict.keys())
        if method not in known_methods:
            raise ValueError('Volume render method should be in %r, not %r' %
                             (known_methods, method))
        self._method = method
        # Get rid of specific variables - they may become invalid
        if 'u_threshold' in self.shared_program:
            self.shared_program['u_threshold'] = None

        self.shared_program.frag = frag_dict[method]
        self.shared_program.frag['sampler_type'] = self._tex.glsl_sampler_type
        self.shared_program.frag['sample'] = self._tex.glsl_sample
        self.shared_program.frag['cmap'] = Function(self._cmap.glsl_map)
        self.update()
Beispiel #26
0
 def method(self, method):
     # Check and save
     known_methods = list(frag_dict.keys())
     if method not in known_methods:
         raise ValueError('Volume render method should be in %r, not %r' %
                          (known_methods, method))
     self._method = method
     self.shared_program.frag = frag_dict[method]
     self.shared_program.frag['sampler_type'] = self._tex.glsl_sampler_type
     self.shared_program.frag['sample'] = self._tex.glsl_sample
     self.shared_program.frag['cmap'] = Function(self._cmap.glsl_map)
     self.shared_program['texture2D_LUT'] = (self.cmap.texture_lut() if (
         hasattr(self.cmap, 'texture_lut')) else None)
     if 'u_threshold' in self.shared_program:
         self.shared_program['u_threshold'] = self.threshold
     self.update()
Beispiel #27
0
def _build_color_transform(grayscale: bool, clim, gamma, cmap):
    if grayscale:
        fclim = Function(_apply_clim_float)
        fgamma = Function(_apply_gamma_float)
        fun = FunctionChain(
            None, [Function(_c2l), fclim, fgamma,
                   Function(cmap.glsl_map)])
    else:
        fclim = Function(_apply_clim)
        fgamma = Function(_apply_gamma)
        fun = FunctionChain(None,
                            [Function(_null_color_transform), fclim, fgamma])
    fclim['clim'] = clim
    fgamma['gamma'] = gamma
    return fun
Beispiel #28
0
def _build_color_transform(data, clim, gamma, cmap):
    if data.ndim == 2 or data.shape[2] == 1:
        fclim = Function(_apply_clim_float)
        fgamma = Function(_apply_gamma_float)
        fun = FunctionChain(
            None, [Function(_c2l), fclim, fgamma,
                   Function(cmap.glsl_map)])
    else:
        fclim = Function(_apply_clim)
        fgamma = Function(_apply_gamma)
        fun = FunctionChain(None,
                            [Function(_null_color_transform), fclim, fgamma])
    fclim['clim'] = clim
    fgamma['gamma'] = gamma
    return fun
Beispiel #29
0
    def _build_interpolation(self):
        # assumes 'nearest' interpolation
        interpolation = self._interpolation
        if interpolation != 'nearest':
            raise NotImplementedError(
                "MultiChannelImageVisual only supports 'nearest' interpolation."
            )
        texture_interpolation = 'nearest'

        self._data_lookup_fn = Function(_rgb_texture_lookup)
        self.shared_program.frag['get_data'] = self._data_lookup_fn
        if self._texture.interpolation != texture_interpolation:
            self._texture.interpolation = texture_interpolation
        self._data_lookup_fn['texture_r'] = self._texture.textures[0]
        self._data_lookup_fn['texture_g'] = self._texture.textures[1]
        self._data_lookup_fn['texture_b'] = self._texture.textures[2]

        self._need_interpolation_update = False
Beispiel #30
0
def test_function_changed():
    ch = []
    
    class C(object):
        def _dep_changed(self, dep, **kwargs):
            ch.append(dep)
    ch_obj = C()
        
    def assert_changed(*objs):
        assert set(ch) == set(objs)
        while ch:
            ch.pop()
        
    fun1 = Function('void main(){$var1; $var2;}')
    fun1._dependents[ch_obj] = None
    fun1['var1'] = 'x'
    fun1['var2'] = 'y'
    assert_changed(fun1)
    
    fun1['var1'] = 'z'
    assert_changed(fun1)
    
    # same value; should result in no change events
    fun1['var1'] = 'z'
    assert_changed()
    
    fun1['var1'] = 0.5
    var1 = fun1['var1']
    var1._dependents[ch_obj] = None
    assert_changed(fun1)
    
    var1.name = 'xxx'
    assert_changed(fun1, var1)
    
    # changing type requires code change
    var1.value = 7
    assert_changed(fun1, var1)

    # changing value (but not type) requires no code changes
    var1.value = 6
    assert_changed()

    # test variable disconnect
    fun1['var1'] = Variable('var1', 7)
    var2 = fun1['var1']
    var2._dependents[ch_obj] = None
    #assert_changed(fun1)
    # var2 is now connected
    var2.value = (1, 2, 3, 4)
    assert_changed(fun1, var2)
    # ..but var1 no longer triggers fun1.changed
    assert_changed()
    var1.value = 0.5
    assert_changed(var1)

    # test expressions
    fun2 = Function('float fn(float x){return $var1 + x;}')
    fun3 = Function('float fn(float x){return $var1 + x;}')
    exp1 = fun2(fun3(0.5))
    fun1['var2'] = exp1
    assert_changed(fun1)
    
    fun2._dependents[ch_obj] = None
    fun3._dependents[ch_obj] = None
    exp1._dependents[ch_obj] = None
    
    fun2['var1'] = 'x'
    assert_changed(fun1, fun2, exp1)
    
    fun3['var1'] = 'x'
    assert_changed(fun1, fun3, exp1)

    # test disconnect
    fun1['var2'] = fun2
    assert_changed(fun1)
    # triggers change
    fun2['var1'] = 0.9
    assert_changed(fun1, fun2, exp1)
    # no longer triggers change
    fun3['var1'] = 0.9
    assert_changed(fun3, exp1)
Beispiel #31
0
def test_function_basics():
    
    # Test init fail
    assert_raises(TypeError, Function)  # no args
    assert_raises(ValueError, Function, 3)  # need string

    # Test init success 1
    fun = Function('void main(){}')
    assert_equal(fun.name, 'main')
    assert len(fun.template_vars) == 0
    
    # Test init success with template vars
    fun = Function('void main(){$foo; $bar;}')
    assert_equal(fun.name, 'main')
    assert len(fun.template_vars) == 2
    assert_in('foo', fun.template_vars)
    assert_in('bar', fun.template_vars)
    
    # Test setting verbatim expressions
    assert_raises(KeyError, fun.__setitem__, 'bla', '33')  # no such template
    fun['foo'] = '33'
    fun['bar'] = 'bla bla'
    assert_is(type(fun['foo']), TextExpression)
    assert_equal(fun['foo'].expression(None), '33')
    assert_is(type(fun['bar']), TextExpression)
    assert_equal(fun['bar'].expression(None), 'bla bla')
    
    # Test setting call expressions
    fun = Function('void main(){\n$foo;\n$bar;\n$spam(XX);\n$eggs(YY);\n}')
    trans = Function('float transform_scale(float x) {return x+1.0;}')
    assert_raises(TypeError, trans)  # requires 1 arg 
    assert_raises(TypeError, trans, '1', '2')
    fun['foo'] = trans('2')
    fun['bar'] = trans('3')
    fun['spam'] = trans
    fun['eggs'] = trans
    #
    for name in ['foo', 'bar']:
        assert_is(type(fun[name]), FunctionCall)
        assert_equal(fun[name].function, trans)
        assert_in(trans, fun.dependencies())
    for name in ['spam', 'eggs']:
        assert_equal(fun[name], trans)
        
    #
    text = fun.compile()
    assert_in('\ntransform_scale(2);\n', text)
    assert_in('\ntransform_scale(3);\n', text)
    assert_in('\ntransform_scale(XX);\n', text)
    assert_in('\ntransform_scale(YY);\n', text)
    
    # test pre/post assignments
    fun = Function('void main() {some stuff;}')
    fun['pre'] = '__pre__'
    fun['post'] = '__post__'
    text = fun.compile()
    assert text == 'void main() {\n    __pre__\nsome stuff;\n    __post__\n}\n'
    
    # Test variable expressions
    fun = Function('void main(){$foo; $bar;}')
    fun['foo'] = Variable('uniform float bla')
    fun['bar'] = Variable('attribute float bla')
    assert_is(type(fun['foo']), Variable)
    assert_is(type(fun['bar']), Variable)
    assert_in(fun['foo'], fun.dependencies())
    assert_in(fun['bar'], fun.dependencies())
    
    # Test special variables
    fun = Function('void main(){$foo; $bar;}')
    variable = Variable('attribute vec3 v_pos')
    varying = Variable('varying vec3 color')
    # These do not work due to index
    assert_raises(TypeError, fun.__setitem__, 3, 3)  # not a string
    assert_raises(KeyError, fun.__setitem__, 'xxx', 3)  # unknown template var
    assert_raises(TypeError, fun.__setitem__, variable, 3)  # only varyings
    # These work
    fun['gl_PointSize'] = '3.0'
    fun[varying] = variable
    # And getting works
    assert_equal(fun['gl_PointSize'].text, '3.0')
    assert_equal(fun[varying], variable)
Beispiel #32
0
    ),
}
PROJECTIONS['lcc'] = (
    lcc_init,
    PROJECTIONS['lcc'][1],
    PROJECTIONS['lcc'][1],
    PROJECTIONS['lcc'][3],
    PROJECTIONS['lcc'][3],
)

# Misc GLSL functions used in one or more mapping functions above
adjlon_func = Function("""
    float adjlon(float lon) {
        if (abs(lon) <= M_PI) return (lon);
        lon += M_PI; // adjust to 0..2pi rad
        lon -= M_TWOPI * floor(lon / M_TWOPI); // remove integral # of 'revolutions'
        lon -= M_PI;  // adjust back to -pi..pi rad
        return( lon );
    }
    """)

pj_msfn = Function("""
    float pj_msfn(float sinphi, float cosphi, float es) {
        return (cosphi / sqrt (1. - es * sinphi * sinphi));
    }
    """)


def pj_msfn_py(sinphi, cosphi, es):
    return cosphi / np.sqrt(1. - es * sinphi * sinphi)
Mayo systems electrophysiology lab
Mayo Clinic
200 1st St SW
Rochester, MN
United States
"""

from vispy import gloo, visuals
import OpenGL.GL as GL
from vispy.scene.visuals import create_visual_node
from vispy.visuals.shaders import Function
import numpy as np

vec1to4 = Function("""
    in int gl_VertexID;
    vec4 vec1to4(float inp) {
        return vec4(gl_VertexID, inp, 0, 1);
    }
""")

vec2to4 = Function("""
    //in int gl_VertexID;
    vec4 vec2to4(vec2 inp) {
        return vec4(inp, 0, 1);
    }
""")

vec3to4 = Function("""
    //in int gl_VertexID;
    vec4 vec3to4(vec3 inp) {
        return vec4(inp, 1);
    }