def renderGL(self): """opengl render method""" # get the time in seconds t = glfwGetTime() # clear first glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # use the shader program glUseProgram(self.__shaderProgram) # calculate ViewProjection matrix projection = glm.perspective(90.0, 4.0 / 3.0, .1, 100.0) projection = np.array(projection, dtype=np.float32) # translate the world/view position view = glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, -50.0)) # make the camera rotate around the origin view = glm.rotate(view, 30.0 * math.sin(t * 0.1), glm.vec3(1.0, 0.0, 0.0)) view = glm.rotate(view, -22.5 * t, glm.vec3(0.0, 1.0, 0.0)) view = np.array(view, dtype=np.float32) # set the uniform glUniformMatrix4fv(self.__viewLocation, 1, GL_FALSE, view) glUniformMatrix4fv(self.__projLocation, 1, GL_FALSE, projection) # bind the vao glBindVertexArray(self.__vao) # draw glDrawArrays(GL_POINTS, 0, self.__particles) glBindVertexArray(0) glUseProgram(0)
def renderGL(self): """opengl render method""" # get the time in seconds t = glfwGetTime() # clear first glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # use the shader program glUseProgram(self.__shaderProgram) # calculate ViewProjection matrix projection = glm.perspective(90.0, 4.0 / 3.0, .1, 100.0) # translate the world/view position view = glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, -5.0)) # make the camera rotate around the origin view = glm.rotate(view, 90.0 * t, glm.vec3(1.0, 1.0, 1.0)) viewProjection = np.array(projection * view, dtype=np.float32) # set the uniform glUniformMatrix4fv(self.__vpLocation, 1, GL_FALSE, viewProjection) # bind the vao glBindVertexArray(self.__vao) # draw # the additional parameter indicates how many instances to render glDrawElementsInstanced(GL_TRIANGLES, 6 * 6, GL_UNSIGNED_INT, None, 8) glBindVertexArray(0) glUseProgram(0)
def from_bl(self, bl, a): self.name = bl.name self.data = a(bl.data) self.parent = a(bl.parent) self.location = glm.vec3(*bl.location) self.rotation = glm.vec3(*bl.rotation_euler) self.scale = glm.vec3(*bl.scale) self.modifiers = [a(x) for x in bl.modifiers] self.constraints = [a(x) for x in bl.constraints]
def from_bl(self, bl, a): self.name = bl.name self.materials = [a(x) for x in bl.materials] self.vertices = [glm.vec3(*x.co) for x in bl.vertices] self.polygons = [ [bl.loops[y].vertex_index for y in range(x.loop_start, x.loop_start + x.loop_total)] for x in bl.polygons]
def update_camera_vectors(self): front = glm.vec3(x=np.cos(glm.radians(self.yaw)) * np.cos(glm.radians(self.pitch)), y=np.sin(glm.radians(self.pitch)), z=np.sin(glm.radians(self.yaw)) * np.cos(glm.radians(self.pitch))) self.front = glm.normalize(front) self.right = glm.normalize(np.cross(self.front, self.world_up)) self.up = glm.normalize(np.cross(self.right, self.front))
def draw(p = None, s = None, r = None, o = None): if r is None: r = 0 if p is None: p = glm.vec2(0) if s is None: s = glm.vec2(1) if o is None: o = glm.vec2(0) global _texcoordsdirty _program.uniform('matrix', _matrix.translate(glm.vec3(p, 0)).rotate(r, glm.vec3(0, 0, 1)).scale(glm.vec3(s, 1)).translate(glm.vec3(-o, 0)).scale(glm.vec3(_img.size, 1))) q = p + glm.vec2(_img.size) * s if _texcoordsdirty: _vbo.data(_itc, s_f6_4) _texcoordsdirty = False _vbo.data(_itc, 0) _wd.draw('triangle fan', 4) _program.uniform('matrix', _matrix)
def __init__(self, width=640, height=480, title='GLFW opengl window'): self.width = width self.height = height self.title = title self.window = None self.__vertexShader = './shaders/%s.vert' % self.title self.__geomShader = './shaders/%s.geom' % self.title self.__fragmentShader = './shaders/%s.frag' % self.title self.__shaderProgram = None self.__vao = None self.__vbo = None self.__viewLocation = None self.__projLocation = None self.__particles = 128 * 1024 self.__tfShader = './shaders/09tfshader.vert' self.__tshaderProgram = None self.__centerLocation = None self.__radiusLocation = None self.__gLocation = None self.__dtLocation = None self.__bounceLocation = None self.__seedLocation = None self.__center = [] self.__radius = [] # physical parameters self.__dt = 1.0 / 60.0 self.__g = glm.vec3(0.0, -9.81, 0.0) self.__bounce = 1.2 # inelastic: 1.0, elastic: 2.0 self.__currentBuffer = 0 self.__bufferCount = 2
def mouse_callback2(win, mouse_x, mouse_y): global last_mouse_x, last_mouse_y global yaw, pitch global camera_front global first_mouse if first_mouse: first_mouse = False last_mouse_x = mouse_x last_mouse_y = mouse_y offset_x = mouse_x - last_mouse_x offset_y = last_mouse_y - mouse_y # invert y last_mouse_x = mouse_x last_mouse_y = mouse_y sensitivity = 0.2 offset_x *= sensitivity offset_y *= sensitivity yaw += offset_x pitch += offset_y # print(yaw, pitch) if pitch > 89.0: pitch = 89.0 if pitch < -89.0: pitch = -89.0 front = glm.vec3(x=np.cos(glm.radians(yaw)) * np.cos(glm.radians(pitch)), y=np.sin(glm.radians(pitch)), z=np.sin(glm.radians(yaw)) * np.cos(glm.radians(pitch))) camera_front = glm.normalize(front)
def __init__(self, position=glm.vec3(0, 0, 3), front=glm.vec3(0, 0, -1), up=glm.vec3(0, 1, 0), yaw=-90., pitch=0., movement_speed=3., mouse_speed=0.5, fov=45., ): self.position = position self.front = front self.up = up self.world_up = up self.right = None self.yaw = yaw self.pitch = pitch self.movement_speed = movement_speed self.mouse_speed = mouse_speed self.fov = fov self.update_camera_vectors()
def test_educatemyself(): 'Just making sure things work like I think they do.' idt = glm.mat4x4.identity() idt2 = glm.mat4x4.identity() assert idt.equals(idt2) l = glm.mat3x3.look_at(glm.vec3(0,0,-1), glm.vec3(0,1,0)) assert l.equals(glm.mat3x3.identity()) # Test that rotation is counter-clockwise center = glm.vec3(0,0,-1) up = glm.vec3(0,1,0) rot = glm.mat3x3.rotation(math.pi / 2.0, glm.vec3(0,1,0)) center = rot.mul_vec3(center) rot = rot.mul_vec3(up) print(center, rot) l = glm.mat3x3.look_at(center, up) assert glm.vec3(-1,0,0).equals(l.mul_vec3(glm.vec3(0,0,-1)))
def render_scene(time, cam1, view, projection): glClearColor(.8, .12, 0.32, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Create meshes points1, normals1 = generate_height_map(nw=8, nl=8, width=4, length=4, t=1.5*time, zscale=0.6) points3, indices3 = box() vao1, vbo1, ebo1 = create_vertex_array2(coords=points1, colors=normals1) vao_lamp, _, _ = create_vertex_array2(coords=points3, indices=indices3) # Light source: lamp light_color = glm.vec3(1, 1, 1) light_position = glm.vec3(np.cos(time), 1., np.sin(time)) # Height map glBindVertexArray(vao1) glUseProgram(shader_basic_lighting) model = glm.identity(4) # model = glm.translate(glm.vec3(.0, 0.5, .0)) * model model = model * glm.rotate(-np.pi/2, glm.vec3(1, 0, 0)) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "light_color"), 1, light_color) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "light_pos"), 1, light_position) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "object_color"), 1, glm.vec3(1, .5, .31)) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "view_pos"), 1, cam1.position) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "model"), 1, GL_TRUE, np.asarray(model)) glDrawArrays(GL_TRIANGLES, 0, len(points1)) glBindVertexArray(0) # Lamp glUseProgram(shader_solid) glBindVertexArray(vao_lamp) model = glm.translate(light_position) model = model * glm.scale(glm.vec3(.2, .2, .2)) glUniform3fv(glGetUniformLocation(shader_solid, "solid_color"), 1, glm.vec3(1, 1, 1)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "model"), 1, GL_TRUE, np.asarray(model)) glDrawElements(GL_TRIANGLES, len(indices3), GL_UNSIGNED_INT, None) glBindVertexArray(0)
def render_scene(time, cam1, view, projection): glClearColor(.8, .12, 0.32, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Create meshes points3, indices3 = box() vao_lamp = VAO(attributes=[points3], indices=indices3) # Light source: lamp light_color = glm.vec3(1, 1, 1) light_position = glm.vec3(3*np.cos(time), 2., 3*np.sin(time)) # Height map # glBindVertexArray(vao1) vao1.bind() glUseProgram(shader_flat_shading) model = glm.identity(4) # model = glm.translate(glm.vec3(.0, 0.5, .0)) * model model = model * glm.rotate(-np.pi/2, glm.vec3(1, 0, 0)) glUniform1f(glGetUniformLocation(shader_flat_shading, "time"), time); glUniform3fv(glGetUniformLocation(shader_flat_shading, "light_color"), 1, light_color) glUniform3fv(glGetUniformLocation(shader_flat_shading, "light_pos"), 1, light_position) glUniform3fv(glGetUniformLocation(shader_flat_shading, "object_color"), 1, glm.vec3(1, .5, .31)) glUniform3fv(glGetUniformLocation(shader_flat_shading, "view_pos"), 1, cam1.position) glUniformMatrix4fv(glGetUniformLocation(shader_flat_shading, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_flat_shading, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_flat_shading, "model"), 1, GL_TRUE, np.asarray(model)) glDrawArrays(GL_TRIANGLES, 0, len(points1)) glBindVertexArray(0) # Lamp glUseProgram(shader_solid) vao_lamp.bind() model = glm.translate(light_position) model = model * glm.scale(glm.vec3(.2, .2, .2)) glUniform3fv(glGetUniformLocation(shader_solid, "solid_color"), 1, glm.vec3(1, 1, 1)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "model"), 1, GL_TRUE, np.asarray(model)) glDrawElements(GL_TRIANGLES, len(indices3), GL_UNSIGNED_INT, None) glBindVertexArray(0)
def __init__(self, width, height): global m_vao global m_vbo i = 0 j = 0 load_shaders() initial_positions = [glm.vec4() for _ in range(POINTS_TOTAL)] initial_velocities = [glm.vec3() for _ in range(POINTS_TOTAL)] connection_vectors = [glm.ivec3() for _ in range(POINTS_TOTAL)] n = 0 for j in range(0, POINTS_Y): fj = float(j) / float(POINTS_Y) for i in range(0, POINTS_X): fi = float(i) / float(POINTS_X) initial_positions[n] = glm.vec4((fi - 0.5) * float(POINTS_X), (fj - 0.5) * float(POINTS_Y), 0.6 * sin(fi) * cos(fj), 1.0) initial_velocities[n] = glm.vec3(0.0) connection_vectors[n] = glm.ivec4(-1) if (j != (POINTS_Y - 1)): if (i != 0): connection_vectors[n][0] = n - 1 if (j != 0): connection_vectors[n][1] = n - POINTS_X if (i != (POINTS_X - 1)): connection_vectors[n][2] = n + 1 if (j != (POINTS_Y - 1)): connection_vectors[n][3] = n + POINTS_X n += 1 for i in range(0, 2): glGenVertexArrays(1, m_vao[i]) for i in range(0, 5): glGenBuffers(i + 1, m_vbo[i]) for i in range(0, 2): glBindVertexArray(m_vao[i]) glBindBuffer(GL_ARRAY_BUFFER, m_vbo[POSITION_A + i]) # POSITION_A glBindBuffer(GL_ARRAY_BUFFER, m_vbo[POSITION_A + i]) ar_position = np.empty([POINTS_TOTAL, 4], dtype='float32') for j, e in enumerate(initial_positions): ar_position[j] = e glBufferData(GL_ARRAY_BUFFER, POINTS_TOTAL * glm.sizeof(glm.vec4()), ar_position, GL_DYNAMIC_COPY) glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) # VELOCITY_A glBindBuffer(GL_ARRAY_BUFFER, m_vbo[VELOCITY_A + i]) ar_velocities = np.empty([POINTS_TOTAL, 3], dtype='float32') for j, e in enumerate(initial_velocities): ar_velocities[j] = e glBufferData(GL_ARRAY_BUFFER, POINTS_TOTAL * glm.sizeof(glm.vec3()), ar_velocities, GL_DYNAMIC_COPY) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # CONNECTION glBindBuffer(GL_ARRAY_BUFFER, m_vbo[CONNECTION]) ar_connection = np.empty([POINTS_TOTAL, 4], dtype='uint32') for j, e in enumerate(connection_vectors): ar_connection[j] = e glBufferData(GL_ARRAY_BUFFER, POINTS_TOTAL * glm.sizeof(glm.ivec4()), ar_connection, GL_STATIC_DRAW) glVertexAttribIPointer(2, 4, GL_INT, 0, None) glEnableVertexAttribArray(2) glGenTextures(2, m_pos_tbo) glBindTexture(GL_TEXTURE_BUFFER, m_pos_tbo[0]) glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, m_vbo[POSITION_A]) glBindTexture(GL_TEXTURE_BUFFER, m_pos_tbo[1]) glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, m_vbo[POSITION_B]) lines = (POINTS_X - 1) * POINTS_Y + (POINTS_Y - 1) * POINTS_X glGenBuffers(1, m_index_buffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_index_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, lines * 2 * ctypes.sizeof(ctypes.c_int), None, GL_STATIC_DRAW) e = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, lines * 2 * ctypes.sizeof(ctypes.c_int), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) int_array = (ctypes.c_int * (4 * lines * 2)).from_address(e) n = 0 for j in range(0, POINTS_Y): for i in range(0, POINTS_X - 1): int_array[n] = i + j * POINTS_X n += 1 int_array[n] = 1 + i + j * POINTS_X n += 1 for i in range(0, POINTS_X): for j in range(0, POINTS_Y - 1): int_array[n] = i + j * POINTS_X n += 1 int_array[n] = POINTS_X + i + j * POINTS_X n += 1 glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER)
w, h = glfwGetFramebufferSize(window) glViewport(0, 0, w, h) # glDepthRange(-10, 10) glEnable(GL_DEPTH_TEST) # draw only if the shape is closer to the viewer glDepthFunc(GL_LESS) # smaller means closer # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # Wireframe while not glfwWindowShouldClose(window): time = glfwGetTime() glClearColor(0.6, 0.6, 0.8, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # glClear(GL_COLOR_BUFFER_BIT) glUseProgram(shader1) view = glm.identity(4) view = glm.translate(glm.vec3(0, 0, -2)) view = view * glm.rotate(time, glm.vec3(0, 1, 0)) # glUniformMatrix4fv(glGetUniformLocation(shader1, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader1, "projection"), 1, GL_FALSE, np.asarray(projection)) glBindVertexArray(vao2) model = glm.identity(4) # model = glm.translate(glm.vec3(.0, 0, .0)) # model = model * glm.rotate(1.0 * np.pi * time, glm.vec3(1, 1, 0.2)) glUniformMatrix4fv(glGetUniformLocation(shader1, "model"), 1, GL_TRUE, np.asarray(model)) # (uniform location, num matrices, transpose?, matrix) # In numpy matrices (2D arrays) are expressed row by row whereas # in OpenGL they are column by column. Hence true is given # as the 3rd argument to transpose the matrix.
def render_scene(time, cam1, view, projection): # Light source: lamp light_color = glm.vec3(1, 1, 1) light_position = glm.vec3(np.cos(time), 1.5, np.sin(time)) # Ground glBindVertexArray(vao1) glUseProgram(shader_solid) model = glm.identity(4) model = glm.rotate(np.pi*0.5, glm.vec3(1, 0, 0)) * model glUniform3fv(glGetUniformLocation(shader_solid, "solid_color"), 1, glm.vec3(0, 0, 1)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "model"), 1, GL_TRUE, np.asarray(model)) glDrawElements(GL_TRIANGLES, len(indices1), GL_UNSIGNED_INT, None) glBindVertexArray(0) # Big Cube glBindVertexArray(vao2) glUseProgram(shader_basic_lighting) model = glm.identity(4) model = glm.translate(glm.vec3(.0, 0.5, .0)) * model # model = model * glm.rotate(1.0 * np.pi * time, glm.vec3(1, 1, 0.2)) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "light_color"), 1, light_color) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "light_pos"), 1, light_position) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "object_color"), 1, glm.vec3(1, .5, .31)) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "view_pos"), 1, cam1.position) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "model"), 1, GL_TRUE, np.asarray(model)) glDrawArrays(GL_TRIANGLES, 0, 36) glBindVertexArray(0) # Small cube glBindVertexArray(vao2) model = glm.identity(4) model = model * glm.translate(glm.vec3(.75, .95, 0)) model = model * glm.rotate(3.0 * np.pi * time, glm.vec3(1, -.2, 0.8)) model = model * glm.scale(glm.vec3(.1, .1, 0.2)) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "light_color"), 1, light_color) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "light_pos"), 1, light_position) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "object_color"), 1, glm.vec3(1, 0, 0)) glUniform3fv(glGetUniformLocation(shader_basic_lighting, "view_pos"), 1, cam1.position) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_basic_lighting, "model"), 1, GL_TRUE, np.array(model)) glDrawArrays(GL_TRIANGLES, 0, 36) glBindVertexArray(0) # Lamp glUseProgram(shader_solid) glBindVertexArray(vao_lamp) model = glm.translate(light_position) model = model * glm.scale(glm.vec3(.2, .2, .2)) glUniform3fv(glGetUniformLocation(shader_solid, "solid_color"), 1, glm.vec3(1, 1, 1)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "view"), 1, GL_TRUE, np.asarray(view)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "projection"), 1, GL_FALSE, np.asarray(projection)) glUniformMatrix4fv(glGetUniformLocation(shader_solid, "model"), 1, GL_TRUE, np.asarray(model)) glDrawElements(GL_TRIANGLES, len(indices3), GL_UNSIGNED_INT, None) glBindVertexArray(0)
def _face_center(self, face): center = glm.vec3() for vert in face: center += self._mesh.verts[vert] center /= len(face) return center
def movementYZ(direction, currentStance, nextStance): if currentStance == 'none': if nextStance == 'horizontal': if direction == 'd': cube.transform.rotation = glm.quat( glm.vec3(0, glm.radians(90), 0)) cube.transform.position += glm.vec3(0.5, 1.5, 0) else: cube.transform.rotation = glm.quat( glm.vec3(0, glm.radians(-90), 0)) cube.transform.position -= glm.vec3(-0.5, 1.5, 0) if nextStance == 'vertical': if direction == 'w': cube.transform.rotation = glm.quat( glm.vec3(glm.radians(90), 0, 0)) cube.transform.position += glm.vec3(-0.5, 0, -1.5) else: cube.transform.rotation = glm.quat( glm.vec3(glm.radians(-90), 0, 0)) cube.transform.position += glm.vec3(0.5, 0, 1.5) if currentStance == 'vertical': if nextStance == 'vertical': if direction == 'd': # cube.transform.rotation *= glm.quat(glm.vec3(0, 0, glm.radians(90))) cube.transform.position += glm.vec3(1, 0, 0) else: # cube.transform.rotation *= glm.quat(glm.vec3(0, 0, glm.radians(-90))) cube.transform.position -= glm.vec3(1, 0, 0) if nextStance == 'none': if direction == 'w': cube.transform.rotation = glm.quat( glm.vec3(0, 0, glm.radians(90))) cube.transform.position += glm.vec3(-0.5, 0, -1.5) else: cube.transform.rotation = glm.quat( glm.vec3(0, 0, glm.radians(-90))) cube.transform.position += glm.vec3(0.5, 0, 1.5) if currentStance == 'horizontal': if nextStance == 'horizontal': if direction == 'w': # cube.transform.rotation *= glm.quat(glm.vec3(0, glm.radians(90), 0)) cube.transform.position += glm.vec3(0, 0, -1) else: # cube.transform.rotation *= glm.quat(glm.vec3(0, glm.radians(-90), 0)) cube.transform.position -= glm.vec3(0, 0, -1) if nextStance == 'none': if direction == 'd': cube.transform.rotation = glm.quat( glm.vec3(0, 0, glm.radians(90))) cube.transform.position += glm.vec3(-0.5, 1.5, 0) else: cube.transform.rotation = glm.quat( glm.vec3(0, 0, glm.radians(-90))) cube.transform.position -= glm.vec3(0.5, 1.5, 0)
"""code that is repeated in all kind of scenes""" from glfw import * from OpenGL.GL import * import numpy as np import camera import glm from gl_utils import initialize_glfw import camera cam1 = camera.Camera(position=glm.vec3(0, 2, 5)) delta_time = 0. last_frame_time = 0. last_mouse_x = 300. last_mouse_y = 300. first_mouse = True keys = [False] * 1024 time = 0. # User input def key_callback(win, key, scancode, action, mods): global keys if key == GLFW_KEY_ESCAPE and action == GLFW_PRESS: glfwSetWindowShouldClose(win, True) if action == GLFW_PRESS: keys[key] = True elif action == GLFW_RELEASE: keys[key] = False
def scale(self, scale): self._dirty.add('_matrix') self._matrix = glm.scale(self._matrix, glm.vec3(scale / self.scale))
def _cmd_v(self, x, y, z=0.0): self.v.append(glm.vec3(float(x), float(y), float(z)))
0.0,0.0,1.0 ) W = 1600 H = 800 # Direct OpenGL commands to this window. window,fps_display = equinox_create_window(W,H,debug_fps=True) models = [] tree_mesh = Mesh.mesh_from_file(os.path.join(os.path.dirname(__file__),"tree.obj")) terrain_mesh = Mesh.mesh_from_file(os.path.join(os.path.dirname(__file__),"terrain.obj")) terrain = Entity(terrain_mesh) terrain.pos = glm.vec3(-20, 0, -20) for i in range(100): tree = Entity(tree_mesh) tree.move_to(glm.vec3(200*random()-100,0.0,200*random()-100)) print(f"tree ({tree}) [{i}] = {tree.pos}") terrain.move_to(glm.vec3(20*random()-10,0.0,20*random()-10)) models.append(tree) models.append(terrain) renderer = MasterRenderer() camera = Camera(W, H)
def get_icosahedron_positions(cls): a = 0.5 b = 1. / (1. + math.sqrt(5.)) return [ glm.vec3(0, b, -a), glm.vec3(b, a, 0), glm.vec3(-b, a, 0), glm.vec3(0, b, a), glm.vec3(0, -b, a), glm.vec3(-a, 0, b), glm.vec3(0, -b, -a), glm.vec3(a, 0, -b), glm.vec3(a, 0, b), glm.vec3(-a, 0, -b), glm.vec3(b, -a, 0), glm.vec3(-b, -a, 0), ]
def __init__(self, global_ambient): self.light_positions = [glm.vec3()] * LightSetup.MAX_LIGHT_COUNT self.lights = [com.Light(glm.vec3())] * LightSetup.MAX_LIGHT_COUNT self.global_ambient = global_ambient self.camera_position = glm.vec3() self.light_count = 0
loc_ka = glGetUniformLocation( program, "ka") # recuperando localizacao da variavel ka na GPU glUniform1f(loc_ka, ka) ### envia ka pra gpu loc_kd = glGetUniformLocation( program, "kd") # recuperando localizacao da variavel ka na GPU glUniform1f(loc_kd, kd) ### envia kd pra gpu #define id da textura do modelo glBindTexture(GL_TEXTURE_2D, 0) # desenha o modelo glDrawArrays(GL_TRIANGLES, 36, 72 - 36) ## renderizando cameraPos = glm.vec3(0.0, 0.0, 1.0) cameraFront = glm.vec3(0.0, 0.0, -1.0) cameraUp = glm.vec3(0.0, 1.0, 0.0) polygonal_mode = False def key_event(window, key, scancode, action, mods): global cameraPos, cameraFront, cameraUp, polygonal_mode, ka, kd cameraSpeed = 0.05 if key == 87 and (action == 1 or action == 2): # tecla W cameraPos += cameraSpeed * cameraFront if key == 83 and (action == 1 or action == 2): # tecla S cameraPos -= cameraSpeed * cameraFront
def initGL(self): """opengl initialization""" # load shaders vertexShader = self.shaderFromFile(GL_VERTEX_SHADER, self.__vertexShader) fragmentShader = self.shaderFromFile(GL_FRAGMENT_SHADER, self.__fragmentShader) self.__shaderProgram = shaders.compileProgram(vertexShader, fragmentShader) if not self.__shaderProgram: self.close() self.__ubIndex = glGetUniformBlockIndex(self.__shaderProgram, 'Matrices') # assign the block binding glUniformBlockBinding(self.__shaderProgram, self.__ubIndex, self.__matricesBinding) # create uniform buffer self.__ubo = glGenBuffers(1) glBindBuffer(GL_UNIFORM_BUFFER, self.__ubo) glBufferData(GL_UNIFORM_BUFFER, 9 * 4 * 4 * 4, None, GL_DYNAMIC_DRAW) # fill the Model matrix array modelMatrices = [] modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3( 2.0, 2.0, 2.0))) modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3( 2.0, 2.0, -2.0))) modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3( 2.0, -2.0, 2.0))) modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3( 2.0, -2.0, -2.0))) modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3(-2.0, 2.0, 2.0))) modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3(-2.0, 2.0, -2.0))) modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3(-2.0, -2.0, 2.0))) modelMatrices.append(glm.translate(glm.mat4(1.0), glm.vec3(-2.0, -2.0, -2.0))) modelMatrices = np.array(modelMatrices, dtype=np.float32) glBufferSubData(GL_UNIFORM_BUFFER, 4 * 4 * 4, modelMatrices.nbytes, modelMatrices) # generate and bind the vao self.__vao = glGenVertexArrays(1) glBindVertexArray(self.__vao) # generate and bind the buffer object vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) # data for a fullscreen quad vertexData = np.array([ # x y z U V # face 0: 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, # vertex 0 -1.0, 1.0, 1.0, 1.0, 0.0, 0.0, # vertex 1 1.0,-1.0, 1.0, 1.0, 0.0, 0.0, # vertex 2 -1.0,-1.0, 1.0, 1.0, 0.0, 0.0, # vertex 3 # face 1: 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, # vertex 0 1.0,-1.0, 1.0, 0.0, 1.0, 0.0, # vertex 1 1.0, 1.0,-1.0, 0.0, 1.0, 0.0, # vertex 2 1.0,-1.0,-1.0, 0.0, 1.0, 0.0, # vertex 3 # face 2: 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, # vertex 0 1.0, 1.0,-1.0, 0.0, 0.0, 1.0, # vertex 1 -1.0, 1.0, 1.0, 0.0, 0.0, 1.0, # vertex 2 -1.0, 1.0,-1.0, 0.0, 0.0, 1.0, # vertex 3 # face 3: 1.0, 1.0,-1.0, 1.0, 1.0, 0.0, # vertex 0 1.0,-1.0,-1.0, 1.0, 1.0, 0.0, # vertex 1 -1.0, 1.0,-1.0, 1.0, 1.0, 0.0, # vertex 2 -1.0,-1.0,-1.0, 1.0, 1.0, 0.0, # vertex 3 # face 4: -1.0, 1.0, 1.0, 0.0, 1.0, 1.0, # vertex 0 -1.0, 1.0,-1.0, 0.0, 1.0, 1.0, # vertex 1 -1.0,-1.0, 1.0, 0.0, 1.0, 1.0, # vertex 2 -1.0,-1.0,-1.0, 0.0, 1.0, 1.0, # vertex 3 # face 5: 1.0,-1.0, 1.0, 1.0, 0.0, 1.0, # vertex 0 -1.0,-1.0, 1.0, 1.0, 0.0, 1.0, # vertex 1 1.0,-1.0,-1.0, 1.0, 0.0, 1.0, # vertex 2 -1.0,-1.0,-1.0, 1.0, 0.0, 1.0, # vertex 3 ], dtype=np.float32) # fill with data glBufferData(GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, GL_STATIC_DRAW) # set up generic attrib pointers glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * 4, None) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * 4, ctypes.c_void_p(3 * 4)) ibo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) indexData = np.array([ # face 0: 0, 1, 2, # first triangle 2, 1, 3, # second triangle # face 1: 4, 5, 6, # first triangle 6, 5, 7, # second triangle # face 2: 8, 9, 10, # first triangle 10, 9, 11, # second triangle # face 3: 12, 13, 14, # first triangle 14, 13, 15, # second triangle # face 4: 16, 17, 18, # first triangle 18, 17, 19, # second triangle # face 5: 20, 21, 22, # first triangle 22, 21, 23, # second triangle ], dtype=np.uint) # fill with data glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexData.nbytes, indexData, GL_STATIC_DRAW) glBindVertexArray(0) # we are drawing 3d objects so we want depth testing glEnable(GL_DEPTH_TEST)
def _Init(self): # create cube mesh self.__cube = GL_MeshCube() # model view projection data shader storage block self.__model = glm.mat4(1) self.__view = glm.lookAt(glm.vec3(0,-3,0), glm.vec3(0,0,0), glm.vec3(0,0,1)) self.__proj = glm.perspective(glm.radians(90), self.__vp_size[0]/self.__vp_size[1], 0.1, 100) buffer_data = np.zeros(3*16, dtype=np.float32) for i in range(4): for j in range(4): buffer_data temp_ssbo = np.empty(1, dtype=np.uint32) glCreateBuffers(len(temp_ssbo), temp_ssbo) self.__mvp_ssbo = temp_ssbo[0] dynamic_mvp_data = True code = 0 if not dynamic_mvp_data else GL_DYNAMIC_STORAGE_BIT | GL_MAP_WRITE_BIT| GL_MAP_PERSISTENT_BIT glNamedBufferStorage(self.__mvp_ssbo, 3*16*SIZEOF_FLAOT32, None, code) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, self.__mvp_ssbo) ssbo_buffer = np.empty([16*3], dtype=np.float32) #modelbuffer = np.frombuffer(glm.value_ptr(self.__model), dtype=float) #viewbuffer = np.frombuffer(glm.value_ptr(self.__view), dtype=float) #projbuffer = np.frombuffer(glm.value_ptr(self.__proj), dtype=float) #glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), modelbuffer) #glBufferSubData(GL_SHADER_STORAGE_BUFFER, 1*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), viewbuffer) #glBufferSubData(GL_SHADER_STORAGE_BUFFER, 2*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), projbuffer) #np.put(ssbo_buffer, [i for i in range(16)], glm.value_ptr(self.__model)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, glm.sizeof(glm.mat4), glm.value_ptr(self.__model)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 1*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), glm.value_ptr(self.__view)) glBufferSubData(GL_SHADER_STORAGE_BUFFER, 2*glm.sizeof(glm.mat4), glm.sizeof(glm.mat4), glm.value_ptr(self.__proj)) # light data shader storage block light_data = [-1.0, -0.5, -2.0, 0.0, 0.2, 0.8, 0.8, 10.0] light_data_buffer = np.array( light_data, dtype=np.float32 ) temp_ssbo = np.empty(1, dtype=np.uint32) glCreateBuffers(len(temp_ssbo), temp_ssbo) self.__light_ssbo = temp_ssbo[0] dynamic_light_data = True code = 0 if not dynamic_light_data else GL_DYNAMIC_STORAGE_BIT | GL_MAP_WRITE_BIT| GL_MAP_PERSISTENT_BIT glNamedBufferStorage(self.__light_ssbo, light_data_buffer.nbytes, light_data_buffer, code) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, self.__light_ssbo) # set states glEnable(GL_DEPTH_TEST) self.__cube.Bind() # initialize (compile and link) shader program # This should be done after all OpenGL states have been set, # because NVIDIA optimize the current program for the current states an would have to recompile it if the states would change. # https://www.opengl.org/discussion_boards/showthread.php/175944-NVidia-280-x-and-GeForce-4xx?p=1229120&viewfull=1#post1229120 if os.path.isfile(spv_vert_draw_file) and os.path.isfile(spv_frag_draw_file): self.__draw_prog = GL_Program_SpirV(spv_vert_draw_file, spv_frag_draw_file) else: self.__draw_prog = GL_Program_GLSL(glsl_vert_draw_file, glsl_frag_draw_file) # create pipeline for draw mesh self.__draw_pipeline = np.empty(1, dtype=np.uint32) glGenProgramPipelines(1, self.__draw_pipeline) glUseProgramStages(self.__draw_pipeline[0], GL_VERTEX_SHADER_BIT | GL_FRAGMENT_SHADER_BIT, self.__draw_prog.Object()) #al = ['inPos', 'inNV', 'inCol'] #self.___attrib = self.__draw_prog.AttributeLocations(al) #print(self.___attrib) #ul = ['u_model', 'u_view', 'u_proj'] #self.__uniform = self.__draw_prog.UniformLocations(ul) #print(self.__uniform) # activate program and set states glBindProgramPipeline(self.__draw_pipeline[0])
to do: - Camera system - checker shader """ import numpy as np from glfw import * from OpenGL.GL import * from gl_utils import initialize_glfw, create_vertex_array2 import glm as glm from geometry import box, rectangle import shaders import camera cam1 = camera.Camera(position=glm.vec3(0, 2, 5)) delta_time = 0. last_frame_time = 0. last_mouse_x = 300. last_mouse_y = 300. first_mouse = True keys = [False] * 1024 # User input def key_callback(win, key, scancode, action, mods): if key == GLFW_KEY_ESCAPE and action == GLFW_PRESS: glfwSetWindowShouldClose(win, True) if action == GLFW_PRESS: keys[key] = True elif action == GLFW_RELEASE:
def scale(self): return decompose(self._matrix, scale=glm.vec3())
# Creating Data Buffers -----------------------------------------------------------| # With the ability of .obj file loading, all the data will be read from the files and bound to proper buffers primitive_objs = { "tiles": parse_and_bind_obj_file("Assets/Primitives/tiles.obj"), "cube": parse_and_bind_obj_file("Assets/Primitives/cube.obj"), "aabb": parse_and_bind_obj_file("Assets/Primitives/aabb.obj"), "plane": parse_and_bind_obj_file("Assets/Primitives/plane.obj"), "rectangular": parse_and_bind_obj_file("Assets/rectangular.obj") } collisionCounter = 0 # Create Shaders ---------------------------------------------------------------------| standard_shader = StandardShader() light_position = glm.vec3(0.0, 5.0, 10.0) AABB_shader = AABBShader(deepcopy(primitive_objs["aabb"])) UI_shader = UnlitBlendShader() # Create Camera and Game Objects -----------------------------------------------------| perspective_projection = glm.perspective(glm.radians(45.0), screen_size.x / screen_size.y, 0.1, 100.0) orthogonal_projection = glm.ortho(-10.0, 10.0, -10.0, 10.0) camera = Camera(Transform(position=glm.vec3(4.0, 10.0, 12.0), ), target=glm.vec3(2, 0.1, 0.2))
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import numpy as np from shader import ShaderProgram from model import Model, ModelFromExport import glm import time from camera3D import Camera3D from keyboard import keys_down, keys_up from collada_loader.model_loader import ColladaModel SCR_WIDTH = 800 SCR_HEIGHT = 800 camera = Camera3D(glm.vec3(0.0, 5.0, 30.0)) last_x = SCR_WIDTH / 2.0 last_y = SCR_HEIGHT / 2.0 first_mouse = True mouse_leave = True delta_time = 0.0 last_frame = 0.0 fps_count = 0 _fps = 0 NUM_SAMPLES = 10 frameTimes = [] currentFrame = 0
def testLookAt(self) : lookNGL=pyngl.lookAt(pyngl.Vec3(2.0,2.0,2.0),pyngl.Vec3(0,0,0),pyngl.Vec3(0,1.0,0)) lookGLM=glm.lookAt(glm.vec3(2.0,2.0,2.0),glm.vec3(0.0,0.0,0.0),glm.vec3(0.0,1.0,0.0)) self.assertTrue(self.glmToNGL(lookGLM)==lookNGL)
def test_node(): world = Node() # move/position assert fcmp(world.position, vec3(0)) world.move(vec3(1, 2, 3)) assert fcmp(world.position, vec3(1, 2, 3)) world.move(vec3(1, 2, 3)) assert fcmp(world.position, vec3(2, 4, 6)) # reset world.pos = vec3(0) assert fcmp(world.position, vec3(0)) # attach child = Node() world.position = vec3(0) assert not world.children world.attach(child) world.position = (1, 2, 3) child.position = vec3(1) assert fcmp(child.world_pos, vec3(2, 3, 4)) world.position = vec3(0) assert fcmp(child.world_pos, vec3(1)) world.position = vec3(1) assert fcmp(child.world_pos, vec3(2)) assert child.parent == world child.detach() assert child.parent is None assert fcmp(child.world_pos, vec3(2)) world.attach(child) assert child in world world.children._blocked += 1 child.detach() world.children._blocked -= 1 assert child in world assert world.children._blocked == 0 world.children.refresh() assert child not in world
def setTranslate(self, x, y, z): self.worldMat = glm.translate(glm.mat4(), glm.vec3(x, y, z))
def add_dodecahedron(self, mesh): phi = (1. + math.sqrt(5.)) / 2. a = 0.5 b = 0.5 / phi c = 0.5 * (2. - phi) self.add_pentagon( mesh, glm.vec3(c, 0, a), glm.vec3(b, b, b), glm.vec3(0, a, c), glm.vec3(-b, b, b), glm.vec3(-c, 0, a), ) self.add_pentagon( mesh, glm.vec3(-c, 0, a), glm.vec3(-b, -b, b), glm.vec3(0, -a, c), glm.vec3(b, -b, b), glm.vec3(c, 0, a), ) self.add_pentagon( mesh, glm.vec3(c, 0, -a), glm.vec3(b, -b, -b), glm.vec3(0, -a, -c), glm.vec3(-b, -b, -b), glm.vec3(-c, 0, -a), ) self.add_pentagon( mesh, glm.vec3(-c, 0, -a), glm.vec3(-b, b, -b), glm.vec3(0, a, -c), glm.vec3(b, b, -b), glm.vec3(c, 0, -a), ) self.add_pentagon( mesh, glm.vec3(0, a, -c), glm.vec3(0, a, c), glm.vec3(b, b, b), glm.vec3(a, c, 0), glm.vec3(b, b, -b), ) self.add_pentagon( mesh, glm.vec3(0, a, c), glm.vec3(0, a, -c), glm.vec3(-b, b, -b), glm.vec3(-a, c, 0), glm.vec3(-b, b, b), ) self.add_pentagon( mesh, glm.vec3(0, -a, -c), glm.vec3(0, -a, c), glm.vec3(-b, -b, b), glm.vec3(-a, -c, 0), glm.vec3(-b, -b, -b), ) self.add_pentagon( mesh, glm.vec3(0, -a, c), glm.vec3(0, -a, -c), glm.vec3(b, -b, -b), glm.vec3(a, -c, 0), glm.vec3(b, -b, b), ) self.add_pentagon( mesh, glm.vec3(a, c, 0), glm.vec3(b, b, b), glm.vec3(c, 0, a), glm.vec3(b, -b, b), glm.vec3(a, -c, 0), ) self.add_pentagon( mesh, glm.vec3(a, -c, 0), glm.vec3(b, -b, -b), glm.vec3(c, 0, -a), glm.vec3(b, b, -b), glm.vec3(a, c, 0), ) self.add_pentagon( mesh, glm.vec3(-a, c, 0), glm.vec3(-b, b, -b), glm.vec3(-c, 0, -a), glm.vec3(-b, -b, -b), glm.vec3(-a, -c, 0), ) self.add_pentagon( mesh, glm.vec3(-a, -c, 0), glm.vec3(-b, -b, b), glm.vec3(-c, 0, a), glm.vec3(-b, b, b), glm.vec3(-a, c, 0), )
def rotate(self, angle): self.worldMat = glm.rotate(self.worldMat, glm.radians(angle), glm.vec3(0, 0, 1))
) glEnableVertexAttribArray(0) glVertexAttribPointer( 1, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 4 * 6, # stride ctypes.c_void_p(4 * 3) # array buffer offset ) glEnableVertexAttribArray(1) i = glm.mat4(1) translate = glm.translate(i, glm.vec3(0, 0, 0)) rotate = glm.rotate(i, 0, glm.vec3(0, 1, 0)) scale = glm.scale(i, glm.vec3(1, 1, 1)) model = translate * rotate * scale view = glm.lookAt(glm.vec3(0, 0, 2), glm.vec3(0, 0, 0), glm.vec3(0, 1, 0)) projection = glm.perspective(glm.radians(45), 800 / 600, 0.1, 1000.0) superMatriz = projection * view * model glViewport(0, 0, 800, 600) def process_input(): for event in pygame.event.get(): if event.type == pygame.QUIT:
def scale(self, x, y): self.worldMat = glm.scale(self.worldMat, glm.vec3(x, y, 1))
def __init__(self, engine, sx, sy, length, height, seed): self.size = glm.vec3(sx * length, height, sy * length) self.tex_size = glm.vec2(sx, sy) self.texture = engine.graphics.get_texture('dirt') self.collider = physics_objects.Box((0, 0, 0), self.size) self.collider.get_height = self.get_height engine.physics.static.append(self.collider) self.positions = np.empty((sx * sy, 3), np.float32) normals = np.empty((sx * sy, 3), np.float32) texcoords = np.empty((sx * sy, 2), np.float32) colors = np.empty((sx * sy, 3), np.float32) indices = np.empty(6 * (sx - 1) * (sy - 1), np.uint32) # self.image = Image.new('L', (sx, sy), 'black') h = hash(seed) sample = glm.vec2(h, hash(h)) # Generate vertex positions for x in range(0, sx): for y in range(0, sy): pos = glm.vec3(x / float(sx), 0.0, y / float(sy)) for i in range(0, 4): pos.y += pow(1.0, -i) * noise2(pos.x + sample.x, pos.z + sample.y, i + 1) pos.y /= 4.0 pos.y = 0.5 * pos.y + 0.5 pos.y *= abs(pos.x-.5) + abs(pos.z-.5) # self.image.putpixel((x, y), int(pos.y * 255)) # pos.y = pos.x self.positions[y * sx + x] = list(pos) texcoords[y * sx + x] = [pos.x, pos.z] # image.close() # Specify indices and normals i = 0 for x in range(0, sx - 1): for y in range(0, sy - 1): indices[i] = y * sx + x indices[i + 1] = (y + 1) * sx + x indices[i + 2] = y * sx + x + 1 v0 = self.positions[indices[i]] v1 = self.positions[indices[i + 1]] v2 = self.positions[indices[i + 2]] normal = np.cross(v1 - v0, v2 - v0) normal /= np.linalg.norm(normal) normals[indices[i]] = normal normals[indices[i + 1]] = normal normals[indices[i + 2]] = normal i += 3 indices[i] = y * sx + (x + 1) indices[i + 1] = (y + 1) * sx + x indices[i + 2] = (y + 1) * sx + (x + 1) v0 = self.positions[indices[i]] v1 = self.positions[indices[i + 1]] v2 = self.positions[indices[i + 2]] normal = np.cross(v1 - v0, v2 - v0) normal /= np.linalg.norm(normal) normals[indices[i]] = normal normals[indices[i + 1]] = normal normals[indices[i + 2]] = normal i += 3 GRASS = glm.vec3(0.35, 0.65, 0.25) SNOW = glm.vec3(0.925, 0.93, 0.95) for x in range(0, sx): for y in range(0, sy): i = y * sx + x p = self.positions[i] normal = glm.vec3(float(normals[i, 0]), float(normals[i, 1]), float(normals[i, 2])) angle = max(glm.dot(normal, glm.vec3(0.0, 1.0, 0.0)), 0.0) h = float(p[1]) color = glm.mix(GRASS, SNOW * h, pow(angle, 10.0)) colors[i] = [color.x, color.y, color.z] self.mesh = mesh.Mesh(self.positions, normals, texcoords, colors, indices)
def scalePredefined(self, x, y): self.predefinedMat = glm.scale(self.predefinedMat, glm.vec3(x, y, 1))
def _cmd_vn(self, x, y, z): self.vn.append(glm.vec3(float(x), float(y), float(z)))
def get_vertices(self, *args, line_num=0, quad_num=0): points, lines, quads, line_offset, quad_offset = [], [], [], [], [] for arg in args: if instanceof(arg, list) and instanceof(arg[0], list) and instanceof(arg[0][0], (int,float)): line_offset.append((line_num, len(arg[0]))) line_num += len(arg[0]) for i in range(0, len(arg[0])): lines.extend([arg[0][i], arg[1][i], arg[2][i]]) elif instanceof(arg, tuple): if len(arg) == 2 and instanceof(arg[0], list): for line in arg[0]: line_offset.append((line_num, len(line))) line_num += len(line) for vert in line: lines.extend(list(vert)) for line in arg[1]: line_offset.append((line_num, len(line))) line_num += len(line) for vert in line: lines.extend(list(vert)) elif instanceof(arg[0], list) and len(arg) == 3 and len(arg[0]) == len(arg[1]) == len(arg[2]): for i in range(0, len(arg[0])): points.extend([arg[0][i], arg[1][i], arg[2][i]]) elif len(arg) == 3 and instanceof(arg[0], (int,float)): points.extend(list(arg)) else: temp = self.get_vertices(*arg, line_num=line_num, quad_num=quad_num) points.extend(temp[0]) lines.extend(temp[1]) quads.extend(temp[2]) line_offset.extend(temp[3]) quad_offset.extend(temp[4]) elif instanceof(arg, list): if instanceof(arg[0], tuple): line_offset.append((line_num, len(arg))) line_num += len(arg) for j in arg: lines.extend(list(j)) elif instanceof(arg[0], list): quad_start = quad_num for i in range(0, len(arg)-1): for j in range(0, len(arg[i])-1): a = glm.vec3(*arg[i][j+1]) - glm.vec3(*arg[i][j]) b = glm.vec3(*arg[i+1][j]) - glm.vec3(*arg[i][j]) normal = glm.normalize(glm.cross(b,a)) x_len = len(arg) - 1 y_len = len(arg[j]) - 1 quads.extend(list(arg[i][j]) + [i/x_len, j/y_len] + list(normal)) quads.extend(list(arg[i][j+1]) + [i/x_len, (j+1)/y_len] + list(normal)) quads.extend(list(arg[i+1][j]) + [(i+1)/x_len, j/y_len] + list(normal)) quads.extend(list(arg[i+1][j+1]) + [(i+1)/x_len, (j+1)/y_len] + list(normal)) quad_num += 4 quad_offset.append((quad_start, quad_num)) return ( np.array(points, dtype="float32"), np.array(lines, dtype="float32"), np.array(quads, dtype="float32"), line_offset, quad_offset )
def display(self): global last_time global total_time currentTime = time.time() uint_zeros = [0, 0, 0, 0] float_zeros = [0.0, 0.0, 0.0, 0.0] float_ones = [1.0, 1.0, 1.0, 1.0] draw_buffers = [GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1] if (not paused): total_time += (currentTime - last_time) last_time = currentTime t = total_time glBindFramebuffer(GL_FRAMEBUFFER, gbuffer) glViewport(0, 0, self.width, self.height) glDrawBuffers(2, draw_buffers) glClearBufferuiv(GL_COLOR, 0, uint_zeros) glClearBufferuiv(GL_COLOR, 1, uint_zeros) glClearBufferfv(GL_DEPTH, 0, float_ones) glBindBufferBase(GL_UNIFORM_BUFFER, 0, render_transform_ubo) matrices = glMapBufferRange( GL_UNIFORM_BUFFER, 0, (2 + NUM_INSTANCES) * glm.sizeof(glm.mat4), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) matricesp = (GLfloat * 16 * (2 + NUM_INSTANCES)).from_address(matrices) proj_matrix = (GLfloat * 16)(*identityMatrix) proj_matrix = m3dPerspective(m3dDegToRad(50.0), float(self.width) / float(self.height), 0.1, 1000.0) matricesp[0] = proj_matrix d = (sin(t * 0.131) + 2.0) * 0.15 eye_pos = (d * 120.0 * sin(t * 0.11), 5.5, d * 120.0 * cos(t * 0.01)) view_matrix = (GLfloat * 16)(*identityMatrix) view_matrix = m3dLookAt(eye_pos, (0.0, -20.0, 0.0), (0.0, 1.0, 0.0)) matricesp[1] = (GLfloat * 16)(*view_matrix) for j in range(0, 15): j_f = float(j) for i in range(0, 15): i_f = float(i) T = (GLfloat * 16)(*identityMatrix) m3dTranslateMatrix44(T, (i - 7.5) * 7.0, 0.0, (j - 7.5) * 11.0) matricesp[j * 15 + i + 2] = T glUnmapBuffer(GL_UNIFORM_BUFFER) glUseProgram(render_program_nm if use_nm else render_program) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, tex_diffuse) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, tex_nm) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) myobject.render(NUM_INSTANCES) glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(0, 0, self.width, self.height) glDrawBuffer(GL_BACK) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, gbuffer_tex[0]) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, gbuffer_tex[1]) if (vis_mode == VIS_OFF): glUseProgram(light_program) else: glUseProgram(vis_program) glUniform1i(loc_vis_mode, vis_mode) glDisable(GL_DEPTH_TEST) glBindBufferBase(GL_UNIFORM_BUFFER, 0, light_ubo) size_light_t = ctypes.sizeof(ctypes.c_float) * 6 lights = glMapBufferRange( GL_UNIFORM_BUFFER, 0, NUM_LIGHTS * size_light_t, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT) lightsp = (GLfloat * 6 * NUM_LIGHTS).from_address(lights) for i in range(0, NUM_LIGHTS): i_f = (i - 7.5) * 0.1 + 0.3 lightsp[i][0:3] = glm.vec3( 100.0 * sin(t * 1.1 + (5.0 * i_f)) * cos(t * 2.3 + (9.0 * i_f)), 15.0, 100.0 * sin(t * 1.5 + (6.0 * i_f)) * cos(t * 1.9 + (11.0 * i_f))) lightsp[i][3:6] = glm.vec3( cos(i_f * 14.0) * 0.5 + 0.8, sin(i_f * 17.0) * 0.5 + 0.8, sin(i_f * 13.0) * cos(i_f * 19.0) * 0.5 + 0.8) glUnmapBuffer(GL_UNIFORM_BUFFER) glBindVertexArray(fs_quad_vao) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) glBindTexture(GL_TEXTURE_2D, 0) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, 0) glutSwapBuffers()
def plot(self, *args, **kwargs): OPTIONS.update(kwargs) self.projection = glm.perspective(glm.radians(45), OPTIONS["size"][0]/OPTIONS["size"][1], 0.1, 1000) pygame.init() pygame.display.gl_set_attribute(GL_CONTEXT_MAJOR_VERSION, 4) pygame.display.gl_set_attribute(GL_CONTEXT_MINOR_VERSION, 1) pygame.display.gl_set_attribute(pygame.GL_CONTEXT_PROFILE_MASK, pygame.GL_CONTEXT_PROFILE_CORE) self.screen = pygame.display.set_mode(OPTIONS["size"], DOUBLEBUF | OPENGL | RESIZABLE | HWSURFACE) glClearColor(39/255,40/255,44/255,1) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_DEPTH_TEST) # glEnable(GL_MULTISAMPLE); # glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) self.generate_vertices(*args) pygame.display.set_caption(OPTIONS["title"]) last_tick = 0 animation_timer = 0 did_change = True self.is_running = True is_focused = False keypress = pygame.key.get_pressed() if OPTIONS["on_update"]: OPTIONS["on_update"]() while self.is_running: tick = pygame.time.get_ticks()/1000 delta_time = tick - last_tick last_tick = tick speed = 10 * delta_time camera_right = glm.normalize(glm.cross(self.camera_front, self.camera_up)) for event in pygame.event.get(): if event.type == MOUSEWHEEL: delta = 1 + event.y/100 self.zoom *= delta self.model = glm.scale(self.model, glm.vec3(delta)) did_change = True elif event.type == MOUSEMOTION: if event.buttons[0]: fx,fy,fz = self.camera_front rotate_front = glm.rotate(glm.mat4(1), glm.radians(-event.rel[0]/10), self.camera_up) rotate_up = glm.rotate(glm.mat4(1), glm.radians(-event.rel[1]/10), camera_right) self.camera_front = (rotate_front * glm.vec4(fx,fy,fz,1)).xyz ux,uy,uz = self.camera_front self.camera_front = (rotate_up * glm.vec4(ux,uy,uz,1)).xyz did_change = True elif event.buttons[2]: self.camera_pos -= speed * event.rel[0] * camera_right self.camera_pos += speed * event.rel[1] * self.camera_up did_change = True elif event.type == pygame.USEREVENT: if hasattr(event, "args"): if event.args: self.generate_vertices(*event.args) if hasattr(event, "kwargs"): OPTIONS.update(event.kwargs) elif hasattr(event, "animate"): delay = event.animate[0] callback = event.animate[1] self.is_animation_running = True did_change = True elif event.type == VIDEORESIZE: did_change = True OPTIONS["size"] = event.size self.projection = glm.perspective(glm.radians(45), event.size[0]/event.size[1], 0.1, 1000) elif event.type == ACTIVEEVENT: is_focused = bool(event.gain) elif (event.type == pygame.QUIT or (event.type == KEYUP and event.key == K_ESCAPE) or (event.type == KEYUP and event.key == K_w and keypress[K_LMETA]) ): self.is_running = False if OPTIONS["on_close"]: OPTIONS["on_close"]() if self.is_animation_running: if animation_timer >= delay: animation_timer = 0 values = callback() if values: self.generate_vertices(*values) did_change = True else: self.is_animation_running = None else: animation_timer += delta_time if not is_focused and OPTIONS["on_update"]: OPTIONS["on_update"]() keypress = pygame.key.get_pressed() if is_focused: if keypress[K_w] or keypress[K_UP]: self.camera_pos += speed * self.camera_front did_change = True if keypress[K_s] or keypress[K_DOWN]: self.camera_pos -= speed * self.camera_front did_change = True if keypress[K_d] or keypress[K_RIGHT]: self.camera_pos += speed * camera_right did_change = True if keypress[K_a] or keypress[K_LEFT]: self.camera_pos -= speed * camera_right did_change = True if did_change: self.view = glm.lookAt(self.camera_pos, self.camera_pos + self.camera_front, self.camera_up) mvp = self.projection * self.view * self.model glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if len(self.points) > 0: glUseProgram(self.shader["points"].program) glUniformMatrix4fv(self.shader["points"]["mvp"], 1, GL_FALSE, glm.value_ptr(mvp)) glBindVertexArray(self.point_vao) glDrawArrays(GL_POINTS, 0, int(len(self.points)/3)) if len(self.lines) > 0: glUseProgram(self.shader["lines"].program) glUniformMatrix4fv(self.shader["lines"]["mvp"], 1, GL_FALSE, glm.value_ptr(mvp)) glBindVertexArray(self.line_vao) for i in range(0, len(self.line_offset)): glDrawArrays(GL_LINE_STRIP, *self.line_offset[i]) if len(self.quads) > 0: glUseProgram(self.shader["quads"].program) glUniformMatrix4fv(self.shader["quads"]["model"], 1, GL_FALSE, glm.value_ptr(self.model)) glUniformMatrix4fv(self.shader["quads"]["view"], 1, GL_FALSE, glm.value_ptr(self.view)) glUniformMatrix4fv(self.shader["quads"]["projection"], 1, GL_FALSE, glm.value_ptr(self.projection)) glUniform3f(self.shader["quads"]["lightPos"], *self.light_pos.xyz) glBindVertexArray(self.quad_vao) for i in range(0, len(self.quad_offset)): glDrawArrays(GL_TRIANGLE_STRIP, *self.quad_offset[i]) if OPTIONS["show_grid"]: glUseProgram(self.shader["grid"].program) glUniformMatrix4fv(self.shader["grid"]["model"], 1, GL_FALSE, glm.value_ptr(self.model)) glUniformMatrix4fv(self.shader["grid"]["view"], 1, GL_FALSE, glm.value_ptr(self.view)) glUniformMatrix4fv(self.shader["grid"]["proj"], 1, GL_FALSE, glm.value_ptr(self.projection)) glUniform1f(self.shader["grid"]["zoom"], self.zoom) glUniform3f(self.shader["grid"]["cameraPos"], *self.camera_pos.xyz) glBindVertexArray(self.grid_vao) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) pygame.display.flip() did_change = False win_w, win_h = Window.from_display_module().position OPTIONS["window_pos"] = str(win_w) + ", " + str(win_h) os.environ["SDL_VIDEO_WINDOW_POS"] = OPTIONS["window_pos"] pygame.display.quit()
def createPlayground(): clearPlayground() i = 0 xValue = 0 yValue = -1 zValue = 0 while i < 15: if xValue <= 2: tile = GameObject( Transform( position=glm.vec3(xValue, yValue, zValue), scale=glm.vec3(0.5), parent=parent_point.transform, ), deepcopy(tiles_obj), ReactiveAABB.copy_from(tiles_obj.AABB)) # tile2 = GameObject( # Transform( # position=glm.vec3(xValue, yValue, zValue + 1), # scale=glm.vec3(0.5), # parent=parent_point.transform, # ), # deepcopy(tiles_obj), # ReactiveAABB.copy_from(tiles_obj.AABB) # ) xValue = xValue + 1 elif xValue == 3 and zValue >= -2: tile = GameObject( Transform( position=glm.vec3(xValue, yValue, zValue), scale=glm.vec3(0.5), parent=parent_point.transform, ), deepcopy(tiles_obj), ReactiveAABB.copy_from(tiles_obj.AABB)) # tile2 = GameObject( # Transform( # position=glm.vec3(xValue - 1, yValue, zValue), # scale=glm.vec3(0.5), # parent=parent_point.transform, # ), # deepcopy(tiles_obj), # ReactiveAABB.copy_from(tiles_obj.AABB) # ) zValue = zValue - 1 elif xValue <= 5 and zValue == -3: tile = GameObject( Transform( position=glm.vec3(xValue, yValue, zValue), scale=glm.vec3(0.5), parent=parent_point.transform, ), deepcopy(tiles_obj), ReactiveAABB.copy_from(tiles_obj.AABB), ) xValue = xValue + 1 elif xValue == 6 and yValue <= 1: tile = GameObject( Transform(position=glm.vec3(xValue - 0.5, yValue + 0.5, zValue), scale=glm.vec3(0.5), parent=parent_point.transform, rotation=glm.quat(glm.vec3(0, 0, glm.radians(90)))), deepcopy(tiles_obj), ReactiveAABB.copy_from(tiles_obj.AABB)) yValue = yValue + 1 elif zValue <= -1 and yValue == 2: tile = GameObject( Transform(position=glm.vec3(xValue - 0.5, yValue + 0.5, zValue), scale=glm.vec3(0.5), parent=parent_point.transform, rotation=glm.quat(glm.vec3(0, 0, glm.radians(90)))), deepcopy(tiles_obj), ReactiveAABB.copy_from(tiles_obj.AABB)) zValue = zValue + 1 # elif xValue <= 5 and zValue == -3: # tile = GameObject(position=glm.vec3(xValue, yValue, zValue), scale=glm.vec3(0.5, 0.05, 0.5)) # xValue = xValue + 1 texture = randomTexture() tiles_obj.meshes[0].material.map_Ka = texture tiles_obj.meshes[0].material.map_Kd = texture tile.join_set(playground) #tile2.join_set(playground) tilesList.append(tile) #tilesList.append(tile2) i += 1
def transform(self, pos): """Transforms vec3 position to a direction matching the current transformation""" dir = glm.inverse(self.matrix) * glm.vec4(pos, 1) return glm.vec3(dir)
start = time.time() import numpy numpy_time = time.time() - start results.append(("import", numpy_time, glm_time)) print("\nTime taken:\n\tPyGLM: {:.2f}s\n\tNumPy: {:.2f}s\n".format(glm_time, numpy_time)) print("{}.\n".format(get_evaluation_string(numpy_time, glm_time))) """ test_func("3 component vector creation", glm.vec3, [0], numpy.zeros, [(3, ), numpy.float32]) test_func("3 component vector creation with custom components", glm.vec3, [1, 2, 3], numpy.array, [(1, 2, 3), numpy.float32]) test_func("dot product", glm.dot, [glm.vec3(), glm.vec3()], numpy.dot, [numpy.zeros((3, )), numpy.zeros((3, ))]) repititions = 100_000 test_func("cross product", glm.cross, [glm.vec3(1), glm.vec3(1, 2, 3)], numpy.cross, [ numpy.array((1, 1, 1), numpy.float32), numpy.array((1, 2, 3), numpy.float32) ]) test_func("L2-Norm of 3 component vector", glm.l2Norm, [glm.vec3(1, 2, 3)], numpy.linalg.norm, [numpy.array((1, 2, 3), numpy.float32)]) repititions = 1_000_000 test_func("4x4 matrix creation", glm.mat4, [0], numpy.zeros, [(4, 4), numpy.float32]) test_func("4x4 identity matrix creation", glm.identity, [glm.mat4], numpy.identity, [4, numpy.float32]) test_func("4x4 matrix transposition", glm.transpose, [glm.mat4()],
def transform_direction(self, dir): """Transforms vec3 direction to a direction matching the current transformation""" dir = glm.inverse(self.matrix) * glm.vec4(dir, 0) return glm.vec3(dir)
def renderGL(self): """opengl render method""" # get the time in seconds t = glfwGetTime() # use the transform shader program glUseProgram(self.__tshaderProgram) # set the uniforms glUniform3fv(self.__centerLocation, 3, self.__center) glUniform1fv(self.__radiusLocation, 3, self.__radius) glUniform3fv(self.__gLocation, 1, self.__g) glUniform1f(self.__dtLocation, self.__dt) glUniform1f(self.__bounceLocation, self.__bounce) glUniform1i(self.__seedLocation, randint(0, 0x7fff)) # bind the current vao glBindVertexArray(self.__vao[(self.__currentBuffer + 1) % self.__bufferCount]) # bind transform feedback target glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, self.__vbo[self.__currentBuffer]) glEnable(GL_RASTERIZER_DISCARD) # perform transform feedback glBeginTransformFeedback(GL_POINTS) glDrawArrays(GL_POINTS, 0, self.__particles) glEndTransformFeedback() glDisable(GL_RASTERIZER_DISCARD) # clear first glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # use the shader program glUseProgram(self.__shaderProgram) # calculate ViewProjection matrix projection = glm.perspective(90.0, 4.0 / 3.0, .1, 100.0) projection = np.array(projection, dtype=np.float32) # translate the world/view position view = glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, -30.0)) # make the camera rotate around the origin view = glm.rotate(view, 30.0, glm.vec3(1.0, 0.0, 0.0)) view = glm.rotate(view, -22.5 * t, glm.vec3(0.0, 1.0, 0.0)) view = np.array(view, dtype=np.float32) # set the uniform glUniformMatrix4fv(self.__viewLocation, 1, GL_FALSE, view) glUniformMatrix4fv(self.__projLocation, 1, GL_FALSE, projection) # bind the vao glBindVertexArray(self.__vao[self.__currentBuffer]) # draw glDrawArrays(GL_POINTS, 0, self.__particles) glBindVertexArray(0) glUseProgram(0) # advance buffer index self.__currentBuffer = (self.__currentBuffer + 1) % self.__bufferCount
def init(debug_mode=False, config=None, edit_mode=False): """ Initializes the :class:`~diskovery_instance.DkInstance` and :class:`~diskovery_entity_manager.EntityManager` objects used in this module. :param debug_mode: Whether or not the :class:`~diskovery_instance.DkInstance` should be created with Vulkan Validation Layers :param config: An optional dictionary of configuration values to set up the Diskovery instance """ global _dk, _scene, _camera, _input pygame.init() _dk = DkInstance(debug_mode) _scene = EntityManager(_dk) pygame.joystick.init() if config != None and 'input' in config: _input = InputManager(config['input']) else: _input = InputManager("maininput.in") r = Renderer(_dk, _dk.image_data['msaa_samples'], _dk.sc_image_views, edit_mode) _scene.add_renderer(r) add_class(Entity, "Entity") add_class(RenderedEntity, "RenderedEntity") add_class(AnimatedEntity, "AnimatedEntity") add_class(Camera, "Camera") add_class(Light, "Light") add_class(Terrain, "Terrain") custom_module = 'diskovery_entities' external_classes = importlib.import_module(custom_module) for x in dir(external_classes): obj = getattr(external_classes, x) if inspect.isclass(obj) and inspect.getmodule( obj).__name__ == custom_module: add_class(obj, obj.__name__) cam_pos = glm.vec3(0, 0, -5) cam_rot = glm.vec3() fov = glm.radians(60) draw_distance = 1000 aspect_ratio = _dk.image_data['extent'].width / _dk.image_data[ 'extent'].height if config != None: if 'cam_pos' in config: cam_pos = glm.vec3(config['cam_pos']) if 'cam_rot' in config: cam_rot = glm.vec3(config['cam_rot']) if 'fov' in config: fov = glm.radians(config['fov']) if 'draw_distance' in config: draw_distance = config['draw_distance'] if 'width' in config and 'height' in config: aspect_ratio = config['width'] / config['height'] if 'bg_color' in config: _dk.bg_color = config['bg_color'] _camera = Camera(cam_pos, cam_rot, fov, draw_distance, aspect_ratio) _scene.add_entity(_camera, "Camera")
def initGL(self): """opengl initialization""" # load shaders vertexShader = self.shaderFromFile(GL_VERTEX_SHADER, self.__vertexShader) geomShader = self.shaderFromFile(GL_GEOMETRY_SHADER, self.__geomShader) fragmentShader = self.shaderFromFile(GL_FRAGMENT_SHADER, self.__fragmentShader) self.__shaderProgram = shaders.compileProgram(vertexShader, geomShader, fragmentShader) if not self.__shaderProgram: self.close() # obtain location of projection uniform self.__viewLocation = glGetUniformLocation(self.__shaderProgram, 'View') self.__projLocation = glGetUniformLocation(self.__shaderProgram, 'Projection') # transform feedback shader and program tfShader = self.shaderFromFile(GL_VERTEX_SHADER, self.__tfShader) self.__tshaderProgram = glCreateProgram() glAttachShader(self.__tshaderProgram, tfShader) # specify transform feedback output varyings = (ctypes.c_char_p * 2)("outposition", "outvelocity") c_array = ctypes.cast(varyings, ctypes.POINTER(ctypes.POINTER(ctypes.c_char))) glTransformFeedbackVaryings(self.__tshaderProgram, len(varyings), c_array, GL_INTERLEAVED_ATTRIBS) glLinkProgram(self.__tshaderProgram) self.__centerLocation = glGetUniformLocation(self.__tshaderProgram, 'center') self.__radiusLocation = glGetUniformLocation(self.__tshaderProgram, 'radius') self.__gLocation = glGetUniformLocation(self.__tshaderProgram, 'g') self.__dtLocation = glGetUniformLocation(self.__tshaderProgram, 'dt') self.__bounceLocation = glGetUniformLocation(self.__tshaderProgram, 'bounce') self.__seedLocation = glGetUniformLocation(self.__tshaderProgram, 'seed') # randomly place particles in a cube vertexData = [] for i in xrange(self.__particles): # initial position pos = glm.vec3(.5 - rand(), .5 - rand(), .5 - rand()) vertexData.append(glm.vec3(0.0, 20.0, 0.0) + 5.0 * pos) # initial velocity vertexData.append(glm.vec3(0.0, 0.0, 0.0)) # generate vbos and vaos self.__vao = glGenVertexArrays(self.__bufferCount) self.__vbo = glGenBuffers(self.__bufferCount) vertexData = np.array(vertexData, dtype=np.float32) for i in range(self.__bufferCount): glBindVertexArray(self.__vao[i]) glBindBuffer(GL_ARRAY_BUFFER, self.__vbo[i]) # fill with initial data glBufferData(GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, GL_STATIC_DRAW) # set up generic attrib pointers glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * 4, None) # set up generic attrib pointers glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * 4, ctypes.c_void_p(3 * 4)) glBindVertexArray(0) # we are blending so no depth testing glDisable(GL_DEPTH_TEST) # enable blending glEnable(GL_BLEND) # and set the blend function to result = 1 * source + 1 * destination glBlendFunc(GL_ONE, GL_ONE) # define sphere for the particles to bounce off center = [] radius = [] center.append((0.0, 12.0, 1.0)) radius.append(3) center.append((-3.0, 0.0, 0.0)) radius.append(7) center.append((5.0, -10.0, 0.0)) radius.append(12) self.__center = np.array(center, dtype=np.float32) self.__radius = np.array(radius, dtype=np.float32) # physical parameters self.__dt = 1.0 / 60.0 self.__g = np.array((0.0, -9.81, 0.0), dtype=np.float32) self.__bounce = 1.2 self.__currentBuffer = 0
def __init__(self, position=None, rotation=None): self.position = glm.vec3(position) if position != None else glm.vec3() self.rotation = glm.vec3(rotation) if rotation != None else glm.vec3() self.parent = None self.children = []