def main(): vertex = """ attribute vec2 position; void main (void) { gl_Position = vec4(position, 0.0, 1.0); } """ fragment = open('/tmp/tt.fs').read() app.use('glfw') window = app.Window(width=640, height=480) @window.event def on_draw(dt): quad['time'] += dt * .5 window.clear() quad.draw(gl.GL_TRIANGLE_STRIP) title = 'FPS:%f' % (clock.get_fps()) window.set_title(title) quad = gloo.Program(vertex, fragment, count=4) quad['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)] quad['resolution'] = [window.width, window.height] quad['time'] = 0 app.run()
def make_window(image_fn, size, title=None, cleanup=True): """Return a glumpy app.Window with standard settings""" app.use('glfw') config = app.configuration.Configuration() config.major_version = 3 config.minor_version = 2 config.profile = "core" window = app.Window(int(size[0]), int(size[1]), title or '', config=config, vsync=True) @window.event def on_draw(dt): window.set_title('fps: {}'.format(window.fps).encode('ascii')) image_fn() if cleanup: @window.event def on_close(): for stream in streams: stream.stop_stream() stream.close() audio.terminate() for shell in shells: shell.ex('exit()') sys.exit(0) return window
def __init__(self, init_f, per_frame_f, width=512, height=512): """ constructor for the GLWindow object :param init_f: function to initialize window with, should return a float tensor in format: [batch_size, channels, height, width] with values between -1 and 1 :param per_frame_f: function run per frame to update window, takes current frame as argument and should return then next frame as a float tensor in format: [batch_size, channels, height, width] :param width: Width of the window in pixels :param height: Height of the window in pixels """ # create window with OpenGL context self.init_f = init_f self.per_frame_f = per_frame_f app.use('glfw') window = app.Window(width, height, fullscreen=False) self.window = window self.setup() @window.event def on_draw(dt): global state self.window.set_title(str(self.window.fps).encode("ascii")) tex = screen['tex'] h, w = tex.shape[:2] # mutate state in torch img = self.per_frame_f( state).detach() # prevent autograd from filling memory # convert into proper format tensor = img.squeeze().transpose(0, 2) tensor = tensor.transpose(0, 1).data # put in texture order tensor = torch.cat((tensor, tensor[:, :, 0].unsqueeze(2)), 2) # add the alpha channel tensor[:, :, 3] = 1 # set alpha # check that tensor order matches texture: tensor = (255 * tensor).byte().contiguous() # convert to ByteTensor # copy from torch into buffer assert tex.nbytes == tensor.numel() * tensor.element_size() with self.cuda_activate(cuda_buffer) as ary: cpy = pycuda.driver.Memcpy2D() cpy.set_src_device(tensor.data_ptr()) cpy.set_dst_array(ary) cpy.width_in_bytes = cpy.src_pitch = cpy.dst_pitch = tex.nbytes // h cpy.height = h cpy(aligned=False) torch.cuda.synchronize() # draw to screen self.window.clear() screen.draw(gl.GL_TRIANGLE_STRIP)
def run(self): app.use('glfw') self.window = app.Window(height=self.h, width=self.w, fullscreen=False) self.window.push_handlers(on_draw=self.on_draw) self.window.push_handlers(on_close=self.on_close) import pycuda.gl.autoinit import pycuda.gl tex, cuda_buffer = create_shared_texture(self.w, self.h, 4) self.tex = tex self.cuda_buffer = cuda_buffer self.screen_program = get_screen_program(tex) app.run(framerate=self.max_framerate)
def run(self): app.use('glfw') self.window = app.Window(height=self.h, width=self.w, fullscreen=False) self.window.push_handlers(on_draw=self.on_draw) self.window.push_handlers(on_close=self.on_close) self.state2 = torch.ones((self.h, self.w, 4), dtype=torch.uint8, device=torch.device('cuda:0')) * 128 self.state2[:, :, 1] = 255 import pycuda.gl.autoinit import pycuda.gl tex, cuda_buffer = create_shared_texture(self.w, self.h, 4) self.tex = tex self.cuda_buffer = cuda_buffer self.screen_program = get_screen_program(tex) app.run(framerate=self.max_framerate)
def run(self): app.use("qt5") self.window = app.Window(width=self.width, height=self.height) #self.window = app.Window() self.window.attach(self) #app.clock.set_fps_limit(20) clock = app.__init__(backend=app.__backend__) if False: with record(self.window, "cube.mp4", fps=20): app.run(framerate=20) else: while True: #dt = clock.tick() #self.program1['time'] = dt*5 time.sleep(0.01) app.__backend__.process(0.05) if self.finish: return
v_color = u_color * color; gl_Position = <transform>; } """ fragment = """ varying vec4 v_color; void main() { gl_FragColor = v_color; } """ 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
#! /usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Nicolas P. Rougier # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- from glumpy import app app.use("osxglut") window = app.Window() @window.event def on_draw(dt): window.clear() app.run()
{ v_color = u_color * color; gl_Position = <transform>; } """ fragment = """ varying vec4 v_color; void main() { gl_FragColor = v_color; } """ app.use("glfw_imgui") 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
screen = screens[ i ] window{i}.set_position( screen.x - 1, screen.y - 1 ) window{i}.model = models[ path.split( '/' )[ -1 ].split( '.' )[ 0 ] ] window{i}.camera = cameras[ cam ] window{i}.quad = quad @window{i}.event def on_init( ): window{i}.quad[ 'position' ] = [ ( -1, -1 ), ( -1, 1 ), ( 1, -1 ), ( 1, 1 ) ] window{i}.quad[ 'texcoord' ] = [ ( 0, 1 ), ( 0, 0 ), ( 1, 1 ), ( 1, 0 ) ] window{i}.camera.subscribe( ) window{i}.camera.start( ) @window{i}.event def on_draw( dt ): _, capture = window{i}.camera.read( ) window{i}.quad[ 'texture' ] = window{i}.model( capture, ( window{i}.width, window{i}.height ) ) window{i}.clear( ) window{i}.quad.draw( gl.GL_TRIANGLE_STRIP ) @window{i}.event def on_exit( ): window{i}.camera.unsubscribe( ) ''' exec( code.format( i ) ) app.use( 'pyglet' ) app.run( framerate = 30 )
out vec4 v_color; void main() { gl_Position = vec4(scale*position, 0.0, 1.0); v_color = color; } """ fragment = """ in vec4 v_color; out vec4 FragColor; void main() { FragColor = v_color; } """ app.use('glfw', api='GL', major=3, minor=3, profile='core') # Create a window with a valid GL context window = app.Window() # Build the program and corresponding buffers (with 4 vertices) quad = gloo.Program(vertex, fragment, count=4, version="330") dtype = [('color', np.float32, 4), ('position', np.float32, 2)] quad_arrays_0 = np.zeros(4, dtype).view(gloo.VertexArray) # Four colors quad_arrays_0['color'] = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1)] quad_arrays_0['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)] quad_arrays_1 = np.zeros(4, dtype).view(gloo.VertexArray) # All red data
# ----------------------------------------------------------------------------- # Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- from glumpy import app app.use("osxglut") window = app.Window() @window.event def on_draw(dt): window.clear() app.run()
out vec4 v_color; void main() { gl_Position = vec4(scale*position, 0.0, 1.0); v_color = color; } """ fragment = """ in vec4 v_color; out vec4 FragColor; void main() { FragColor = v_color; } """ app.use('glfw', api='GL', major=3, minor=3, profile='core') # Create a window with a valid GL context window = app.Window() # Build the program and corresponding buffers (with 4 vertices) quad = gloo.Program(vertex, fragment, count=4, version="330") dtype = [('color', np.float32, 4), ('position', np.float32, 2)] quad_arrays_0 = np.zeros(4, dtype).view(gloo.VertexArray) # Four colors quad_arrays_0['color'] = [ (1,0,0,1), (0,1,0,1), (0,0,1,1), (1,1,0,1) ] quad_arrays_0['position'] = [ (-1,-1), (-1,+1), (+1,-1), (+1,+1) ] quad_arrays_1 = np.zeros(4, dtype).view(gloo.VertexArray) # All red data
# Author: Tomas Hodan ([email protected]) # Center for Machine Perception, Czech Technical University in Prague # Renders rgb/depth image of a 3D mesh model. import numpy as np from glumpy import app, gloo, gl # Set backend (http://glumpy.readthedocs.io/en/latest/api/app-backends.html) app.use('glfw') # app.use('qt5') # app.use('pyside') # Set logging level from glumpy.log import log import logging log.setLevel(logging.WARNING) # ERROR, WARNING, DEBUG, INFO # Color vertex shader #------------------------------------------------------------------------------- _color_vertex_code = """ uniform mat4 u_mv; uniform mat4 u_nm; uniform mat4 u_mvp; uniform vec3 u_light_eye_pos; attribute vec3 a_position; attribute vec3 a_normal; attribute vec3 a_color; attribute vec2 a_texcoord;
def torch_process(state): """Random convolutions.""" fs = 11 filters, sgns = (Variable(init(torch.cuda.FloatTensor(3, 3, fs, fs)), volatile=True) for init in (lambda x: x.normal_(), lambda x: x.bernoulli_(0.52))) filters = F.softmax(filters) * (sgns * 2 - 1) state = F.conv2d(state, filters, padding=fs // 2) state = state - state.mean().expand(state.size()) state = state / state.std().expand(state.size()) return state # create window with OpenGL context app.use('glfw') window = app.Window(512, 512, fullscreen=False) @window.event def on_draw(dt): global state window.set_title(str(window.fps).encode("ascii")) tex = screen['tex'] h, w = tex.shape[:2] # mutate state in torch state = torch_process( state).detach() # prevent autograd from filling memory img = F.tanh(state).abs() # convert into proper format tensor = img.squeeze().transpose(0, 2).t().data # put in texture order
from glumpy import app, gloo, gl app.use("qt5") vertex = """ attribute vec2 position; void main(){ gl_Position = vec4(position, 0.0, 1.0); } """ fragment = """ void main() { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); } """ window = app.Window() quad = gloo.Program(vertex, fragment, count=4) quad['position'] = (-1, +1), (+1, +1), (-1, -1), (+1, -1) @window.event def on_draw(dt): window.clear() quad.draw(gl.GL_TRIANGLE_STRIP) app.run()
from glumpy import app from glumpy.app.window import key import numpy as np import pygame from entity import Camera from constants import WINDOW_WIDTH, WINDOW_HEIGHT # pygame.init() app.use('sdl') window = app.Window(WINDOW_WIDTH, WINDOW_HEIGHT) camera = Camera(position=np.array([0.0, 0.0, 0.0])) @window.event def on_draw(dt): window.clear() camera.update(dt) @window.event def on_key_press(symbol, modifiers): if symbol == key.ESCAPE: window.close() exit() if symbol == key.W: camera.move_forward = True elif symbol == key.A: camera.move_left = True
# Author: Tomas Hodan ([email protected]) # Center for Machine Perception, Czech Technical University in Prague # Renders rgb/depth image of a 3D mesh model. import numpy as np from glumpy import app, gloo, gl # Set backend (http://glumpy.readthedocs.io/en/latest/api/app-backends.html) # app.use('glfw') app.use('qt5') # app.use('pyside') # Set logging level from glumpy.log import log import logging log.setLevel(logging.ERROR) # ERROR, WARNING, DEBUG, INFO # Color vertex shader #------------------------------------------------------------------------------- _color_vertex_code = """ uniform mat4 u_mv; uniform mat4 u_nm; uniform mat4 u_mvp; uniform vec3 u_light_eye_pos; attribute vec3 a_position; attribute vec3 a_normal; attribute vec3 a_color; attribute vec2 a_texcoord;
def get_device(): return "cuda:0" if is_available() else "cpu" if get_device().startswith("cuda"): # This optimizes performance in cuda mode print("CUDA enabled, using GPU!") from torch.backends import cudnn # QA if cudnn.is_available(): cudnn.enabled = True cudnn.benchmark = True # create window with OpenGL context app.use("pyglet") window = app.Window(512, 512, fullscreen=False, decoration=True) WindowManager.bind_window(window) # Instantiate generator # generator = simple_gan_setup(model_type=model_type) # generator = no_gan_setup() generator = complex_gan_setup(model_type=model_type) # visualize_graph(generator) generator.to_device(get_device()) @window.event def on_draw(dt):
def render(interactive=False): """ The main thread rendering funciton for this application This takes care of the rendering, handling of window event - Console (information) update - Redrawing of the cubes representing the finger joints location - Resizing funcitons for all cubes (including debugging cube) - Handling of low-level OpenGL initialization / rendering - Key board event for some interesting interaction - Opening up the interactive python interpreter to give advanced user full control over the driver :param interactive: Whether the program should give user an interactive python interpreter after the OpenGL window is loaded up """ log.info(f"Runnning glfw renderer") app.use("glfw") # setting OpenGL backend, you'll need glfw installed config = app.configuration.Configuration() config.samples = 16 # super sampling anti-aliasing console = app.Console(rows=32, cols=80, scale=3, color=(0.1, 0.1, 0.1, 1)) # easy to use info displayer global window # to be used to close the window, declared as global var for interpreter to reference window = app.Window(width=console.cols * console.cwidth * console.scale, height=console.rows * console.cheight * console.scale, color=(1, 1, 1, 1), config=config) @window.timer(1 / 30.0) def timer(dt): # used every 1/30 second to update frame rate and stuff... console.clear() console.write( "-------------------------------------------------------") console.write(" Glumpy version %s" % (__version__)) console.write(" Window size: %dx%d" % (window.width, window.height)) console.write(" Console size: %dx%d" % (console._rows, console._cols)) console.write(" Backend: %s (%s)" % (window._backend.__name__, window._backend.__version__)) console.write(" Actual FPS: %.2f frames/second" % (window.fps)) console.write(" Arduino FPS: %.2f frames/second" % (arduino_fps)) console.write(" Hit 'V' key to toggle bone view") console.write(" Hit 'P' key to pause or unpause") console.write( "-------------------------------------------------------") for line in repr(window.config).split("\n"): console.write(" " + line) console.write( "-------------------------------------------------------") @window.timer(1 / 30.0) def rotate(dt): # used every 1/30 to update the model matrix of all cubes, to check whether the program is frozen # Rotate cube for hand in hand_pool: model = hand.key_point.model glm.rotate(model, 1, 0, 0, 1) glm.rotate(model, 1, 0, 1, 0) hand.key_point.model = model model = hand.bone.model glm.rotate(model, 1, 0, 1, 0) hand.bone.model = model @window.event def on_draw(dt): # on every window refresh, redraw the OpenGL program on the screen window.clear() console.draw() parser[1].debug_cube.draw() for hand in hand_pool: hand.draw() @window.event def on_resize(width, height): # when the user resizes the window, update the OpenGL program parser[1].debug_cube.resize(width, height) for hand in hand_pool: hand.resize(width, height) @window.event def on_init(): # init the OpenGL parameters gl.glEnable(gl.GL_DEPTH_TEST) # enable depth buffer gl.glEnable(gl.GL_LINE_SMOOTH) # enable line antialiasing gl.glPolygonOffset(1, 1) # resize line polygon @window.event def on_close(): # when the user press `ESC` or closed the window # kill all other threads kill() log.info("The user closed the renderer window") @window.event def on_character(text): # process keyboard information # like changing the display style # or changing pause the update of Hand object global update_hand_obj 'A character has been typed' if text == "v": for hand in hand_pool: hand.show_type += 1 hand.show_type %= 3 elif text == 'p': update_hand_obj = not update_hand_obj # TODO: Update keyboard mapping here for WSAD window.attach(console) if interactive: log.info(f"Running in interactive mode, run Python here freely") log.info( f"Use 'app.__backend__.windows()[0].close()' to close the window") log.info(f"Use Ctrl+D to quit the Python Interactive Shell") app.run(framerate=60, interactive=interactive) log.info(f"The render function returned")
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) import numpy as np import math import logging from glumpy import app, gl, glm, gloo, data, key from glumpy.ext import glfw from pyvisual.rendering import generative, stage, transform, video, var, util from pyvisual.rendering.var import _V from pyvisual.audio import analyzer from pyvisual import visualapp, event logging.basicConfig(level=logging.DEBUG) app.use("glfw") window = app.Window() audio = analyzer.AudioAnalyzer() beat_on = audio.beat_on beat_status = audio.beat_status vu = audio.vu time = var.RelativeTime() vu_norm = audio.vu_norm keys = event.Keys(window) key_space = keys[key.SPACE] key_right = keys[key.RIGHT] change = event.EveryOnEvent(beat_on, every_n=16)
import vispy.scene.visuals as visuals from vispy import app import numpy as np import pandas as pd # ----------------------------------------------------------------------------- # Glumpy / Qt5 integration example (c) LeMinaw, 2020 # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- import numpy as np from glumpy import app as glumpy_app from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QPushButton, QTextEdit glumpy_app.use("qt5") glumpy_window = glumpy_app.Window() qwindow = QMainWindow() widget = QWidget() button = QPushButton("Press me!") text = QTextEdit() qwindow.setCentralWidget(widget) widget.setLayout(QVBoxLayout()) widget.layout().addWidget(text) widget.layout().addWidget(button) c = Canvas(tile_provider=Mapnik()) c.show() df = pd.read_csv("../data/business-locations-us.txt", sep="\t")