Example #1
0
    def __init__(self, user_dtype=None, transform=None, viewport=None,
                 vertex=None, fragment=None, **kwargs):
        """
        Initialize the collection.

        Parameters
        ----------

        user_dtype: list
            The base dtype can be completed (appended) by the used_dtype. It
            only make sense if user also provide vertex and/or fragment shaders

        viewport: glumpy.Transforms
            The viewport to use to render the collection

        transform: glumpy.Tranforms
            The default vertex shader apply the supplied transform to the
            vertices positions before computing the actual vertices positions
            for path thickness.

        vertex: string
            Vertex shader code

        fragment: string
            Fragment  shader code

        color : string
            'local', 'shared' or 'global'
        """
        base_dtype = [ ('position', (np.float32, 3), "!local", (0,0,0)),
                       ('size',     (np.float32, 1), "global", 3.0),
                       ('color',    (np.float32, 4), "global", (0,0,0,1) ) ]

        dtype = base_dtype
        if user_dtype:
            dtype.extend(user_dtype)

        if vertex is None:
            vertex = library.get("collections/raw-point.vert")
        if fragment is None:
            fragment= library.get("collections/raw-point.frag")

        Collection.__init__(self, dtype=dtype, itype=None, mode=gl.GL_POINTS,
                            vertex=vertex, fragment=fragment, **kwargs)

        # Set hooks if necessary
        program = self._programs[0]

        if "transform" in program.hooks:
            if transform is not None:
                # FIXME: this line break things because snippet code will be included
                #        and it messes with new snippet code
                program["transform"] = Position()
                program["transform"] = transform
            else:
                program["transform"] = Position()

        if "viewport" in program.hooks:
            if viewport is not None:
                # FIXME: this line break things because snippet code will be included
                #        and it messes with new snippet code
                program["viewport"] = Viewport()
                program["viewport"] = viewport
            else:
                program["viewport"] = Viewport()
Example #2
0
window = app.Window(1024, 1024, color=(1, 1, 1, 1))


@window.event
def on_draw(dt):
    window.clear()
    points.draw()


@window.event
def on_mouse_scroll(x, y, dx, dy):
    if dy < 0:
        transform["exponent"] = np.minimum(10.0, 1.1 * transform["exponent"])
    else:
        transform["exponent"] = np.maximum(0.1, transform["exponent"] / 1.1)


transform = Position(PowerScale())
transform["exponent"] = 2
transform["domain"] = -10, +10

points = PointCollection("agg", transform=transform)
P = np.random.uniform(-100, 100, (10000, 3))
P = np.copysign(np.sqrt(abs(P)), P)
points.append(P)

window.attach(points["transform"])
window.attach(points["viewport"])
app.run()
# program['u_minor_grid_step'] = np.array([ 0.25, np.pi/60])
# program['u_limits1'] = -5.1, +5.1, -5.1, +5.1
# program['u_limits2'] = 1.0, 5.0, 0*np.pi, 2*np.pi

# Cartesian domains
program['u_major_grid_step'] = np.array([1.00, 1.00])
program['u_minor_grid_step'] = np.array([0.10, 0.10])
program['u_limits1'] = -5.1, +5.1, -5.1, +5.1
program['u_limits2'] = -5.0, +5.0, -5.0, +5.0

# Hammer domains
# program['u_major_grid_step'] = np.array([ 1.00, 0.50]) * np.pi/ 6.0
# program['u_minor_grid_step'] = np.array([ 1.00, 0.50]) * np.pi/30.0
# program['u_limits1'] = -3.0, +3.0, -1.5, +1.5
# program['u_limits2'] = -np.pi, +np.pi, -np.pi/3, +np.pi/3

# program['transform'] = shaders.get("transforms/polar.glsl")
# program['transform'] = shaders.get("transforms/hammer.glsl")
program['transform_forward'] = gloo.Snippet(
    library.get("transforms/identity_forward.glsl"))
program['transform_inverse'] = gloo.Snippet(
    library.get("transforms/identity_inverse.glsl"))
program['trackball'] = Trackball(Position("texcoord"))
program['trackball'].theta = 0
program['trackball'].phi = 0
program['trackball'].zoom = 7.5

window.attach(program['trackball'])

