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())
def __init__(self, texture, pos): self.vshader = Function(""" void line_of_sight() { vec4 polar_pos = $transform(vec4($pos, 1)); if( polar_pos.x > 0.999 ) { polar_pos.x = 0.001; } vec4 c = texture2D($texture, vec2(polar_pos.x, 0.5)); float depth = c.r; if( polar_pos.y > depth+0.5 ) { $mask = vec3(0.5, 0.5, 1); // out-of-sight objects turn blue } else { $mask = vec3(1, 1, 1); } } """) self.fshader = Function(""" void apply_texture_mask() { gl_FragColor *= vec4($mask,1); } """) self.center = STTransform() self.transform = STTransform( scale=(0.5 / np.pi, 1, 0), translate=(0.5, 0, 0)) * PolarTransform().inverse * self.center self.vshader['pos'] = pos self.vshader['transform'] = self.transform self.vshader['texture'] = texture self.vshader['mask'] = Varying('mask', dtype='vec3') self.fshader['mask'] = self.vshader['mask']
def __init__(self, vcode=None, vhook='post', vpos=5, fcode=None, fhook='post', fpos=5): super(Filter, self).__init__() if vcode is not None: self.vshader = Function(vcode) if isinstance(vcode, str) else vcode self._vexpr = self.vshader() self._vhook = vhook self._vpos = vpos else: self.vshader = None if fcode is not None: self.fshader = Function(fcode) if isinstance(fcode, str) else fcode self._fexpr = self.fshader() self._fhook = fhook self._fpos = fpos else: self.fshader = None self._attached = False
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
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())
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
def test_example1(): """ Just a few simple compositions. """ # Get function objects. Generate random name for transforms code = Function(vert_template) t1 = Function(transformScale) t2 = Function(transformZOffset) t3 = Function(transformScale) # We need to create a variable in order to use it in two places pos = Variable('attribute vec4 a_position') # Compose everything together code['position'] = t1(t2(pos)) code['correction'] = t1(pos) # Look, we use t1 again, different sig code['endtransform'] = t3 # function pointer rather than function call code['nlights'] = '4' t1['scale'] = t2 t3['scale'] = (3.0, 4.0, 5.0) t2['offset'] = '1.0' code2 = Function(frag_template) code2['color'] = Varying('v_position') code['gl_PointSize'] = '3.0' code[code2['color']] = pos print(code)
def __init__(self, shading='flat', ambient_coefficient=(1, 1, 1, 1), diffuse_coefficient=(1, 1, 1, 1), specular_coefficient=(1, 1, 1, 1), shininess=100, light_dir=(10, 5, -5), ambient_light=(1, 1, 1, .25), diffuse_light=(1, 1, 1, 0.7), specular_light=(1, 1, 1, .25), enabled=True): self._shading = shading self._ambient_coefficient = _as_rgba(ambient_coefficient) self._diffuse_coefficient = _as_rgba(diffuse_coefficient) self._specular_coefficient = _as_rgba(specular_coefficient) self._shininess = shininess self._light_dir = light_dir self._ambient_light = _as_rgba(ambient_light) self._diffuse_light = _as_rgba(diffuse_light) self._specular_light = _as_rgba(specular_light) self._enabled = enabled 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)
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)
def __init__(self, opacity, pos): self.opacity = opacity self.vshader = Function(""" void line_of_sight() { vec2 diff = $player_pos.xy - $pos.xy; float dist = length(diff); float s = 0.5; vec2 step = s * diff / dist; int steps = int(dist/s); $visible = 1; vec2 sample_pos = $pos.xy + step/s; for( int i=1; i<steps; i++ ) { float op = texture2D($opacity, (sample_pos+0.5) / $opacity_size).r; if( op > 0 ) { $visible = 0; break; } sample_pos += step; } } """) self.fshader = Function(""" void line_of_sight() { gl_FragColor = gl_FragColor * $visible; //gl_FragColor.r = $visible; } """) self.vshader['opacity'] = opacity self.vshader['opacity_size'] = opacity.shape[:2][::-1] self.vshader['pos'] = pos self.vshader['visible'] = Varying('visible', dtype='float') self.fshader['visible'] = self.vshader['visible']
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
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
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 == []
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
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()
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()
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']
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
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
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
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; } } """)
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()
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()
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)
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
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); } } """)
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()
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()