def on_draw(dt): global phi, theta, duration window.clear() # Filled cube gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) cube['u_color'] = 1, 1, 1, 1 cube.draw(gl.GL_TRIANGLES, I) # Outlined cube gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) cube['u_color'] = 0, 0, 0, 1 cube.draw(gl.GL_LINES, O) gl.glDepthMask(gl.GL_TRUE) # Rotate cube theta += 0.5 # degrees phi += 0.5 # degrees view = cube['u_view'].reshape(4,4) model = np.eye(4, dtype=np.float32) glm.rotate(model, theta, 0, 0, 1) glm.rotate(model, phi, 0, 1, 0) cube['u_model'] = model cube['u_normal'] = np.array(np.matrix(np.dot(view, model)).I.T)
def ApplyImpulse(dest, position, value): prog_splat["FillColor"] = value,value,value dest.activate() gl.glEnable(gl.GL_BLEND) prog_splat.draw(gl.GL_TRIANGLE_STRIP) dest.deactivate() gl.glDisable(gl.GL_BLEND)
def __exit__(self, type, value, traceback): # Done with "original" rendering self._framebuffers[0].deactivate() # Actual filtering starts here gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glDisable(gl.GL_DEPTH_TEST) # Apply all filters using ping-pong framebuffers index = 0 for i in range(len(self._programs)-1): program = self._programs[i] if i == 0: # special case for first rendering program['filtered'] = self._framebuffers[0].color[0] else: program['filtered'] = self._framebuffers[1+index].color[0] index = (index + 1) % 2 # ping-pong self._framebuffers[index+1].activate() self._programs[i].draw(gl.GL_TRIANGLE_STRIP) self._framebuffers[index+1].deactivate() # Final rendering (no transformation) at original viewport size program = self._programs[-1] program['filtered'] = self._framebuffers[index+1].color[0] gl.glViewport( *self._viewport ) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glDisable(gl.GL_DEPTH_TEST) program.draw(gl.GL_TRIANGLE_STRIP)
def on_draw(dt): global phi, theta, time time += dt window.clear() surface['data'] gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) surface["color"] = 1,1,1,1 surface.draw(gl.GL_TRIANGLES, s_indices) gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) surface["color"] = 0,0,0,1 surface.draw(gl.GL_LINE_LOOP, b_indices) gl.glDepthMask(gl.GL_TRUE) model = surface['transform']['model'].reshape(4,4) view = surface['transform']['view'].reshape(4,4) surface['view'] = view surface['model'] = model surface['normal'] = np.array(np.matrix(np.dot(view, model)).I.T)
def on_draw(dt): # Clear depth and color buffers gl.glClearColor(*C0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # Opaque objects rendering gl.glDepthMask(gl.GL_TRUE) gl.glDisable(gl.GL_BLEND) # Transparent objects rendering gl.glDepthMask(gl.GL_FALSE) gl.glEnable(gl.GL_BLEND) framebuffer.activate() gl.glClearColor(0,0,0,1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) window.clear(color=(0,0,0,1)) gl.glBlendFuncSeparate(gl.GL_ONE, gl.GL_ONE, gl.GL_ZERO, gl.GL_ONE_MINUS_SRC_ALPHA) scene.draw(gl.GL_TRIANGLES, indices) framebuffer.deactivate() # Compositing gl.glBlendFunc(gl.GL_ONE_MINUS_SRC_ALPHA, gl.GL_SRC_ALPHA) compose.draw(gl.GL_TRIANGLE_STRIP)
def on_draw(dt): global phi, theta window.clear() # Filled cube gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) cube['u_color'] = 1, 1, 1, 1 cube.draw(gl.GL_TRIANGLES, faces) # Outlined cube gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) cube['u_color'] = 0, 0, 0, 1 cube.draw(gl.GL_LINES, outline) gl.glDepthMask(gl.GL_TRUE) # Make cube rotate theta += 0.5 # degrees 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) cube['model'] = model
def on_draw(dt): window.clear() gl.glEnable(gl.GL_DEPTH_TEST) earth.draw(gl.GL_TRIANGLES, indices) paths.draw() gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_BLEND) markers.draw() labels.draw()
def on_draw(dt): global phi, theta, duration window.clear() gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) cube.draw(gl.GL_TRIANGLES, indices) # Rotate cube theta += 0.5 # degrees 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) cube['u_model'] = model
def on_draw(dt): window.clear() # Cells gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) cells.draw() # Cell outlines gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) outlines.draw() gl.glDepthMask(gl.GL_TRUE)
def on_draw(dt): gl.glEnable(gl.GL_DEPTH_TEST) framebuffer.activate() window.clear() program.draw(gl.GL_POINTS) if mouse is not None: gl.glReadBuffer(gl.GL_COLOR_ATTACHMENT1, gl.GL_FRONT) r,g,b,a = gl.glReadPixels(mouse[0],mouse[1],1,1, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE) index = ord(b) + 256*ord(g) + 256*256*ord(r) if index < len(program): program["bg_color"][index] = 0,0,0,1 framebuffer.deactivate() gl.glDisable(gl.GL_DEPTH_TEST) quad.draw(gl.GL_TRIANGLE_STRIP)
def draw_depth(shape, vertex_buffer, index_buffer, mat_model, mat_view, mat_proj): assert type(mat_view) is list, 'Requires list of arrays.' program = gloo.Program(_depth_vertex_code, _depth_fragment_code) program.bind(vertex_buffer) # Frame buffer object color_buf = np.zeros((shape[0], shape[1], 4), np.float32).view(gloo.TextureFloat2D) depth_buf = np.zeros((shape[0], shape[1]), np.float32).view(gloo.DepthTexture) fbo = gloo.FrameBuffer(color=color_buf, depth=depth_buf) fbo.activate() # OpenGL setup gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(0.0, 0.0, 0.0, 0.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, shape[1], shape[0]) for i in range(len(mat_view)): program['u_mv'] = _compute_model_view(mat_model, mat_view[i]) program['u_mvp'] = _compute_model_view_proj(mat_model, mat_view[i], mat_proj) # Keep the back-face culling disabled because of objects which do not have # well-defined surface (e.g. the lamp from the dataset of Hinterstoisser) gl.glDisable(gl.GL_CULL_FACE) # gl.glEnable(gl.GL_CULL_FACE) # gl.glCullFace(gl.GL_BACK) # Back-facing polygons will be culled # Rendering program.draw(gl.GL_TRIANGLES, index_buffer) # Retrieve the contents of the FBO texture depth = np.zeros((shape[0], shape[1], 4), dtype=np.float32) gl.glReadPixels(0, 0, shape[1], shape[0], gl.GL_RGBA, gl.GL_FLOAT, depth) depth.shape = shape[0], shape[1], 4 depth = depth[::-1, :] depth = depth[:, :, 0] # Depth is saved in the first channel fbo.deactivate() return depth
def on_draw(dt): self.window.clear() gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) self.render_kernel.draw(gl.GL_TRIANGLES) gl.glReadPixels(0, 0, self.width, self.height, gl.GL_RGBA, gl.GL_FLOAT, self.rgb_buffer) gl.glReadPixels( 0, 0, self.width, self.height, gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, self.depth_buffer, )
def draw(self, projection, view, width, height): model_matrix = self._transform.matrix # Set uniforms self._program["u_projection"] = projection # Note: OpenGL matrix multiplication works on column-major oriented storage (as least for pre-multiplication). # Also glumpy.glm is using column-major assumption for its operations. view_model_matrix = np.transpose( np.matmul(np.transpose(view), np.transpose(model_matrix))) self._program["u_view_model_matrix"] = view_model_matrix # self._program["u_view"] = view # self._program["u_model"] = self._model view_model_normal_matrix = np.transpose( np.linalg.inv(view_model_matrix)) self._program["u_view_model_normal_matrix"] = view_model_normal_matrix self._program["u_color_scale"] = self._color_scale self._program["u_normal_scale"] = self._normal_scale self._program["u_depth_scale"] = self._depth_scale if self._shader_type == self.PHONG: self._program["u_light_position"] = self._light_position self._program[ "u_light_ambient_intensity"] = 0.4 * self._light_intensity self._program[ "u_light_diffuse_intensity"] = 0.4 * self._light_intensity self._program[ "u_light_specular_intensity"] = 0.2 * self._light_intensity self._program["u_material_ambient"] = self._material self._program["u_material_diffuse"] = self._material self._program["u_material_specular"] = self._material self._program["u_material_shininess"] = 32 with self._program.activate(): # Bind index buffer and draw if self.use_depth_test: gl.glEnable(gl.GL_DEPTH_TEST) else: gl.glDisable(gl.GL_DEPTH_TEST) if self.use_face_culling: gl.glFrontFace(gl.GL_CCW) gl.glCullFace(gl.GL_BACK) gl.glEnable(gl.GL_CULL_FACE) else: gl.glDisable(gl.GL_CULL_FACE) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self._gl_index_buffer) gl.glDrawElements(gl.GL_TRIANGLES, 3 * len(self._faces), opengl_utils.get_gl_type(self._faces), None) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0)
def on_draw(dt): gl.glViewport(0, 0, GridWidth, GridHeight) gl.glDisable(gl.GL_BLEND) Advect(Velocity.Ping, Velocity.Ping, Obstacles, Velocity.Pong, VelocityDissipation) Velocity.swap() Advect(Velocity.Ping, Temperature.Ping, Obstacles, Temperature.Pong, TemperatureDissipation) Temperature.swap() Advect(Velocity.Ping, Density.Ping, Obstacles, Density.Pong, DensityDissipation) Density.swap() ApplyBuoyancy(Velocity.Ping, Temperature.Ping, Density.Ping, Velocity.Pong) Velocity.swap() ApplyImpulse(Temperature.Ping, ImpulsePosition, ImpulseTemperature) ApplyImpulse(Density.Ping, ImpulsePosition, ImpulseDensity) ComputeDivergence(Velocity.Ping, Obstacles, Divergence) ClearSurface(Pressure.Ping, 0.0) for i in range(NumJacobiIterations): Jacobi(Pressure.Ping, Divergence, Obstacles, Pressure.Pong) Pressure.swap() SubtractGradient(Velocity.Ping, Pressure.Ping, Obstacles, Velocity.Pong) Velocity.swap() gl.glViewport(0, 0, window.width, window.height) gl.glClearColor(0, 0, 0, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) prog_visualize['u_data'] = Density.Ping.texture prog_visualize['u_shape'] = Density.Ping.texture.shape[ 1], Density.Ping.texture.shape[0] prog_visualize['u_kernel'] = data.get("spatial-filters.npy") prog_visualize["Sampler"] = Density.Ping.texture prog_visualize["FillColor"] = 0.95, 0.925, 1.00 prog_visualize["Scale"] = 1.0 / window.width, 1.0 / window.height prog_visualize.draw(gl.GL_TRIANGLE_STRIP)
def on_draw(dt): window.clear() # Filled cube gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) cube['u_color'] = 1, 1, 1, 1 cube.draw(gl.GL_TRIANGLES, faces) # Outlined cube gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) cube['u_color'] = 0, 0, 0, 1 cube.draw(gl.GL_LINES, outline) gl.glDepthMask(gl.GL_TRUE)
def on_draw(dt): global pingpong pingpong = 1 - pingpong compute["pingpong"] = pingpong render["pingpong"] = pingpong gl.glDisable(gl.GL_BLEND) framebuffer.activate() gl.glViewport(0, 0, cwidth, cheight) compute.draw(gl.GL_TRIANGLE_STRIP) framebuffer.deactivate() gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glViewport(0, 0, window.width, window.height) render.draw(gl.GL_TRIANGLE_STRIP)
def draw(self, **kwargs): """Render to self.target. Keyword args bound to shader.""" with self.target: for k, v in kwargs.items(): # if isinstance(v, Layer): # v = v.state[0] self.program[k] = v for i, state in enumerate(self.target.history): for j, buf in enumerate(state): u = 'history_t{}_b{}'.format(i, j) try: self.program[u] = buf except IndexError as e: pass gl.glDisable(gl.GL_BLEND) self.program.draw(self.draw_method) return self.state
def draw_label(shape, vertex_buffer, index_buffer, texture, mat_model, mat_view, mat_proj, ambient_weight, bg_color, shading, inst_ids): assert type(mat_view) is list, 'Requires list of arrays.' program = gloo.Program(_label_vertex_code, _label_fragment_code) program.bind(vertex_buffer) # FBO color_buf = np.zeros((shape[0], shape[1], 4), np.float32).view(gloo.TextureFloat2D) depth_buf = np.zeros((shape[0], shape[1]), np.float32).view(gloo.DepthTexture) fbo = gloo.FrameBuffer(color=color_buf, depth=depth_buf) fbo.activate() # OpenGL setup gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(bg_color[0], bg_color[1], bg_color[2], bg_color[3]) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, shape[1], shape[0]) print('inst ids = ' + str(inst_ids)) for i in range(len(mat_view)): program['u_mvp'] = _compute_model_view_proj(mat_model, mat_view[i], mat_proj) program['inst_id'] = inst_ids[ i] / 255. # input instance-id is mapped to range [0,1] gl.glDisable(gl.GL_CULL_FACE) program.draw(gl.GL_TRIANGLES, index_buffer) label = np.zeros((shape[0], shape[1], 4), dtype=np.float32) gl.glReadPixels(0, 0, shape[1], shape[0], gl.GL_RGBA, gl.GL_FLOAT, label) label.shape = shape[0], shape[1], 4 label = label[::-1, :] label = np.round(label[:, :, 0] * 255).astype( np.uint8) # Label is saved in the first channel fbo.deactivate() return label
def __init__(self, model, im_size, texture=None, bg_color=(0.0, 0.0, 0.0, 0.0), ambient_weight=0.5, shading='flat', mode='rgb+depth'): # Set texture / color of vertices texture_uv = np.zeros((model['pts'].shape[0], 2), np.float32) colors = np.ones((model['pts'].shape[0], 3), np.float32) * 0.5 # Set the vertex data vertices_type = [('a_position', np.float32, 3), ('a_normal', np.float32, 3), ('a_color', np.float32, colors.shape[1]), ('a_texcoord', np.float32, 2)] vertices = np.array( list(zip(model['pts'], model['normals'], colors, texture_uv)), vertices_type) # Create buffers self.vertex_buffer = vertices.view(gloo.VertexBuffer) self.index_buffer = model['faces'].flatten().astype(np.uint32).view( gloo.IndexBuffer) self.window = app.Window(visible=False) self.program = gloo.Program(_normal_vertex_code, _normal_fragment_code) self.program.bind(self.vertex_buffer) scale = max(im_size) shape = (scale, scale) color_buf = np.zeros((shape[0], shape[1], 4), np.float32).view(gloo.TextureFloat2D) depth_buf = np.zeros((shape[0], shape[1]), np.float32).view(gloo.DepthTexture) fbo = gloo.FrameBuffer(color=color_buf, depth=depth_buf) fbo.activate() gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(bg_color[0], bg_color[1], bg_color[2], bg_color[3]) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, shape[1], shape[0]) gl.glDisable(gl.GL_CULL_FACE)
def on_draw(dt): global phi, theta, duration window.clear() gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_LINE_SMOOTH) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) #cube["u_color"] = 1,1,1,1 cube.draw(gl.GL_TRIANGLES, indices) #rotate cube #theta += 0.5 # deg #phi += 0.5 # deg model = np.eye(4, dtype=np.float32) #glm.rotate(model, theta, 1,0,0) #glm.rotate(model, phi, 0,1,0) cube['u_model'] = model
def on_draw(dt): gl.glViewport(0, 0, GridWidth, GridHeight) gl.glDisable(gl.GL_BLEND) Advect(Velocity.Ping, Velocity.Ping, Obstacles, Velocity.Pong, VelocityDissipation) Velocity.swap() Advect(Velocity.Ping, Temperature.Ping, Obstacles, Temperature.Pong, TemperatureDissipation) Temperature.swap() Advect(Velocity.Ping, Density.Ping, Obstacles, Density.Pong, DensityDissipation) Density.swap() ApplyBuoyancy(Velocity.Ping, Temperature.Ping, Density.Ping, Velocity.Pong) Velocity.swap() ApplyImpulse(Temperature.Ping, ImpulsePosition, ImpulseTemperature) ApplyImpulse(Density.Ping, ImpulsePosition, ImpulseDensity) ComputeDivergence(Velocity.Ping, Obstacles, Divergence) ClearSurface(Pressure.Ping, 0.0) for i in range(NumJacobiIterations): Jacobi(Pressure.Ping, Divergence, Obstacles, Pressure.Pong) Pressure.swap() SubtractGradient(Velocity.Ping, Pressure.Ping, Obstacles, Velocity.Pong) Velocity.swap() gl.glViewport(0,0,window.width,window.height) gl.glClearColor(0, 0, 0, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) prog_visualize['u_data'] = Density.Ping.texture prog_visualize['u_shape'] = Density.Ping.texture.shape[1], Density.Ping.texture.shape[0] prog_visualize['u_kernel'] = data.get("spatial-filters.npy") prog_visualize["Sampler"] = Density.Ping.texture prog_visualize["FillColor"] = 0.95, 0.925, 1.00 prog_visualize["Scale"] = 1.0/window.width, 1.0/window.height prog_visualize.draw(gl.GL_TRIANGLE_STRIP)
def initializeGL(self): gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_BLEND) # gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glFrontFace(gl.GL_CCW) gl.glClearColor(*self._clear_color) gl.glDisable(gl.GL_CULL_FACE) self._init_camera() self._init_default_shader() if self.cc: self.cc.active_material_changed.connect( self._active_material_changed) # Start an update timer to refresh rendering self._timer = QTimer() self._timer.setInterval(int(1000 / self._frame_rate)) self._timer.timeout.connect(self.update) self._timer.start() self.init_done.emit()
def _draw_circles(self, centers): gl.glEnable(gl.GL_BLEND) gl.glEnable(gl.GL_LINE_SMOOTH) gl.glDisable(gl.GL_DEPTH_TEST) gl.glLineWidth(3) for i in range(len(centers)): center = centers[i] radius = self.__harmonics[i].radius model = np.eye(4, dtype=np.float32) glm.scale(model, radius / 2, radius / 2, 1) glm.translate(model, center[0] / 2, center[1] / 2, 0) self.__circles_program[self.u_model] = model self.__circles_program[self.u_color] = self.__circle_color self.__circles_program.draw(gl.GL_TRIANGLE_FAN, self.__circle_i) self.__circles_program[self.u_color] = self.__ocircle_color self.__circles_program.draw(gl.GL_LINE_LOOP, self.__ocircle_i)
def on_draw(dt): window.clear() demo_idx = 0 for program_object in self.programs: program = program_object.program model = matrix_model(np.copy(program_object.u_model)) #self.deg_x += dt*20 #self.deg_y += dt*40 self.demo_dt += dt/5 demo_idx += 1 ''' if self.demo_dt > 2: if demo_idx == 1: if self.demo_dt > 2.4: if program['alpha'] <= 0.1: continue else: program['alpha'] -= 0.01 elif demo_idx == 2: if self.demo_dt > 2.8: program['alpha'] += 0.01 ''' program['u_model'] = np.dot(model, self.u_model) program['u_view'] = self.u_view program['u_projection'] = self.u_projection if program_object.draw_mode == gl.GL_TRIANGLES: program.draw(program_object.draw_mode, program_object.face) elif program_object.draw_mode == gl.GL_LINES and program_object.name == 'ProgramSFM3DRegion': gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) program.draw(program_object.draw_mode, program_object.O) gl.glDepthMask(gl.GL_TRUE) else: program.draw(program_object.draw_mode)
def on_draw(dt): # GUI imguiRenderer.process_inputs() imgui.new_frame() if imgui.begin_main_menu_bar(): if imgui.begin_menu("File", True): clicked, selected = imgui.menu_item("Quit", 'ESC', False, True) if clicked: exit(0) imgui.end_menu() imgui.end_main_menu_bar() imgui.begin('Cube') changed, zoom = imgui.slider_float('zoom', trackball.zoom, 15, 90) if changed: trackball.zoom = zoom imgui.end() imgui.end_frame() imgui.render() window.clear() # Filled cube gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) cube['u_color'] = 1, 1, 1, 1 cube.draw(gl.GL_TRIANGLES, faces) # Outlined cube gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) cube['u_color'] = 0, 0, 0, 1 cube.draw(gl.GL_LINES, outline) gl.glDepthMask(gl.GL_TRUE) imguiRenderer.render(imgui.get_draw_data())
def _draw_rgb(self, obj_id, mat_model, mat_view, mat_proj): """Renders an RGB image. :param obj_id: ID of the object model to render. :param mat_model: 4x4 ndarray with the model matrix. :param mat_view: 4x4 ndarray with the view matrix. :param mat_proj: 4x4 ndarray with the projection matrix. :return: HxWx3 ndarray with the rendered RGB image. """ # Update the OpenGL program. program = self.rgb_programs[obj_id] program['u_light_eye_pos'] = [0, 0, 0] # Camera origin. program['u_light_ambient_w'] = self.light_ambient_weight program['u_mv'] = _calc_model_view(mat_model, mat_view) program['u_nm'] = _calc_normal_matrix(mat_model, mat_view) program['u_mvp'] = _calc_model_view_proj(mat_model, mat_view, mat_proj) # OpenGL setup. gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(self.bg_color[0], self.bg_color[1], self.bg_color[2], self.bg_color[3]) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, self.width, self.height) # Keep the back-face culling disabled because of objects which do not have # well-defined surface (e.g. the lamp from the lm dataset). gl.glDisable(gl.GL_CULL_FACE) # Rendering. program.draw(gl.GL_TRIANGLES, self.index_buffers[obj_id]) # Get the content of the FBO texture. rgb = np.zeros((self.height, self.width, 4), dtype=np.float32) gl.glReadPixels(0, 0, self.width, self.height, gl.GL_RGBA, gl.GL_FLOAT, rgb) rgb.shape = (self.height, self.width, 4) rgb = rgb[::-1, :] rgb = np.round(rgb[:, :, :3] * 255).astype( np.uint8) # Convert to [0, 255]. return rgb
def on_draw(self, dt): program = self.program window = self.window # set title window.set_title(str( window.fps).encode("ascii")) self.update_VertexBuffer(dt) # # Point # gl.glDisable(gl.GL_BLEND) # gl.glEnable(gl.GL_DEPTH_TEST) # gl.glPointSize(5) # program['ucolor'] = 1, 1, 1, 1 # program.draw(gl.GL_POINTS, self.point_idx) # Fill gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) program['ucolor'] = 1, 1, 1, 1 program.draw(gl.GL_QUADS, self.outline) # Outlined program # gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) # gl.glEnable(gl.GL_BLEND) # gl.glDepthMask(gl.GL_FALSE) # program['ucolor'] = 0, 0, 0, 1 # program.draw(gl.GL_LINES, self.outline) # gl.glDepthMask(gl.GL_TRUE) # Make program rotate self.theta += 0*dt # degrees self.phi += 2*dt # degrees model = np.eye(4, dtype=np.float32) glm.rotate(model, 90, 1, 0, 0) glm.rotate(model, self.theta, 0, 0, 1) glm.rotate(model, self.phi, 0, 1, 0) glm.rotate(model, 45, 1, 0, 0) program['model'] = model
def initializeGL(self): gl.glEnable(gl.GL_DEPTH_TEST) gl.glShadeModel(gl.GL_FLAT) gl.glDisable(gl.GL_BLEND) gl.glFrontFace(gl.GL_CCW) gl.glClearColor(*self._clear_color) gl.glDisable(gl.GL_CULL_FACE) # Setup object self.V, self.I = object_vertices.get_2d_plane() self.program.bind(self.V) # Send the updated transformation matrices to the shader self.program[OBJECT_MATRIX_NAME] = self._object_to_world self.program[VIEW_MATRIX_NAME] = self._world_to_view self.program[PROJECTION_MATRIX_NAME] = self._view_to_projection # Start an update timer to refresh rendering self._timer = QTimer() self._timer.setInterval(int(1000 / self._frame_rate)) self._timer.timeout.connect(self.update) self._timer.start()
def on_draw(self, dt): self.last_view_matrix = self.get_next_view_matrix( self.n_frame, self.t_elapsed) self.last_frame = self.render_frame(self.last_view_matrix) if self.out_buffer_location == 'torch': cpy_tensor_to_texture(self.last_frame, self.screen_tex_cuda) self.window.clear() gl.glDisable(gl.GL_CULL_FACE) # ensure viewport size is correct (offline renderer could change it) gl.glViewport(0, 0, self.viewport_size[0], self.viewport_size[1]) self.screen_program.draw(gl.GL_TRIANGLE_STRIP) self.n_frame += 1 self.t_elapsed += dt if self.args.nearest_train: ni = nearest_train( self.scene_data['view_matrix'], np.linalg.inv(self.scene_data['model3d_origin']) @ self.last_view_matrix) label = self.scene_data['camera_labels'][ni] assert self.args.gt, 'you must define path to gt images' path = self.args.gt.replace('*', str(label)) if not os.path.exists(path): print(f'{path} NOT FOUND!') elif self.last_gt_image != path: self.last_gt_image = path img = cv2.imread(path) max_side = max(img.shape[:2]) s = 1024 / max_side img = cv2.resize(img, None, None, s, s) cv2.imshow('nearest train', img) cv2.waitKey(1)
def on_draw(dt): global framebuffer, offset_index offset_name = list(offsets.keys())[offset_index] offset = offsets[offset_name] gl.glViewport(0, 0, width, height) framebuffer_2.activate() window.clear() framebuffer_2.deactivate() for dx, dy in offset: framebuffer_1.activate() window.clear() scene["offset"] = (2 * dx - 1) / width, (2 * dy - 1) / height scene.draw(gl.GL_TRIANGLE_STRIP) # scene.draw(gl.GL_LINE_LOOP) framebuffer_1.deactivate() framebuffer_2.activate() gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_CONSTANT_ALPHA, gl.GL_ONE) gl.glBlendColor(0, 0, 0, 1 / len(offset)) ssaa.draw(gl.GL_TRIANGLE_STRIP) gl.glDisable(gl.GL_BLEND) framebuffer_2.deactivate() gl.glViewport(0, 0, window.width, window.height) window.clear() final.draw(gl.GL_TRIANGLE_STRIP) gl.glReadPixels(0, 0, window.width, window.height, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, framebuffer) framebuffer[...] = framebuffer[::-1, :] # filename = "triangle-ssaa-outlined-%s.png" % offset_name filename = "triangle-ssaa-filled-%s.png" % offset_name png.from_array(framebuffer, 'RGB').save(filename) offset_index += 1
def draw_depth(shape, vertex_buffer, index_buffer, mat_model, mat_view, mat_proj): program = gloo.Program(_depth_vertex_code, _depth_fragment_code) program.bind(vertex_buffer) program['u_mv'] = _compute_model_view(mat_model, mat_view) program['u_mvp'] = _compute_model_view_proj(mat_model, mat_view, mat_proj) # Frame buffer object color_buf = np.zeros((shape[0], shape[1], 4), np.float32).view(gloo.TextureFloat2D) depth_buf = np.zeros((shape[0], shape[1]), np.float32).view(gloo.DepthTexture) fbo = gloo.FrameBuffer(color=color_buf, depth=depth_buf) fbo.activate() # OpenGL setup gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(0.0, 0.0, 0.0, 0.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, shape[1], shape[0]) # Keep the back-face culling disabled because of objects which do not have # well-defined surface (e.g. the lamp from the dataset of Hinterstoisser) gl.glDisable(gl.GL_CULL_FACE) # gl.glEnable(gl.GL_CULL_FACE) # gl.glCullFace(gl.GL_BACK) # Back-facing polygons will be culled # Rendering program.draw(gl.GL_TRIANGLES, index_buffer) # Retrieve the contents of the FBO texture depth = np.zeros((shape[0], shape[1], 4), dtype=np.float32) gl.glReadPixels(0, 0, shape[1], shape[0], gl.GL_RGBA, gl.GL_FLOAT, depth) depth.shape = shape[0], shape[1], 4 depth = depth[::-1, :] depth = depth[:, :, 0] # Depth is saved in the first channel fbo.deactivate() return depth
def render(self, scene, cull_face=True): self.fbo.activate() gl.glEnable(gl.GL_PROGRAM_POINT_SIZE) gl.glEnable(gl.GL_DEPTH_TEST) gl.glShadeModel(gl.GL_FLAT) if cull_face: gl.glEnable(gl.GL_CULL_FACE) gl.glCullFace(gl.GL_BACK) else: gl.glDisable(gl.GL_CULL_FACE) gl.glClearColor(*self.clear_color) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, self.viewport_size[0], self.viewport_size[1]) if scene.draw_points: scene.program.draw(gl.GL_POINTS) else: assert scene.index_buffer is not None scene.program.draw(gl.GL_TRIANGLES, scene.index_buffer) if self.out_buffer_location == 'torch': frame = cpy_texture_to_tensor(self.color_buf_cuda, self.out_buf).clone() elif self.out_buffer_location == 'opengl': frame = self.out_buf else: gl.glReadPixels(0, 0, self.viewport_size[0], self.viewport_size[1], gl.GL_RGB, gl.GL_FLOAT, self.out_buf) frame = self.out_buf.copy() self.fbo.deactivate() return frame
def _draw_depth(self, obj_id, mat_model, mat_view, mat_proj): """Renders a depth image. :param obj_id: ID of the object model to render. :param mat_model: 4x4 ndarray with the model matrix. :param mat_view: 4x4 ndarray with the view matrix. :param mat_proj: 4x4 ndarray with the projection matrix. :return: HxW ndarray with the rendered depth image. """ # Update the OpenGL program. program = self.depth_programs[obj_id] program['u_mv'] = _calc_model_view(mat_model, mat_view) program['u_mvp'] = _calc_model_view_proj(mat_model, mat_view, mat_proj) # OpenGL setup. gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(0.0, 0.0, 0.0, 0.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, self.width, self.height) # Keep the back-face culling disabled because of objects which do not have # well-defined surface (e.g. the lamp from the lm dataset). gl.glDisable(gl.GL_CULL_FACE) # Rendering. program.draw(gl.GL_TRIANGLES, self.index_buffers[obj_id]) # Get the content of the FBO texture. depth = np.zeros((self.height, self.width, 4), dtype=np.float32) gl.glReadPixels(0, 0, self.width, self.height, gl.GL_RGBA, gl.GL_FLOAT, depth) depth.shape = (self.height, self.width, 4) depth = depth[::-1, :] depth = depth[:, :, 0] # Depth is saved in the first channel return depth
def _deactivate(self): """ Deactivate texture on GPU """ log.debug("GPU: Deactivate texture cube") gl.glBindTexture(self._target, 0) gl.glDisable(gl.GL_TEXTURE_CUBE_MAP)
def draw_color(shape, vertex_buffer, index_buffer, texture, mat_model, mat_view, mat_proj, ambient_weight, bg_color, shading): # Set shader for the selected shading if shading == 'flat': color_fragment_code = _color_fragment_flat_code else: # 'phong' color_fragment_code = _color_fragment_phong_code program = gloo.Program(_color_vertex_code, color_fragment_code) program.bind(vertex_buffer) program['u_light_eye_pos'] = [0, 0, 0] # Camera origin program['u_light_ambient_w'] = ambient_weight program['u_mv'] = _compute_model_view(mat_model, mat_view) program['u_nm'] = _compute_normal_matrix(mat_model, mat_view) program['u_mvp'] = _compute_model_view_proj(mat_model, mat_view, mat_proj) if texture is not None: program['u_use_texture'] = int(True) program['u_texture'] = texture else: program['u_use_texture'] = int(False) program['u_texture'] = np.zeros((1, 1, 4), np.float32) # Frame buffer object color_buf = np.zeros((shape[0], shape[1], 4), np.float32).view(gloo.TextureFloat2D) depth_buf = np.zeros((shape[0], shape[1]), np.float32).view(gloo.DepthTexture) fbo = gloo.FrameBuffer(color=color_buf, depth=depth_buf) fbo.activate() # OpenGL setup gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(bg_color[0], bg_color[1], bg_color[2], bg_color[3]) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, shape[1], shape[0]) # gl.glEnable(gl.GL_BLEND) # gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) # gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST) # gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST) # gl.glDisable(gl.GL_LINE_SMOOTH) # gl.glDisable(gl.GL_POLYGON_SMOOTH) # gl.glEnable(gl.GL_MULTISAMPLE) # Keep the back-face culling disabled because of objects which do not have # well-defined surface (e.g. the lamp from the dataset of Hinterstoisser) gl.glDisable(gl.GL_CULL_FACE) # gl.glEnable(gl.GL_CULL_FACE) # gl.glCullFace(gl.GL_BACK) # Back-facing polygons will be culled # Rendering program.draw(gl.GL_TRIANGLES, index_buffer) # Retrieve the contents of the FBO texture rgb = np.zeros((shape[0], shape[1], 4), dtype=np.float32) gl.glReadPixels(0, 0, shape[1], shape[0], gl.GL_RGBA, gl.GL_FLOAT, rgb) rgb.shape = shape[0], shape[1], 4 rgb = rgb[::-1, :] rgb = np.round(rgb[:, :, :3] * 255).astype(np.uint8) # Convert to [0, 255] fbo.deactivate() return rgb
def on_init(): gl.glEnable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_BLEND)
@window.event def on_mouse_scroll(x, y, dx, dy): scale = C["scale"][0] C["scale"] = min(max(0.01, scale + .01 * dy * scale), 100) font = Font("Vera.ttf") C = gp.GlyphCollection(dtypes=[('translate', np.float32, 2)], translate='shared') for anchor_x in ['left', 'center', 'right']: for anchor_y in ['bottom', 'center', 'top']: C.append("Hello", font, anchor_x=anchor_x, anchor_y=anchor_y, color=(0,0,0,.5)) theta,dtheta = 0,0 C['u_kernel'] = gp.data.get("spatial-filters.npy") C['atlas_data'] = font.atlas C['atlas_data'].interpolation = gl.GL_LINEAR C['atlas_shape'] = font.atlas.shape[1],font.atlas.shape[0] C['scale'] = 1.0 C['model'] = np.eye(4, dtype=np.float32) gl.glClearColor(1.0, 1.0, 1.0, 1.0) gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gp.run()
x, y, z = spectrum_to_xyz(bb_spectrum, temperature) r, g, b = xyz_to_rgb(SMPTEsystem, x, y, z) r = min((max(r, 0), 1)) g = min((max(g, 0), 1)) b = min((max(b, 0), 1)) colors[i] = norm_rgb(r, g, b) program = gloo.Program(vertex, fragment, count=len(galaxy)) view = np.eye(4, dtype=np.float32) model = np.eye(4, dtype=np.float32) projection = np.eye(4, dtype=np.float32) glm.translate(view, 0, 0, -5) program['u_model'] = model program['u_view'] = view program['u_colormap'] = colors program['u_texture'] = data.get("particle.png") program['u_texture'].interpolation = gl.GL_LINEAR program['a_temperature'] = (galaxy['temperature'] - t0) / (t1 - t0) program['a_brightness'] = galaxy['brightness'] program['a_size'] = galaxy['size'] program['a_type'] = galaxy['type'] gl.glClearColor(0.0, 0.0, 0.03, 1.0) gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE) app.run(framerate=60)
def on_draw(dt): global trans self.window.clear() gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) self.render_kernel.draw(gl.GL_TRIANGLES)
def on_draw(dt): window.clear() gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) obj.draw(gl.GL_TRIANGLES, I) obj['time'] += dt
def on_draw(dt): self.window.clear() gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) self.render_kernels[self.brightness_k].draw(gl.GL_TRIANGLES)
def on_draw(dt): self.window.clear() gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) # print('brightness_k', self.brightness_k) # this function runs when running app.run() self.render_kernels[self.brightness_k].draw(gl.GL_TRIANGLES)
def on_init(): gl.glDisable(gl.GL_DEPTH_TEST) gl.glDisable(gl.GL_BLEND) ClearSurface(Temperature.Ping, AmbientTemperature) CreateObstacles(Obstacles, GridWidth, GridHeight)