app.run()
    if ( i < n ) {
        float nu = log(log(sqrt(d))/log_2)/log_2;
        float index = float(i) + 1.0 - nu;
        float v = pow(index/float(n),0.5);
        gl_FragColor = vec4(hot(v),1.0);
    } else {
        gl_FragColor = vec4(hot(0.0),1.0);
    }
}
"""

window = app.Window(width=1024, height=1024)

@window.event
def on_draw(dt):
    window.clear()
    program.draw(gl.GL_TRIANGLE_STRIP)

@window.event
def on_key_press(key, modifiers):
    if key == app.window.key.SPACE:
        transform.reset()


program = gloo.Program(vertex, fragment, count=4)
program['position'] = [(-1,-1), (-1, 1), ( 1,-1), ( 1, 1)]
program['texcoord'] = [( 0, 1), ( 0, 0), ( 1, 1), ( 1, 0)]
transform = PanZoom(Position("position"),aspect=1)
program['transform'] = transform
window.attach(transform)
app.run()
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import app
from glumpy.graphics.collections import PointCollection
from glumpy.transforms import LinearScale, Position, Viewport

window = app.Window(1024, 1024, color=(1, 1, 1, 1))


@window.event
def on_draw(dt):
    window.clear()
    points.draw()


@window.event
def on_mouse_scroll(x, y, dx, dy):
    if dy < 0:
        transform["domain"] = 1.1 * transform["domain"]
    else:
        transform["domain"] = transform["domain"] / 1.1


transform = Position(LinearScale())
points = PointCollection("agg", transform=transform)
points.append(P=np.random.normal(0, .5, (10000, 3)))

window.attach(points["transform"])
window.attach(points["viewport"])
app.run()
Example #6
0
    def __init__(self,
                 user_dtype=None,
                 transform=None,
                 viewport=None,
                 vertex=None,
                 fragment=None,
                 **kwargs):
        """
        Initialize the collection.

        Parameters
        ----------

        user_dtype: list
            The base dtype can be completed (appended) by the used_dtype. It
            only make sense if user also provide vertex and/or fragment shaders

        viewport: glumpy.Transforms
            The viewport to use to rende the collection

        transform: glumpy.Tranforms
            The default vertex shader apply the supplied transform to the
            vertices positions before computing the actual vertices positions
            for path thickness. Note that it is necessary to add the
            glumpy.transforms.Viewport transform at the end of the supplied transform.

        vertex: string
            Vertex shader code

        fragment: string
            Fragment  shader code

        caps : string
            'local', 'shared' or 'global'

        join : string
            'local', 'shared' or 'global'

        color : string
            'local', 'shared' or 'global'

        miter_limit : string
            'local', 'shared' or 'global'

        linewidth : string
            'local', 'shared' or 'global'

        antialias : string
            'local', 'shared' or 'global'
        """

        base_dtype = [('p0', (np.float32, 3), '!local', (0, 0, 0)),
                      ('p1', (np.float32, 3), '!local', (0, 0, 0)),
                      ('p2', (np.float32, 3), '!local', (0, 0, 0)),
                      ('p3', (np.float32, 3), '!local', (0, 0, 0)),
                      ('uv', (np.float32, 2), '!local', (0, 0)),
                      ('caps', (np.float32, 2), 'global', (0, 0)),
                      ('join', (np.float32, 1), 'global', 0),
                      ('color', (np.float32, 4), 'global', (0, 0, 0, 1)),
                      ('miter_limit', (np.float32, 1), 'global', 4),
                      ('linewidth', (np.float32, 1), 'global', 1),
                      ('antialias', (np.float32, 1), 'global', 1)]

        dtype = base_dtype
        if user_dtype:
            dtype.extend(user_dtype)

        if vertex is None:
            vertex = library.get('collections/agg-path.vert')
        if fragment is None:
            fragment = library.get('collections/agg-path.frag')

        Collection.__init__(self,
                            dtype=dtype,
                            itype=np.uint32,
                            mode=gl.GL_TRIANGLES,
                            vertex=vertex,
                            fragment=fragment,
                            **kwargs)

        # Set hooks if necessary
        program = self._programs[0]
        if "transform" in program.hooks:
            if transform is not None:
                program["transform"] = transform
            else:
                program["transform"] = Position() + Viewport()

        if "viewport" in program.hooks:
            if viewport is not None:
                program["viewport"] = viewport
            else:
                program["viewport"] = Viewport()
Example #7
0
app.use("glfw")  # Required for ImGui integration
window = app.Window(width=1024, height=1024,
                    color=(0.30, 0.30, 0.35, 1.00))

# Build cube data
V, I, O = colorcube()
vertices = V.view(gloo.VertexBuffer)
faces    = I.view(gloo.IndexBuffer)
outline  = O.view(gloo.IndexBuffer)

cube = gloo.Program(vertex, fragment)
cube.bind(vertices)

# create an instance of the TrackballPan object.
trackball = TrackballPan(Position("position"), znear=3, zfar=10, distance=5)
cube['transform'] = trackball

trackball.aspect = 1
# rotation around the X axis
trackball.phi = 0
# rotation around the Y axis
trackball.theta = 0
trackball.zoom = 50


@window.event
def on_draw(dt):
    # GUI
    imguiRenderer.process_inputs()
    imgui.new_frame()
Example #8
0
def glumpyVisualize(voronoiCrystal):
    from glumpy import app, gloo, gl, data
    from glumpy.transforms import Position, Trackball
    from glumpy.graphics.filter import Filter
    vertex = """
uniform vec3 light_position;
attribute vec3 position;
attribute vec3 color;
attribute float radius;
varying float v_size;
varying vec3 v_color;
varying float v_radius;
varying vec4 v_eye_position;
varying vec3 v_light_direction;
void main (void)
{
    v_color = color;
    v_radius = radius;
    v_eye_position = <transform.trackball_view> *
                     <transform.trackball_model> *
                     vec4(position,1.0);
    v_light_direction = normalize(light_position);
    gl_Position = <transform(position)>;
    // stackoverflow.com/questions/8608844/...
    //  ... resizing-point-sprites-based-on-distance-from-the-camera
    vec4 p = <transform.trackball_projection> *
             vec4(radius, radius, v_eye_position.z, v_eye_position.w);
    v_size = 512.0 * p.x / p.w;
    gl_PointSize = v_size + 5.0;
}
"""

    fragment = """
#include "antialias/outline.glsl"
varying float v_size;
varying vec3 v_color;
varying float v_radius;
varying vec4 v_eye_position;
varying vec3 v_light_direction;
void main()
{
    vec2 P = gl_PointCoord.xy - vec2(0.5,0.5);
    float point_size = v_size  + 5.0;
    float distance = length(P*point_size) - v_size/2;
    vec2 texcoord = gl_PointCoord* 2.0 - vec2(1.0);
    float x = texcoord.x;
    float y = texcoord.y;
    float d = 1.0 - x*x - y*y;
    if (d <= 0.0) discard;
    float z = sqrt(d);
    vec4 pos = v_eye_position;
    pos.z += v_radius*z;
    vec3 pos2 = pos.xyz;
    pos = <transform.trackball_projection> * pos;
    gl_FragDepth = 0.5*(pos.z / pos.w)+0.5;
    vec3 normal = vec3(x,y,z);
    float diffuse = clamp(dot(normal, v_light_direction), 0.0, 1.0);
    vec4 color = vec4((0.5 + 0.5*diffuse)*v_color, 1.0);
    gl_FragColor = outline(distance, 1.0, 1.0, vec4(0,0,0,1), color);
    // gl_FragColor = color;
}
	"""
    window = app.Window(width=800, height=800, color=(1, 1, 1, 1))
    particles = gloo.Program(vertex, fragment)
    particles['light_position'] = 0., 0., 2.
    particles["transform"] = Trackball(Position(), distance=500)
    particles.bind(
        getBindDataFromVoronoiCrystals(voronoiCrystal).view(gloo.VertexBuffer))

    @window.event
    def on_draw(dt):
        window.clear()
        particles.draw(gl.GL_POINTS)

    @window.event
    def on_init():
        gl.glEnable(gl.GL_DEPTH_TEST)

    window.attach(particles["transform"])
    app.run()
Example #9
0
import numpy as np
from glumpy import app
from glumpy.graphics.collections import PointCollection
from glumpy.transforms import LinearScale, LogScale, Position

window = app.Window(1024, 1024, color=(1, 1, 1, 1))


@window.event
def on_draw(dt):
    window.clear()
    points.draw()


# lin-lin
transform = Position(LinearScale('.xy', domain=(0, 10)))

# log-lin
transform = Position(LogScale('.x', domain=(-1, 1)),
                     LinearScale('.y', domain=(0, 10)))

# lin-log
transform = Position(LinearScale('.x', domain=(0, 10)),
                     LogScale('.y', domain=(-1, 1)))

# log-log
# transform = Position(LogScale('.xy', domain=(-1,1)))

points = PointCollection("agg", transform=transform, color='local')
X = np.linspace(0.01, 10.0, 10000).reshape(10000, 1)
Z = np.zeros((len(X), 1))
Example #10
0
    return P


@window.event
def on_draw(dt):
    window.clear()
    paths.draw()


@window.event
def on_key_press(key, modifiers):
    if key == app.window.key.SPACE:
        transform.reset()


transform = PanZoom(OrthographicProjection(Position()), aspect=None)

n = 2500
S = star(n=5)
P = np.tile(S.ravel(), n).reshape(n, len(S), 3)
P *= np.random.uniform(5, 10, n)[:, np.newaxis, np.newaxis]
P[:, :, :2] += np.random.uniform(0, 800, (n, 2))[:, np.newaxis, :]
P = P.reshape(n * len(S), 3)

paths = PathCollection(mode="agg", transform=transform)
paths.append(P, closed=True, itemsize=len(S))
paths["linewidth"] = 1.0

window.attach(paths["transform"])
window.attach(paths["viewport"])
app.run()
Example #11
0
}
"""

fragment = """
const vec4 blue  = vec4(0.80,0.80,1.00,1.00);
const vec4 white = vec4(1.00,1.00,1.00,1.00);
uniform sampler2D texture;
varying vec2 v_texcoord;
void main()
{
    float v = texture2D(texture, v_texcoord).r;
    gl_FragColor = mix(white,blue,v);
}
"""

transform = Arcball(Position(), znear=1, zfar=10)
viewport = Viewport()

radius = 1.5
vertices, indices = sphere(radius, 64, 64)
earth = gloo.Program(vertex, fragment)
earth.bind(vertices)
earth['texture'] = data.get("earth-black.jpg")
earth['texture'].interpolation = gl.GL_LINEAR
earth['transform'] = transform

paths = PathCollection(mode="agg+",
                       color="global",
                       linewidth="global",
                       viewport=viewport,
                       transform=transform)
Example #12
0
               "One, two! One, two! And through and through\n"
               "  The vorpal blade went snicker-snack!\n"
               "He left it dead, and with its head\n"
               "  He went galumphing back.\n"
               "\"And, has thou slain the Jabberwock?\n"
               "  Come to my arms, my beamish boy!\n"
               "O frabjous day! Callooh! Callay!'\n"
               "  He chortled in his joy.\n"
               "\n"
               "`Twas brillig, and the slithy toves\n"
               "  Did gyre and gimble in the wabe;\n"
               "All mimsy were the borogoves,\n"
               "  And the mome raths outgrabe.\n")

window = app.Window(width=700, height=700, color=(1, 1, 1, 1))


@window.event
def on_draw(dt):
    window.clear()
    glyphs.draw()


glyphs = GlyphCollection(transform=Trackball(Position()))
glyphs.append(jabberwocky, FontManager.get("Roboto-Regular.ttf"))

window.attach(glyphs["transform"])
window.attach(glyphs["viewport"])

app.run()
Example #13
0
    pos = <transform.trackball_projection> * pos;
    gl_FragDepth = 0.5*(pos.z / pos.w)+0.5;
    vec3 normal = vec3(x,y,z);
    float diffuse = clamp(dot(normal, v_light_direction), 0.0, 1.0);

    vec4 color = vec4((0.5 + 0.5*diffuse)*v_color, 1.0);
    gl_FragColor = outline(distance, 1.0, 1.0, vec4(0,0,0,1), color);
    // gl_FragColor = color;
}
"""

window = app.Window(width=800, height=800, color=(1, 1, 1, 1))

protein = gloo.Program(vertex, fragment)
protein['light_position'] = 0., 0., 2.
protein["transform"] = Trackball(Position())
protein.bind(data.get("protein.npy").view(gloo.VertexBuffer))
protein['color'] *= .25
protein['color'] += .75


@window.event
def on_draw(dt):
    window.clear()
    protein.draw(gl.GL_POINTS)


@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)
Example #14
0
    phi += 0.5  # degrees
    model = np.eye(4, dtype=np.float32)
    glm.rotate(model, theta, 0, 0, 1)
    glm.rotate(model, phi, 0, 1, 0)
    transform['model'] = model


# Build cube data
V, I, O = colorcube()
vertices = V.view(gloo.VertexBuffer)
faces = I.view(gloo.IndexBuffer)
outline = O.view(gloo.IndexBuffer)

cube = gloo.Program(vertex, fragment)
cube.bind(vertices)
transform = PVMProjection(Position("position"))
cube['transform'] = transform
window.attach(transform)

phi, theta = 0, 0

# OpenGL initalization
gl.glEnable(gl.GL_DEPTH_TEST)
gl.glPolygonOffset(1, 1)
gl.glEnable(gl.GL_LINE_SMOOTH)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
gl.glLineWidth(0.75)

# Run
app.run()
Example #15
0
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import app
from glumpy.graphics.collections import PointCollection
from glumpy.transforms import LogScale, Position, Viewport

window = app.Window(1024,1024, color=(1,1,1,1))

@window.event
def on_draw(dt):
    window.clear()
    points.draw()

@window.event
def on_mouse_scroll(x,y,dx,dy):
    if dy < 0:
        transform["base"] = np.minimum(20., 1.1*transform["base"])
    else:
        transform["base"] = np.maximum(1., transform["base"]/1.1)

transform = Position(LogScale())
transform["domain"] = -1,2 # = [base^-1, base^2]
points = PointCollection("agg", transform = transform)
P = np.random.uniform(0,10,(10000,3))
points.append(P*P)

window.attach(points["transform"])
window.attach(points["viewport"])
app.run()
Example #16
0
    source=parents.pop(0)
    for i in range(branch):
        try:
            target=next(nodes)
            parents.append(target)
            A[source,target] = 1
        except StopIteration:
            break

# Current selected node
selected = -1

# Get edges
src,tgt = np.nonzero(A)

transform = OrthographicProjection(Position(), aspect=None)
viewport = Viewport()


markers = collections.MarkerCollection(marker='disc', transform=transform, viewport=viewport)
markers.append(N, size=15, linewidth=2, itemsize=1,
               fg_color=(1,1,1,1), bg_color=(1,.5,.5,1))
segments = collections.SegmentCollection('agg', transform=transform, viewport=viewport)
segments.append(N[src], N[tgt], linewidth=1.0, itemsize=1,
                color=(0.75,0.75,0.75,1.00))

window.attach(transform)
window.attach(viewport)

app.run()
def on_draw(dt):
    window.clear()
    triangles.draw()
    paths.draw()

@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)

@window.event
def on_key_press(key, modifiers):
    if key == app.window.key.SPACE:
        transform.reset()


transform = PanZoom(OrthographicProjection(Position()))
triangles = TriangleCollection("agg", transform=transform, color='shared')
paths = PathCollection("agg", transform=transform, color='shared')
paths["linewidth"] = 10

P = star()
I = triangulate(P)

n = 64
for i in range(n):
    c = i/float(n)
    d = i
    x,y = np.random.uniform(0,800,2)
    s = 25
    triangles.append(P*s+(x,y,d), I, color=(0,0,0,.5))
    paths.append(P*s+(x,y,(d-1)), closed=True, color=(0,0,0,1))
Example #18
0
                          direction=(1, 0, 0),
                          anchor_x="left",
                          anchor_y="center")

        x = xmax - 0.05 * (xmax - xmin)
        labels.append(values[i].upper(),
                      regular,
                      color=c,
                      origin=(x, y, 0),
                      scale=0.002,
                      direction=(1, 0, 0),
                      anchor_x="right",
                      anchor_y="center")


transform = PanZoom(OrthographicProjection(Position(), normalize=True),
                    aspect=1)
transform.zoom = 0.165
viewport = Viewport()

quads = collections.TriangleCollection(transform=transform, viewport=viewport)
labels = collections.GlyphCollection(transform=transform, viewport=viewport)
regular = FontManager.get("OpenSans-Regular.ttf")

x, y = -2.5 * 2.6, +4
for i, name in enumerate([
        "Red", "Pink", "Purple", "Deep Purple", "Indigo", "Blue", "Light Blue",
        "Cyan", "Teal", "Green", "Light Green", "Lime", "Yellow", "Amber",
        "Orange", "Deep Orange", "Brown", "Grey"
]):
    family = "material:%s" % name
# -----------------------------------------------------------------------------
from glumpy import app
from glumpy.graphics.text import FontManager
from glumpy.graphics.collections import GlyphCollection
from glumpy.transforms import Position, OrthographicProjection, Viewport

window = app.Window(width=1200, height=800, color=(1, 1, 1, 1))


@window.event
def on_draw(dt):
    window.clear()
    labels.draw()


labels = GlyphCollection(transform=OrthographicProjection(Position()))
regular = FontManager.get("OpenSans-Regular.ttf")
text = "The quick brown fox jumps over the lazy dog"
x, y, z = 2, window.height, 0

for i in range(6, 54, 2):
    scale = i / 48.0
    y -= i * 1.1
    labels.append(text,
                  regular,
                  origin=(x, y, z),
                  scale=scale,
                  anchor_x="left")

window.attach(labels["transform"])
window.attach(labels["viewport"])
Example #20
0
    gl.glEnable(gl.GL_DEPTH_TEST)


vertices = np.array([[+1, +1, +1], [-1, +1, +1], [-1, -1, +1], [+1, -1, +1],
                     [+1, -1, -1], [+1, +1, -1], [-1, +1, -1], [-1, -1, -1]])
texcoords = np.array([[+1, +1, +1], [-1, +1, +1], [-1, -1, +1], [+1, -1, +1],
                      [+1, -1, -1], [+1, +1, -1], [-1, +1, -1], [-1, -1, -1]])
faces = np.array([
    vertices[i] for i in
    [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 6, 7, 2, 1, 7, 4, 3, 2, 4, 7, 6, 5]
])
indices = np.resize(np.array([0, 1, 2, 0, 2, 3], dtype=np.uint32), 36)
indices += np.repeat(4 * np.arange(6, dtype=np.uint32), 6)
indices = indices.view(gloo.IndexBuffer)
texture = np.zeros((6, 1024, 1024, 3), dtype=np.float32).view(gloo.TextureCube)
texture.interpolation = gl.GL_LINEAR
program = gloo.Program(vertex, fragment, count=24)
program['position'] = faces * 10
program['texcoord'] = faces
program['texture'] = texture
program['transform'] = Trackball(Position(), distance=0)

texture[2] = data.get("sky-left.png") / 255.
texture[3] = data.get("sky-right.png") / 255.
texture[0] = data.get("sky-front.png") / 255.
texture[1] = data.get("sky-back.png") / 255.
texture[4] = data.get("sky-up.png") / 255.
texture[5] = data.get("sky-down.png") / 255.
window.attach(program["transform"])
app.run()
Example #21
0
glm.translate(view, 0, 0, -45)

program['position'] = np.dstack((x, y, z))[0]
program['radius'] = np.ones(n) * 5
program['fg_color'] = 0.8, 0.8, 0.8, 1
# colors = np.random.uniform(0.75, 1.00, (n, 4))
colors = np.ones((n, 4))
colors[:, 0] = np.linspace(0.00, 0.80, n)
colors[:, 1] = 0
colors[:, 2] = 0
colors[:, 3] = 1
program['bg_color'] = colors
program['linewidth'] = 1.0
program['antialias'] = 1.0
program['view'] = view
program['transform'] = Trackball(Position("position"))
window.attach(program['transform'])

if os.path.isfile('active_site.pt'):
    print("... plot with active_site.pt")
    data = np.genfromtxt("active_site.pt",
                         dtype=[('x', 'f8'), ('y', 'f8'), ('z', 'f8')])
    ndata = len(data['x'])
    pro2 = gloo.Program(vertex, fragment, count=ndata)
    pro2['position'] = np.dstack((data['x'], data['y'], data['z']))[0]
    pro2['radius'] = np.ones_like(data['x']) * 3
    pro2['fg_color'] = 0, 0, 0, 1
    colors = np.zeros((ndata, 4))
    colors[:, 0:1] = 0.5
    colors[:, 2] = 1.0
    colors[:, 3] = 0.8
Example #22
0
radius, theta, dtheta = 245.0, 0.0, 6.5 / 180.0 * np.pi
for i in range(500):
    theta += dtheta
    x = 256 + radius * np.cos(theta)
    y = 256 + radius * np.sin(theta)
    r = 10.1 - i * 0.01
    radius -= 0.4
    data['orientation'][i] = theta + np.pi
    data['position'][i] = x, y
    data['size'][i] = 2 * r
    data['linewidth'][i] = 1.5 - 0.5 * i / 500.

data['position'][-1] = 512 + 256, 256
data['size'][-1] = 512 / np.sqrt(2)
data['linewidth'][-1] = 16.0
data['fg_color'][-1] = 0, 0, 0, 1
data['bg_color'][-1] = .95, .95, .95, 1
data['orientation'][-1] = 0

program = gloo.Program("arrows/arrow.vert", "arrows/arrow.frag")
program.bind(data)
program['antialias'] = 1.00
program['arrow'] = "stealth"
program['paint'] = "filled"
transform = OrthographicProjection(Position("position"))
program['transform'] = transform
print transform
window.attach(transform)

app.run()
Example #23
0
    def __init__(self,
                 marker='heart',
                 user_dtype=None,
                 transform=None,
                 viewport=None,
                 vertex=None,
                 fragment=None,
                 **kwargs):
        """
        Initialize the collection.

        Parameters
        ----------

        user_dtype: list
            The base dtype can be completed (appended) by the used_dtype. It
            only make sense if user also provide vertex and/or fragment shaders

        transform: glumpy.Tranforms
            The default vertex shader apply the supplied transform to the
            vertices positions before computing the actual vertices positions
            for path thickness. Note that it is necessary to add the
            glumpy.transforms.Viewport transform at the end of the supplied transform.

        vertex: string
            Vertex shader code

        fragment: string
            Fragment  shader code

        size : string
            'local', 'shared' or 'global'

        orientation : string
            'local', 'shared' or 'global'

        fg_color : string
            'local', 'shared' or 'global'

        bg_color : string
            'local', 'shared' or 'global'

        linewidth : string
            'local', 'shared' or 'global'

        antialias : string
            'local', 'shared' or 'global'
        """

        base_dtype = [('position', (np.float32, 3), '!local', (0, 0, 0)),
                      ('size', (np.float32, 1), 'local', 1),
                      ('marker', (np.float32, 1), 'local', 1),
                      ('orientation', (np.float32, 1), 'local', 0.0),
                      ('fg_color', (np.float32, 4), 'local', (0, 0, 0, 1)),
                      ('bg_color', (np.float32, 4), 'local', (1, 1, 1, 1)),
                      ('linewidth', (np.float32, 1), 'global', 1.0),
                      ('antialias', (np.float32, 1), 'global', 1.0)]
        dtype = base_dtype
        if user_dtype:
            dtype.extend(user_dtype)

        if vertex is None:
            vertex = library.get('collections/marker.vert')
        if fragment is None:
            fragment = library.get('collections/marker.frag')

        Collection.__init__(self,
                            dtype=dtype,
                            itype=None,
                            mode=gl.GL_POINTS,
                            vertex=vertex,
                            fragment=fragment,
                            **kwargs)

        # Set hooks if necessary
        program = self._programs[0]
        if "transform" in program.hooks:
            if transform is not None:
                program["transform"] = transform
            else:
                program["transform"] = Position()

        if "viewport" in program.hooks:
            if viewport is not None:
                program["viewport"] = viewport
            else:
                program["viewport"] = Viewport()

        program["marker"] = marker
        program["paint"] = "outline"
      // the falloff equation, starts at falloff and is kind of 1/x^2 falling
      bl += step(falloff,depthDifference)*normDiff*(1.0-smoothstep(falloff,strength,depthDifference));
   }

   // output the result
   float ao = 1.0 - base*bl/16;
   gl_FragColor.rgb = color * ao;
   gl_FragColor.a = 1.0;
}
"""

window = app.Window(width=800, height=800, color=(1,1,1,1))

protein = gloo.Program(vertex, fragment)
protein['light_position'] = 0., 0., 2.
protein["transform"] = Trackball(Position(), znear=2.0, zfar=100.0)
protein.bind(data.get("protein.npy").view(gloo.VertexBuffer))

ssao= gloo.Program(ssao_vertex, ssao_fragment, count=4)
ssao['position']= [(0,0), (0,1), (1,0), (1,1)]
ssao['base']    = 1.00
ssao['strength']= 0.20;
ssao['falloff'] = 0.000002;
ssao['radius']  = 0.01;

ssao['normals'] = np.zeros((800,800,4),np.float32).view(gloo.Texture2D)
ssao['normals'].interpolation = gl.GL_LINEAR
ssao['colors'] = np.zeros((800,800,4),np.float32).view(gloo.Texture2D)
ssao['colors'].interpolation = gl.GL_LINEAR
ssao['noise'] = np.random.uniform(0,1,(256,256,3))
ssao['noise'].interpolation = gl.GL_LINEAR
                    help='path')
parser.add_argument('--start', type=int, default=0, help='Starting frame')
parser.add_argument('--end', type=int, default=-1, help='Ending frame')
parser.add_argument('--fps', type=int, default=15, help='Ending frame')

opt, _ = parser.parse_known_args()

filenames = np.genfromtxt(join(opt.path_to_data, 'youtube.txt'), dtype=str)
if opt.end == -1:
    opt.end = len(filenames)
filenames = filenames[opt.start:opt.end]

fps = opt.fps
n_frames = len(filenames)

trackball = Trackball(Position("position"),
                      aspect=1,
                      theta=45,
                      phi=45,
                      distance=100,
                      zoom=135)

vertices_field, indices_field = plane()

field = gloo.Program(vertex_tex, fragment_tex)
field.bind(vertices_field)
field['position'] = vertices_field
field['u_texture'] = data.get(join(opt.path_to_data, 'texture.png'))
field['transform'] = trackball

all_programs = []
Example #26
0
                range=(-1.5, 1.5),
                call="forward",
                clamp=True),
    LinearScale('.y',
                name='y',
                domain=(+1, -1),
                range=(-2.4, 2.4),
                call="forward",
                clamp=True))

program['scale'] = Position(
    # This translates cartesian coordinates (mercator domains) to texture coordinates
    LinearScale('.x',
                name='x',
                domain=(-np.pi, np.pi),
                range=(0, 1),
                clamp=True),
    LinearScale('.y',
                name='y',
                domain=(-np.pi / 2, np.pi / 2),
                range=(0, 1),
                clamp=True))
window.set_size(500, 800)


@window.event
def on_mouse_scroll(x, y, dx, dy):
    xdomain = program['projection']['x']['domain']
    ydomain = program['projection']['y']['domain']
    if dy < 0:
        xdomain *= .9
        ydomain *= .9
Example #27
0
    paths.draw()


@window.event
def on_key_press(key, modifiers):
    if key == app.window.key.SPACE:
        reset()


def reset():
    transform.theta = 0
    transform.phi = 0
    transform.zoom = 16.5


transform = Trackball(Position())
viewport = Viewport()
labels = GlyphCollection(transform=transform, viewport=viewport)
paths = PathCollection(mode="agg+", transform=transform, viewport=viewport)
ticks = SegmentCollection(mode="agg",
                          transform=transform,
                          viewport=viewport,
                          linewidth='local',
                          color='local')

# xmin,xmax = 0,800
# ymin,ymax = 0,800
xmin, xmax = -1, 1
ymin, ymax = -1, 1

z = 0
Example #28
0
import numpy as np
from glumpy import app
from glumpy.graphics.collections import PointCollection
from glumpy.transforms import LogScale, LinearScale, PolarProjection, Position, Viewport

window = app.Window(1024, 1024, color=(1, 1, 1, 1))


@window.event
def on_draw(dt):
    window.clear()
    points.draw()


transform = Position(
    PolarProjection(
        LogScale('.x', domain=(-1, 3), range=(0, 1)),
        LinearScale('.y', domain=(0, 2 * np.pi), range=(0, 2 * np.pi))))

points = PointCollection("agg", transform=transform)

n = 10000
R = np.random.uniform(0, 1000, n)
T = np.random.uniform(0, 2 * np.pi, n)
Z = np.zeros(n)

points.append(np.dstack((R, T, Z)).reshape(n, 3))

window.attach(points["transform"])
window.attach(points["viewport"])
app.run()
Example #29
0
    window.clear()
    quads.draw(gl.GL_TRIANGLES, indices)


@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glEnable(gl.GL_BLEND)


quads = gloo.Program(vertex, fragment, count=12)
quads["position"] = [(-1, -1, -1), (-1, +1, -1), (+1, -1, -1), (+1, +1, -1),
                     (-1, -1, 0), (-1, +1, 0), (+1, -1, 0), (+1, +1, 0),
                     (-1, -1, +1), (-1, +1, +1), (+1, -1, +1), (+1, +1, +1)]
quads["position"] *= 10

quads["color"] = C1, C1, C1, C1, C2, C2, C2, C2, C3, C3, C3, C3
indices = np.zeros((3, 6), dtype=np.uint32)
indices[0] = 0 + np.array([0, 1, 2, 1, 2, 3])
indices[1] = 4 + np.array([0, 1, 2, 1, 2, 3])
indices[2] = 8 + np.array([0, 1, 2, 1, 2, 3])
indices = indices.view(gloo.IndexBuffer)

trackball = Trackball(Position("position"), znear=0.1, zfar=500, distance=50)
quads['transform'] = trackball
trackball.theta = 40
trackball.phi = 45
trackball.zoom = 40
window.attach(quads['transform'])
app.run()
Example #30
0
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
from glumpy import app, gl, gloo, glm, data
from glumpy.graphics.text import FontManager
from glumpy.graphics.collections import GlyphCollection
from glumpy.transforms import Position, OrthographicProjection

window = app.Window(width=512, height=512)

@window.event
def on_draw(dt):
    window.clear()
    label.draw()

x,y,z = 256,256,0
font = FontManager.get("OpenSans-Regular.ttf", 64, mode='agg')
label = GlyphCollection('agg', transform=OrthographicProjection(Position()))
label.append("Hello World !", font,
                   anchor_x = 'center', anchor_y = 'center',
                   origin=(x,y,z), color=(1,1,1,1))

window.attach(label["transform"])

app.run()