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 __updateCameraVectors(self): front = np.array([0, 0, 0], np.float32) front[0] = math.cos(math.radians(self.yaw)) * math.cos(math.radians(self.pitch)) front[1] = math.sin(math.radians(self.pitch)) front[2] = math.sin(math.radians(self.yaw)) * math.cos(math.radians(self.pitch)) self.front = glm.normalize(front) self.right = glm.normalize(np.cross(self.front, self.worldUp)) self.up = glm.normalize(np.cross(self.right, self.front))
def paintGL(self): currentTime = self.__timer.elapsed() / 1000.0 self.__deltaTime = currentTime - self.__lastTime self.__lastTime = currentTime # clear the colorbuffer glClearColor(0.1, 0.1, 0.1, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # configure view/projection matrices glUseProgram(self.__shader) view = self.camera.viewMatrix projection = glm.perspective(self.camera.zoom, float(self.width())/self.height(), 0.1, 100.0) glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'view'), 1, GL_FALSE, view) glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'projection'), 1, GL_FALSE, projection) # render normal-mapped quad rotVec = glm.normalize(np.array([1.0, 0.0, 1.0], np.float32)) model = glm.rotate(np.identity(4, np.float32), currentTime * -10.0, rotVec[0], rotVec[1], rotVec[2]) glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'model'), 1, GL_FALSE, model) glUniform3fv(glGetUniformLocation(self.__shader, 'lightPos'), 1, self.lightPos) glUniform3fv(glGetUniformLocation(self.__shader, 'viewPos'), 1, self.camera.position) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.diffuseMap) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, self.normalMap) self.renderQuad() # render light source (simply re-renders a smaller plane at the light's position for debugging/visualization) # model = glm.scale(np.identity(4, np.float32), 0.1, 0.1, 0.1) # model = glm.translate(model, self.lightPos[0], self.lightPos[1], self.lightPos[2]) # glUniformMatrix4fv(glGetUniformLocation(self.__shader, 'model'), 1, GL_FALSE, model) # self.renderQuad() glUseProgram(0)
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 move_camera2(): global camera_pos global camera_front global keys global delta_time camera_speed = 3. * delta_time if keys[GLFW_KEY_W]: camera_pos += camera_speed * camera_front if keys[GLFW_KEY_S]: camera_pos -= camera_speed * camera_front if keys[GLFW_KEY_A]: camera_pos -= glm.normalize(np.cross(camera_front, world_up)) * camera_speed if keys[GLFW_KEY_D]: camera_pos += glm.normalize(np.cross(camera_front, world_up)) * camera_speed
def alter_heights(self, function): keys_to_delete = [] keys_to_add = [] for key in self.vert_dictionary: temp_vert = key keys_to_delete.append(temp_vert) new_vert = glm.vec3(key[0], function(), key[2]) temp_key_value = { "key": new_vert, "values": { "normals": [], "indices": self.vert_dictionary[key]["indices"] } } temp_normal = glm.vec3(0, 0, 0) for norm in self.vert_dictionary[key]["normals"]: changed_normal = glm.vec3(norm[0], norm[1] + new_vert[1], norm[2]) temp_key_value["values"]["normals"].append(changed_normal) temp_normal += changed_normal temp_normal = glm.normalize(temp_normal) for index in self.vert_dictionary[key]["indices"]: actual_index = index * 3 self._vertices[actual_index] = new_vert[0] self._vertices[actual_index + 1] = new_vert[1] self._vertices[actual_index + 2] = new_vert[2] self._normals[actual_index] = temp_normal[0] self._normals[actual_index + 1] = temp_normal[1] self._normals[actual_index + 2] = temp_normal[2] keys_to_add.append(temp_key_value) for key in keys_to_add: self.vert_dictionary[key["key"]] = { "normals": key["values"]["normals"], "indices": key["values"]["indices"] } for key in keys_to_delete: del self.vert_dictionary[key] self.update_buffers()
def get_normals(self): normals = np.array([]) normal_arrows = [] edge_normals = [] # 3 floats per vertex, 3 vertices per triangle for i in range(len(self.vertices) // 9): P = [ self.vertices[9 * i], self.vertices[9 * i + 1], self.vertices[9 * i + 2] ] Q = [ self.vertices[9 * i + 3], self.vertices[9 * i + 4], self.vertices[9 * i + 5] ] R = [ self.vertices[9 * i + 6], self.vertices[9 * i + 7], self.vertices[9 * i + 8] ] # For P, Q, R, defined counter-clockwise, glm.cross(R-Q, P-Q) RQ = glm.vec3(self.vertices[9 * i + 6] - self.vertices[9 * i + 3], self.vertices[9 * i + 7] - self.vertices[9 * i + 4], self.vertices[9 * i + 8] - self.vertices[9 * i + 5]) PQ = glm.vec3(self.vertices[9 * i] - self.vertices[9 * i + 3], self.vertices[9 * i + 1] - self.vertices[9 * i + 4], self.vertices[9 * i + 2] - self.vertices[9 * i + 5]) PR = glm.vec3(self.vertices[9 * i] - self.vertices[9 * i + 6], self.vertices[9 * i + 1] - self.vertices[9 * i + 7], self.vertices[9 * i + 2] - self.vertices[9 * i + 8]) normal = glm.normalize(glm.cross(RQ, PQ)) normal = self.generate_normal_arrows(normal, P, Q, R, normal_arrows) self.generate_edge_normals(P, PQ, PR, Q, R, RQ, edge_normals, normal) # Insert once for each vertex normals = np.append(normals, [normal.x, normal.y, normal.z] * 3) return normals.astype( np.float32), np.array(normal_arrows), np.array(edge_normals)
def _init_cylinder_mat4(center: glm.dvec3, direction: glm.dvec3, radius: float = 0.02): init_vector = glm.vec3(0, 1, 0) length = glm.length(direction) angle = _angle_between(direction, init_vector) translate_vector = direction / 2 + center model = glm.translate(glm.mat4(1.), translate_vector) if angle: model = glm.rotate(model, angle, glm.cross(init_vector, glm.normalize(direction))) model = glm.scale(model, glm.vec3(radius, length, radius)) return model
def create_noise(noise_size): noise = numpy.empty((noise_size * noise_size, 3), dtype=numpy.float32) for i1 in range(2): for i2 in range(noise_size * noise_size // 2): iang = 2 * i2 + i1 angle = 2.0 * math.pi * iang / noise_size i = i1 * noise_size // 2 + i2 v = glm.normalize(glm.vec3(math.cos(angle), math.sin(angle), 0)) noise[i, :] = [*v] noise_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, noise_texture) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16_SNORM, noise_size, noise_size, 0, GL_RGB, GL_FLOAT, noise) glPixelStorei(GL_UNPACK_ALIGNMENT, 4) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) return noise_texture
def __init__(self): self.zoom = 1 self.model = glm.mat4(1.0) self.camera_pos = glm.vec3(0, 10, 7) self.camera_front = glm.normalize(glm.vec3(0, -1, -1)) self.camera_up = glm.vec3(0, 1, 0) self.view = glm.lookAt(self.camera_pos, self.camera_pos * self.camera_front, self.camera_up) self.projection = glm.perspective( glm.radians(45), OPTIONS["size"][0] / OPTIONS["size"][1], 0.1, 1000) self.model = glm.rotate(self.model, glm.radians(-90.0), glm.vec3(0, 1, 0)) self.light_pos = glm.vec3(10, 10, 10) self.is_running = False self.is_animation_running = False
def update(self, dt): if self.aim is None: self.aim = self.find_aim() self.t = 0 self.initial_vel = vec3(self.velocity) if self.aim is None: return super().update(dt) if self.aim.position.z > self.position.z: self.aim = None return super().update(dt) self.t = clamp(self.t + dt * 5, 0, 1) vel = self.speed * normalize(self.aim.position - self.position) self.velocity = vel * self.t + self.initial_vel * (1 - self.t) return super().update(dt)
def _process_input(self, _delta, world): (l, _m, _r) = pygame.mouse.get_pressed() (x, y) = pygame.mouse.get_pos() if (l): self.is_pressed = True # Relative mouse position self.possible_velocity = (self.position - glm.vec2(x, y)) * self.force_per_px self._recalc_prediciton(world) elif (self.is_pressed): self.is_pressed = False self.last_mouse_pos = glm.vec2() # world.score_system.decrement_score(1) self.velocity = glm.normalize(self.possible_velocity) self.distance = glm.length(self.possible_velocity) * 1.5
def get_cylinder_vertices( cylinder: CylinderObject3D, sides: int) -> Tuple[glm.array, glm.array, glm.array]: """Get vertices, normals, and indices for a cylinder object. Args: cylinder: A CylinderObject3D. sides: An int representing the number of sides per circle. """ # faster way to calculate points along a circle theta = 2.0 * math.pi / sides tan_factor = tan(theta) rad_factor = cos(theta) x = vec3(cylinder.radius, 0.0, 0.0) vertices = [] for i in range(sides): vertices.append(vec3(0.0, 0.0, 0.0) + x) vertices.append(vec3(0.0, 0.0, cylinder.height) + x) delta = vec3(x[1] * tan_factor, -x[0] * tan_factor, 0.0) x = (x + delta) * rad_factor vertices.append(vec3(0.0, 0.0, 0.0)) vertices.append(vec3(0.0, 0.0, cylinder.height)) normals = [] for i in range(len(vertices)): n = vec3(vertices[i].x, vertices[i].y, 0.0) * mat3( cylinder.trans_matrix) normals.append(glm.normalize(n)) vertices[i] = vec3(vec4(vertices[i], 1.0) * cylinder.trans_matrix) normals[-2] = vec3(0.0, 0.0, -1.0) * mat3(cylinder.trans_matrix) normals[-1] = vec3(0.0, 0.0, 1.0) * mat3(cylinder.trans_matrix) indices = [] for i in range(0, sides * 2, 2): i2 = (i + 2) % (2 * sides) i3 = (i + 3) % (2 * sides) indices.extend((u32vec3(i, i + 1, i2), u32vec3(i + 1, i3, i2), u32vec3(2 * sides, i, i2), u32vec3(2 * sides + 1, i3, i + 1))) return glm.array(vertices), glm.array(normals), glm.array(indices)
def __init__(self): self._cam_target = glm.vec3(0, 0, 0) self._pitch = 0 self._yaw = 0 self._cam_unit_pos = None self._update_cam_unit_pos() self._cam_distance = 3 self._cam_direction = glm.normalize(self.cam_pos - self._cam_target) self._cam_up = glm.vec3(0, 1, 0) self._min_distance = 0.1 self._view_matrix = self._calc_view_matrix() self._should_update: bool = False self._last_x = 0 self._last_y = 0 self.rotation_speed: float = 5 self.autorotate_speed: float = 0.5 self.wheel_speed: float = 0.5
def update(self, entity, dt): if entity.ai_charge_time > 0: entity.ai_charge_time -= dt player = entity.app.state.player to_player = player.position - entity.position if to_player.z > 0: # Butterfly is behind the player return entity.play_sound("squeak.wav") entity.velocity = glm.normalize(to_player) * 30 * self.aggressivity entity.ia_next_charge = self.random_charge() else: entity.ia_next_charge -= dt entity.velocity = vec3(0) if entity.ia_next_charge < 0: entity.ai_charge_time = self.aggressivity**2 / 15 + 1
def key_event(window,key,scancode,action,mods): global cameraPos, cameraFront, cameraUp global wireframe, scale, cameraSpeed, sensitivity global lightOn, intensity # quit simulation with <ESC> or Q if (key == glfw.KEY_Q or key == glfw.KEY_ESCAPE) and action == glfw.PRESS: glfw.set_window_should_close(window, True) if key == glfw.KEY_W and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos + cameraSpeed * cameraFront): cameraPos += cameraSpeed * cameraFront else: cameraPos -= cameraSpeed * cameraFront if key == glfw.KEY_S and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos - cameraSpeed * cameraFront): cameraPos -= cameraSpeed * cameraFront else: cameraPos += cameraSpeed * cameraFront if key == glfw.KEY_A and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos - glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed): cameraPos -= glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed else: cameraPos += glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed if key == glfw.KEY_D and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos + glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed): cameraPos += glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed else: cameraPos -= glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed if key == glfw.KEY_O and action == glfw.PRESS: wireframe = not wireframe if key == glfw.KEY_L and action == glfw.PRESS: loc_light = glGetUniformLocation(program, "lightColor2") if lightOn: glUniform3f(loc_light, 0.0, 0.0, 0.0) else: glUniform3f(loc_light, 255.0/255.0, 147.0/255.0, 41.0/255.0) lightOn = not lightOn if key == glfw.KEY_U and action == glfw.PRESS: if intensity + 0.05 < 1.0: intensity += 0.05 loc_light = glGetUniformLocation(program, "lightColor") glUniform3f(loc_light, (201.0/255.0) * intensity, (226.0/255.0) * intensity, (255.0/255.0) * intensity ) if key == glfw.KEY_P and action == glfw.PRESS: if intensity - 0.05 > 0.0: intensity -= 0.05 loc_light = glGetUniformLocation(program, "lightColor") glUniform3f(loc_light, (201.0/255.0) * intensity, (226.0/255.0) * intensity, (255.0/255.0) * intensity )
def generate_ray(self, pixel_x, pixel_y, image_width, image_height): image_aspect_ratio = float(image_width) / float(image_height) alpha = 2.0 * math.atan(1.0 / (2.0 * self.focal_length)) s_1 = random.uniform(0, 1) s_2 = random.uniform(0, 1) pixel_ndc_x = (pixel_x + s_1) / image_width pixel_ndc_y = (pixel_y + s_2) / image_height pixel_screen_x = 2.0 * pixel_ndc_x - 1.0 pixel_screen_y = 2.0 * pixel_ndc_y - 1.0 pixel_camera_x = pixel_screen_x * self.width * image_aspect_ratio * math.tan( alpha / 2) pixel_camera_y = pixel_screen_y * self.height * math.tan(alpha / 2) camera_point = glm.vec3(pixel_camera_x, pixel_camera_y, -1.0) return Ray(self.position, glm.normalize(-camera_point))
def __init__(self, start: vec3, end: vec3, radius: float): super().__init__() self.start: vec3 = vec3(start) self.end: vec3 = vec3(end) self.radius: float = radius self.height: float = glm.distance(self.start, self.end) self.normal: vec3 = glm.normalize(self.end - self.start) self.b1: vec3 self.b2: vec3 self.b1, self.b2 = orthonormal_basis_of(self.normal) # calculate rotation matrix for cylinder self.trans_matrix: mat4 = glm.orientation(vec3(0.0, 0.0, 1.0), self.normal) # add translation to matrix self.trans_matrix[0][3] = start.x self.trans_matrix[1][3] = start.y self.trans_matrix[2][3] = start.z # get corners of OBB points = glm.array( vec3(self.radius, self.radius, 0.0), vec3(-self.radius, self.radius, 0.0), vec3(self.radius, -self.radius, 0.0), vec3(-self.radius, -self.radius, 0.0), vec3(self.radius, self.radius, self.height), vec3(-self.radius, self.radius, self.height), vec3(self.radius, -self.radius, self.height), vec3(-self.radius, -self.radius, self.height)) # inflate OBB into AABB # TODO: # BoundingBox _should_ have default values - we shouldn't have to # initialize with inf and -inf manually. but if we do that, # it seems to initialize with other BoundingBox's values. # Something weird is going on with (I presume) glm pointers? self._bbox = BoundingBox(vec3(inf), vec3(-inf)) for v in points: self._bbox.vec3_extend(vec3(vec4(v, 1.0) * self.trans_matrix))
def update(self, bot, input): seenBotInfo = bot.sight.getSeenBotInfo(self.seenBotEntity) if seenBotInfo.transform == None: return destination = (seenBotInfo.transform.position[0] + self.randomAimOffset[0], seenBotInfo.transform.position[1] + self.randomAimOffset[1]) vector = glm.vec2(destination[0] - bot.transform.position[0], destination[1] - bot.transform.position[1]) direction = vector if glm.length(vector) > 0.0: direction = glm.normalize(vector) bot.agent.lookAt((direction.x, direction.y)) if self.timer.read() < bot.shootDelay: return if bot.agent.finishedRotate == True: input.shootSecondaryWeapon()
def update(self, delta, world): self.delta_total += delta target = self._get_target() difference = target - self.position distance = glm.length(difference) direction = glm.normalize(difference) # Move in steps to prevent clipping while (distance > 0.0): travel = 7.5 if (distance < travel): travel = distance motion = direction * travel _, entities = world.is_colliding(self, motion, True) for _side, dis, e in entities: e.set_position(e.position + dis * 1.01) self.set_position(self.position + motion) distance -= travel
def keyboard_interaction(direction): # modifies the direction via keyboard input if b'w' in pressed_keys: direction += glm.vec3(0, 0, 2) if b's' in pressed_keys: direction -= glm.vec3(0, 0, 2) if b'd' in pressed_keys: direction -= glm.vec3(2, 0, 0) if b'a' in pressed_keys: direction += glm.vec3(2, 0, 0) if b'e' in pressed_keys: direction += glm.vec3(0, 2, 0) if b'q' in pressed_keys: direction -= glm.vec3(0, 2, 0) # do the following if one of these keys are pressed if len(pressed_keys.intersection((b'w', b'a', b's', b'd'))) != 0: # set the speed of the player velocity = 8.0 # set the direction of the player direction = glm.normalize(direction) player.velocity = direction * velocity
def mouse_event(window, xpos, ypos): global cameraFront, yaw, pitch, lastX, lastY, sensitivity xoffset = xpos - lastX yoffset = lastY - ypos lastX = xpos lastY = ypos xoffset *= sensitivity yoffset *= sensitivity yaw += xoffset; pitch += yoffset; #if pitch >= 90.0: pitch = 90.0 #if pitch <= -90.0: pitch = -90.0 front = glm.vec3() front.x = math.cos(glm.radians(yaw)) * math.cos(glm.radians(pitch)) front.y = math.sin(glm.radians(pitch)) front.z = math.sin(glm.radians(yaw)) * math.cos(glm.radians(pitch)) cameraFront = glm.normalize(front)
def __init__(self, direction, radian, color, intensity): direction = glm.normalize(glm.vec3(direction)) self.m_radian = radian self.d_dir_radian = vki.SVVec4(glm.vec4(direction, radian)) self.d_intensity = Spectrum(glm.vec3(color) * intensity) self.m_cptr = SVCombine_Create( { 'dir_radian': self.d_dir_radian, 'intensity': self.d_intensity }, ''' Spectrum sample_l(in Comb_#hash# self, in vec3 ip, inout RNGState state, inout vec3 dirToLight, inout float distance, inout float pdfw) { vec3 dir = self.dir_radian.xyz; float factor = 1.0 - cos(self.dir_radian.w); float r1 = rand01(state); float r2 = rand01(state) * radians(360.0); vec3 a, b; if (abs(dir.x)>0.8) a = vec3(0.0, 1.0, 0.0); else a = vec3(1.0, 0.0, 0.0); a = normalize(cross(a, dir)); b = cross(a, dir); float v_z = 1.0 - r1 * factor; float v_xy = sqrt(1.0 - v_z*v_z); float v_x = v_xy * cos(r2); float v_y = v_xy * sin(r2); dirToLight = v_z*dir + a*v_x + b*v_y; distance = -1.0; pdfw = 1.0/(radians(360.0)*factor); return self.intensity; } ''')
def intersect(self, my_ray, inter_rec): eo = self.center - my_ray.origin v = glm.dot(eo, my_ray.direction) disc = (self.radius * self.radius) - (glm.dot(eo, eo) - (v * v)) if disc < 0.0: return False else: d = sqrt(disc) t1 = v - d t2 = v + d if t1 > 0.00001: inter_rec.t = t1 else: inter_rec.t = t2 inter_rec.position = my_ray.origin + inter_rec.t * my_ray.direction inter_rec.normal = glm.normalize(inter_rec.position - self.center) inter_rec.material = self.material return True
def throw_fork(index): joke_x = obstacle_objects[index].transform.position.x joke_y = obstacle_objects[index].transform.position.y joke_z = obstacle_objects[index].transform.position.z starting_position = glm.vec3(joke_x, joke_y, joke_z) fork_object = GameObject( Transform( position=starting_position, scale=glm.vec3(0.3), ), deepcopy(primitive_objs["fork"]), ReactiveAABB.copy_from(primitive_objs["fork"].AABB), ) fork_objects.append(fork_object) fork_object.join_set(collision_testers) diffVec = mosquito_Object.transform.position - starting_position total = diffVec.x**2 + diffVec.y**2 + diffVec.z**2 total = total**(1 / 2.0) distanceForIndex = 0 if total <= 3: distanceForIndex = 1 elif 3 < total <= 6: distanceForIndex = 2 elif 6 < total <= 9: distanceForIndex = 3 elif 9 < total <= 12: distanceForIndex = 4 elif 12 < total <= 15: distanceForIndex = 5 target_position = mosquito_Object.transform.position + glm.vec3( mosquito_Object.velocity.x * distanceForIndex, mosquito_Object.velocity.y * distanceForIndex, mosquito_Object.velocity.z * distanceForIndex) travel_position = target_position - starting_position return glm.normalize(travel_position / 100)
def _create_bumpmap(self, tilex, tiley): import glm normals = [] for y in range(self.tile_height): for x in range(self.tile_width): n = glm.normalize( glm.vec3( self._get_pixel(tilex, tiley, x + 1, y) - self._get_pixel(tilex, tiley, x - 1, y), self._get_pixel(tilex, tiley, x, y - 1) - self._get_pixel(tilex, tiley, x, y + 1), .5)) normals.append(n) for y in range(self.tile_height): for x in range(self.tile_width): ofs = ((tiley * self.tile_height + y) * self.tile_width * self.width + (tilex * self.tile_width) + x) * 4 n = normals[y * self.tile_width + x] # keep green as specular map self.values[ofs + 3] = self.values[ofs + 1] self.values[ofs] = n[0] self.values[ofs + 1] = n[1] self.values[ofs + 2] = n[2]
def RayTriangleCollisionCheck(self, ray, a, b, c): ray_direction = ray.direction ray_origin = ray.origin edge1 = b - a edge2 = c - a normal = glm.cross(edge1, edge2) det = -glm.dot(ray_direction, normal) invertDet = 1.0 / det AO = ray_origin - a DAO = glm.cross(AO, ray_direction) u = glm.dot(edge2, DAO) * invertDet v = -glm.dot(edge1, DAO) * invertDet ray_intersection_offset = glm.dot(AO, normal) * invertDet if det >= 1e-6 and ray_intersection_offset >= 0.0 and u >= 0.0 and v >= 0.0 and ( u + v) <= 1.0: intersection_point = ray.PointAtOffset(ray_intersection_offset) normal = glm.normalize(normal) intersection_result = IntersectionResult(self, intersection_point, ray_intersection_offset, normal) return intersection_result return None
def CheckDirection(target): compass = [ glm.vec2(0.0, 1.0), glm.vec2(1.0, 0.0), glm.vec2(0.0, -1.0), glm.vec2(-1.0, 0.0) ] direction = ["UP", "RIGHT", "DOWN", "LEFT"] maxVal = 0.0 bestVal = -1 index = 0 for value in compass: dotProduct = glm.dot(glm.normalize(target), value) if dotProduct > maxVal: maxVal = dotProduct bestVal = index index = index + 1 return direction[bestVal]
def decompose_matrix( mat: glm.mat4 ) -> Tuple[Optional[glm.vec3], Optional[glm.quat], Optional[glm.vec3]]: sx = glm.length(glm.vec3(mat[0])) sy = glm.length(glm.vec3(mat[1])) sz = glm.length(glm.vec3(mat[2])) if glm.determinant(mat) < 0.0: sx = -sx translation = glm.vec3(mat[3]) scale = glm.vec3(sx, sy, sz) inv_sx = 1.0 / sx inv_sy = 1.0 / sy inv_sz = 1.0 / sz rot_mat = copy.copy(mat) rot_mat[0][0] *= inv_sx rot_mat[0][1] *= inv_sx rot_mat[0][2] *= inv_sx rot_mat[1][0] *= inv_sy rot_mat[1][1] *= inv_sy rot_mat[1][2] *= inv_sy rot_mat[2][0] *= inv_sz rot_mat[2][1] *= inv_sz rot_mat[2][2] *= inv_sz rot_mat[3] = glm.vec4(0.0, 0.0, 0.0, 1.0) rotation = glm.normalize(glm.quat_cast(rot_mat)) if translation == glm.vec3(): translation = None if rotation == glm.quat(): rotation = None if scale == glm.vec3(): scale = None return (translation, rotation, scale)
def _wasd_movement(self, entity_id, speed, vertical_movement, vertical_speed): keys = pygame.key.get_pressed() velocity = self.world.component_for_entity(entity_id, com.Velocity) # WASD direction = glm.vec3() if keys[pygame.locals.K_w]: direction.y += 1 if keys[pygame.locals.K_s]: direction.y -= 1 if keys[pygame.locals.K_a]: direction.x += 1 if keys[pygame.locals.K_d]: direction.x -= 1 if glm.length(direction) > 0.001: new_v = glm.normalize(direction) * speed velocity.value.x = new_v.x velocity.value.y = new_v.y else: velocity.value.x = 0.0 velocity.value.y = 0.0 if vertical_movement: velocity.value.z = 0 if keys[pygame.locals.K_SPACE]: velocity.value.z += vertical_speed if keys[pygame.locals.K_LSHIFT]: velocity.value.z -= vertical_speed if keys[pygame.locals.K_p]: tra = self.world.component_for_entity(entity_id, com.Transformation) print( f"Transformation(Position: {tra.position}, Rotation: {tra.rotation})" )
def __init__(self, app, scene, parent, position, direction, damage=1, img=BULLET_IMAGE_PATH, speed=BULLET_SPEED, **kwargs): self.speed = speed velocity = normalize(direction) * speed super().__init__(app, scene, BULLET_IMAGE_PATH, position=position, velocity=velocity, life=SCREEN_DIST * FULL_FOG_DISTANCE * 1.2 / self.speed, **kwargs) self.damage = damage self.solid = True self.size.z = BULLET_SIZE # to prevent tunneling self.parent = parent # whoever shot the bullet
def key_event(window,key,scancode,action,mods): global cameraPos, cameraFront, cameraUp global wireframe, scale, cameraSpeed, sensitivity # quit simulation with <ESC> or Q if (key == glfw.KEY_Q or key == glfw.KEY_ESCAPE) and action == glfw.PRESS: glfw.set_window_should_close(window, True) if key == glfw.KEY_W and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos + cameraSpeed * cameraFront): cameraPos += cameraSpeed * cameraFront else: cameraPos -= cameraSpeed * cameraFront if key == glfw.KEY_S and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos - cameraSpeed * cameraFront): cameraPos -= cameraSpeed * cameraFront else: cameraPos += cameraSpeed * cameraFront if key == glfw.KEY_A and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos - glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed): cameraPos -= glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed else: cameraPos += glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed if key == glfw.KEY_D and (action == glfw.PRESS or action == glfw.REPEAT): if skybox(cameraPos + glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed): cameraPos += glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed else: cameraPos -= glm.normalize(glm.cross(cameraFront, cameraUp)) * cameraSpeed if key == glfw.KEY_P and action == glfw.PRESS: wireframe = not wireframe if key == 61 and mods == 0 and (action == glfw.PRESS or action == glfw.REPEAT): cameraSpeed += 0.01 if key == 45 and mods == 0 and (action == glfw.PRESS or action == glfw.REPEAT): cameraSpeed -= 0.01 if key == 61 and mods == 1 and (action == glfw.PRESS or action == glfw.REPEAT): sensitivity += 0.01 if key == 45 and mods == 1 and (action == glfw.PRESS or action == glfw.REPEAT): sensitivity -= 0.01
def __post_init__(self): self.normal = glm.normalize( glm.cross(self.p1 - self.p0, self.p2 - self.p0))
def main(): file_name = args.file print("Opening input CSV file: " + file_name) csv_file = open(file_name, "r") raw_lines = csv_file.read().splitlines() csv_file.close() csv_header = raw_lines[0] render_uavs = not args.graph_only use_mad = not args.skip_mad lines = [] colors = [] for line in raw_lines[1:]: #Parse raw lines and stick into lines parsed = parse_csv_line(line) if "color" in parsed: colors.append(parsed) else: parsed["pos"] = glm.vec3(parsed["x"], parsed["y"], parsed["z"]) lines.append(parsed) uavs = set() for line in lines: uavs.add(line["ip_address"]) print("Loaded {} uav's from file {}".format(len(uavs), file_name)) #Mapping between a uav id and the index of the latest line that assert's a uav's position that is before the current re-simulation's time #Used for interpolating each uav's position each frame uav_last_index = {} for uav in uavs: #Start searching for times at the start of the file uav_last_index[uav] = -0 uav_colors = {} for uav in uavs: #All UAV's are white by default uav_colors[uav] = glm.vec3(1, 1, 1) target_fps = 144 if render_uavs: pygame.init() display = (1440, 810) pygame.display.set_mode(display, DOUBLEBUF | OPENGL) clock = pygame.time.Clock() pygame.mouse.set_visible(False) pygame.event.set_grab(True) simulation_speed = 1 sensitivity = 0.75 * 1.0 / target_fps move_speed = 15.0 * 1.0 / target_fps gluPerspective(70, (display[0] / display[1]), 0.01, 500.0) #The position of the camera in 3d space camera_pos = glm.vec3(0.0, 0.0, 10.0) #A unit vector pointing where the camera is looking - relative to the position of the camera camera_forward = glm.vec3(0.0, 0.0, -1.0) keymap = {} for i in range(0, 256): keymap[i] = False else: last_time_print = 0 last_time = time.time() delta_time = 0.0 simulation_time = 0.0 exit_loop = False mad_times = [] mad_values = [] list_uavs = list(uavs) smallest = -1 for i in range(1, len(list_uavs)): best_num = int(list_uavs[smallest].split(".")[3]) current_num = int(list_uavs[i].split(".")[3]) if smallest == -1 or current_num < best_num: print("setting {} {}".format(current_num, best_num)) smallest = i print("best num " + str(list_uavs[smallest])) central = list_uavs[smallest] while True: if render_uavs: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_loop = True break camera_up = glm.vec3(0.0, 1.0, 0.0) camera_right = glm.cross(camera_forward, camera_up) if event.type == pygame.MOUSEMOTION: mouse_move = pygame.mouse.get_rel() camera_forward = glm.rotate(camera_forward, -mouse_move[0] * sensitivity, camera_up) camera_forward = glm.rotate(camera_forward, -mouse_move[1] * sensitivity, camera_right) #cameraLook.rotate( if event.type == pygame.KEYDOWN: keymap[event.scancode] = True if (event.scancode == pygame.KSCAN_ESCAPE): exit_loop = True break if event.type == pygame.KEYUP: keymap[event.scancode] = False if exit_loop: break camera_move = glm.vec3(0.0) if keymap[pygame.KSCAN_W]: camera_move += camera_forward if keymap[pygame.KSCAN_S]: camera_move -= camera_forward if keymap[pygame.KSCAN_A]: camera_move -= camera_right if keymap[pygame.KSCAN_D]: camera_move += camera_right if keymap[pygame.KSCAN_SPACE]: camera_move += camera_up if keymap[pygame.KSCAN_LSHIFT]: camera_move -= camera_up if glm.length(camera_move) > 0.0: camera_pos += glm.normalize(camera_move) * move_speed glPushMatrix() #glRotatef(1, 3, 1, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) gluLookAt(camera_pos.x, camera_pos.y, camera_pos.z, camera_pos.x + camera_forward.x, camera_pos.y + camera_forward.y, camera_pos.z + camera_forward.z, 0.0, 1.0, 0.0) for color in colors: if simulation_time > color["time"]: #Re compute the current colors using the current time uav_colors[color["ip_address"]] = color["color"] #Counts the number of UAV's that have no future position assignments uav_done_with_pos_cout = 0 for uav in uavs: #We need to find 2 lines in the list of all lines that tell us this uav's position before and after this re rendering's time step #We will the interpolate these two time points with the uav's position and our middle time in this rendering, allowing us #to have a smooth re-rendering of the swarm search_index = uav_last_index[uav] #We need to find the latest time a position was set in the csv file that is before _simulation_time_. #If this doesn't exist then we skip this uav since it doesn't have a position yet before_index = None after_index = None while True: if search_index >= len(lines): uav_done_with_pos_cout += 1 break data = lines[search_index] if data["ip_address"] == uav: #We found a line that talks about this uav if data["time"] <= simulation_time: before_index = search_index else: after_index = search_index break search_index += 1 if before_index != None: uav_last_index[uav] = before_index else: uav_last_index[uav] = search_index #print("Before {}, after {}".format(before_index, after_index)) if render_uavs: if before_index == None and after_index == None: #We have no position data nothing to do continue elif before_index != None and after_index == None: #There are no more data points after this point in the simulation. Lock uav's to thier last known position pos = lines[before_index]["pos"] elif before_index == None and after_index != None: #There are no data points before here so for all we know the UAV was always here (should be unlikely in pratice) pos = lines[after_index]["pos"] else: #We have data points before and after so interpolate! a = lines[before_index]["pos"] a_time = lines[before_index]["time"] b = lines[after_index]["pos"] b_time = lines[after_index]["time"] f = normalize(a_time, b_time, simulation_time) pos = lerp(a, b, f) #print("sim {}, a is {}, b is {}, f {}".format(simulation_time, a_time, b_time, f)) color = uav_colors[uav] render_cube(offset=pos, size=0.5, color=color) if render_uavs: #Show origin as green render_cube(glm.vec3(0, 0, 0), 0.1, color=glm.vec3(0, 1, 0)) pygame.display.flip() glPopMatrix() if use_mad: #Compute mad of distances central_last = lines[uav_last_index[central]]["pos"] distances = [] for i in range(0, len(list_uavs)): if i == smallest: #Dont compute the distance from the central node to the central node continue uav_id = list_uavs[i] last_pos = lines[uav_last_index[uav_id]]["pos"] distance = glm.length(central_last - last_pos) distances.append(distance) mean = numpy.mean(distances) mad_value = mad(distances)[0] mad_percent = mad_value * mean * 100 mad_times.append(lines[uav_last_index[central]]["time"]) mad_values.append(mad_percent) if render_uavs: clock.tick(target_fps) now = time.time() delta_time = now - last_time last_time = now simulation_time += delta_time * simulation_speed else: #Fixed simulation steps when we arent rendering in real time simulation_time += 1.0 / target_fps if simulation_time - last_time_print > 15: print("Simulation at " + str(simulation_time)) last_time_print = simulation_time if uav_done_with_pos_cout == len(uavs): print("Finished MAD data collection") break #print("time at {}, delta {}".format(simulation_time, delta_time)) if use_mad: #Simulation done. Graph mad print("Saving graph to: " + args.mad_file) plt.scatter(mad_times, mad_values, s=2) plt.xlabel("Time (s)") plt.ylabel("MAD %") plt.title( "Mean Absloute Deviation Distance as Percent of the Mean vs time") plt.savefig(args.mad_file, dpi=500) pygame.quit() sys.exit()
def aa2q(angle, axis): a = math.cos(angle / 2) i, j, k = math.sin(angle / 2) * glm.normalize(axis) return [round(v, 6) for v in [a, i, j, k]]
def renderQuad(self): if self.quadVAO == 0: # positions pos1 = np.array((-1.0, 1.0, 0.0), np.float32) pos2 = np.array((-1.0, -1.0, 0.0), np.float32) pos3 = np.array((1.0, -1.0, 0.0), np.float32) pos4 = np.array((1.0, 1.0, 0.0), np.float32) # texture coordinates uv1 = np.array((0.0, 1.0), np.float32) uv2 = np.array((0.0, 0.0), np.float32) uv3 = np.array((1.0, 0.0), np.float32) uv4 = np.array((1.0, 1.0), np.float32) # normal vector nm = np.array((0.0, 0.0, 1.0), np.float32) # calculate tangent/bitangent vectors of both triangles # triangle 1 edge1 = pos2 - pos1 edge2 = pos3 - pos1 deltaUV1 = uv2 - uv1 deltaUV2 = uv3 - uv1 f = 1.0 / (deltaUV1[0] * deltaUV2[1] - deltaUV2[0] * deltaUV1[1]) tangent1 = np.array([ f * (deltaUV2[1] * edge1[0] - deltaUV1[1] * edge2[0]), f * (deltaUV2[1] * edge1[1] - deltaUV1[1] * edge2[1]), f * (deltaUV2[1] * edge1[2] - deltaUV1[1] * edge2[2]) ], np.float32) tangent1 = glm.normalize(tangent1) bitangent1 = np.array([ f * (-deltaUV2[0] * edge1[0] + deltaUV1[0] * edge2[0]), f * (-deltaUV2[0] * edge1[1] + deltaUV1[0] * edge2[1]), f * (-deltaUV2[0] * edge1[2] + deltaUV1[0] * edge2[2]) ], np.float32) bitangent1 = glm.normalize(bitangent1) # triangle 2 edge1 = pos3 - pos1 edge2 = pos4 - pos1 deltaUV1 = uv3 - uv1 deltaUV2 = uv4 - uv1 f = 1.0 / (deltaUV1[0] * deltaUV2[1] - deltaUV2[0] * deltaUV1[1]) tangent2 = np.array([ f * (deltaUV2[1] * edge1[0] - deltaUV1[1] * edge2[0]), f * (deltaUV2[1] * edge1[1] - deltaUV1[1] * edge2[1]), f * (deltaUV2[1] * edge1[2] - deltaUV1[1] * edge2[2]) ], np.float32) tangent2 = glm.normalize(tangent2) bitangent2 = np.array([ f * (-deltaUV2[0] * edge1[0] + deltaUV1[0] * edge2[0]), f * (-deltaUV2[0] * edge1[1] + deltaUV1[0] * edge2[1]), f * (-deltaUV2[0] * edge1[2] + deltaUV1[0] * edge2[2]) ], np.float32) bitangent2 = glm.normalize(bitangent2) quadVertices = np.hstack([ # positions, normal, texture coords, tangent, bittangent pos1, nm, uv1, tangent1, bitangent1, pos2, nm, uv2, tangent1, bitangent1, pos3, nm, uv3, tangent1, bitangent1, pos1, nm, uv1, tangent2, bitangent2, pos3, nm, uv3, tangent2, bitangent2, pos4, nm, uv4, tangent2, bitangent2, ]) # setup plane VAO self.quadVAO = glGenVertexArrays(1) quadVBO = glGenBuffers(1) glBindVertexArray(self.quadVAO) glBindBuffer(GL_ARRAY_BUFFER, quadVBO) glBufferData(GL_ARRAY_BUFFER, quadVertices.nbytes, quadVertices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 14 * quadVertices.itemsize, None) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 14 * quadVertices.itemsize, ctypes.c_void_p(3 * quadVertices.itemsize)) glEnableVertexAttribArray(2) glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 14 * quadVertices.itemsize, ctypes.c_void_p(6 * quadVertices.itemsize)) glEnableVertexAttribArray(3) glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 14 * quadVertices.itemsize, ctypes.c_void_p(8 * quadVertices.itemsize)) glEnableVertexAttribArray(4) glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 14 * quadVertices.itemsize, ctypes.c_void_p(11 * quadVertices.itemsize)) glBindVertexArray(self.quadVAO) glDrawArrays(GL_TRIANGLES, 0, 6) glBindVertexArray(0)
def initializeGL(self): glViewport(0, 0, self.width(), self.height()) # setup some OpenGL options glEnable(GL_DEPTH_TEST) vertexShader, fragmentShader = self.loadShaders('9.ssao_geometry.vs', '9.ssao_geometry.frag') self.__geometyPassShader = shaders.compileProgram(vertexShader, fragmentShader) vertexShader, fragmentShader = self.loadShaders('9.ssao.vs', '9.ssao_blur.frag') self.__ssaoBlurShader = shaders.compileProgram(vertexShader, fragmentShader) _shaders = self.loadShaders('9.ssao.vs', '9.ssao_lighting.frag') self.__lightingPassShader = glCreateProgram() [glAttachShader(self.__lightingPassShader, s) for s in _shaders if s] self.__lightingPassShader = shaders.ShaderProgram(self.__lightingPassShader) glLinkProgram(self.__lightingPassShader) glUseProgram(self.__lightingPassShader) glUniform1i(glGetUniformLocation(self.__lightingPassShader, 'gPositionDepth'), 0) glUniform1i(glGetUniformLocation(self.__lightingPassShader, 'gNormal'), 1) glUniform1i(glGetUniformLocation(self.__lightingPassShader, 'gAlbedo'), 2) glUniform1i(glGetUniformLocation(self.__lightingPassShader, 'ssao'), 3) self.__lightingPassShader.check_validate() self.__lightingPassShader.check_linked() [glDeleteShader(s) for s in _shaders if s] _shaders = self.loadShaders('9.ssao.vs', '9.ssao.frag') self.__ssaoShader = glCreateProgram() [glAttachShader(self.__ssaoShader, s) for s in _shaders if s] self.__ssaoShader = shaders.ShaderProgram(self.__ssaoShader) glLinkProgram(self.__ssaoShader) glUseProgram(self.__ssaoShader) glUniform1i(glGetUniformLocation(self.__ssaoShader, 'gPositionDepth'), 0) glUniform1i(glGetUniformLocation(self.__ssaoShader, 'gNormal'), 1) glUniform1i(glGetUniformLocation(self.__ssaoShader, 'texNoise'), 2) self.__ssaoShader.check_validate() self.__ssaoShader.check_linked() [glDeleteShader(s) for s in _shaders if s] # models modelPath = os.path.join(abPath, '..', '..', 'resources', 'objects', 'nanosuit', 'nanosuit.obj') self.cyborg = Model(modelPath) # light position self.lightPos = np.array([2.0, 4.0, -2.0], np.float32) self.lightColor = np.array([0.2, 0.2, 0.7], np.float32) # set up G-Buffer # 3 textures: # 1. Position (RGB) # 2. Color (RGB) + Specular (A) # 3. Normals (RGB) self.gbuffer = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, self.gbuffer) self.gPositionDepth, self.gNormal, self.gAlbedo = glGenTextures(3) # position color buffer glBindTexture(GL_TEXTURE_2D, self.gPositionDepth) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, self.width(), self.height(), 0, GL_RGBA, GL_FLOAT, None) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.gPositionDepth, 0) # normal color buffer glBindTexture(GL_TEXTURE_2D, self.gNormal) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.width(), self.height(), 0, GL_RGB, GL_FLOAT, None) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, self.gNormal, 0) # color + specular buffer glBindTexture(GL_TEXTURE_2D, self.gAlbedo) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.width(), self.height(), 0, GL_RGB, GL_FLOAT, None) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, self.gAlbedo, 0) # tell OpenGL which color attachments we'll use (of this framebuffer) attachments = [GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2] glDrawBuffers(3, attachments) # create depth buffer (renderbuffer) self.rboDepth = glGenRenderbuffers(1) glBindRenderbuffer(GL_RENDERBUFFER, self.rboDepth) glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, self.width(), self.height()) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, self.rboDepth) if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: print 'GBuffer Framebuffer not complete!' glBindFramebuffer(GL_FRAMEBUFFER, 0) # Also create framebuffer to hold SSAO processing stage self.ssaoFBO, self.ssaoBlurFBO = glGenFramebuffers(2) glBindFramebuffer(GL_FRAMEBUFFER, self.ssaoFBO) self.ssaoColorBuffer, self.ssaoColorBufferBlur = glGenTextures(2) # SSAO Color buffer glBindTexture(GL_TEXTURE_2D, self.ssaoColorBuffer) glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, self.width(), self.height(), 0, GL_RGB, GL_FLOAT, None) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.ssaoColorBuffer, 0) if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: print 'SSAO Framebuffer not complete!' # and blur stage glBindFramebuffer(GL_FRAMEBUFFER, self.ssaoBlurFBO) glBindTexture(GL_TEXTURE_2D, self.ssaoColorBufferBlur) glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, self.width(), self.height(), 0, GL_RGB, GL_FLOAT, None) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.ssaoColorBufferBlur, 0) if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: print 'SSAO Blur Framebuffer not complete!' glBindFramebuffer(GL_FRAMEBUFFER, 0) # Sample kernel self.ssaoKernel = [] for i in range(64): sample = np.array([random.random() * 2.0 - 1.0, random.random() * 2.0 - 1.0, random.random()], np.float32) sample = glm.normalize(sample) sample *= random.random() scale = i / 64.0 # scale samples s.t. they're more aligned to center of kernel scale = lerp(0.1, 1.0, scale * scale) sample *= scale self.ssaoKernel.append(sample) # Noise texture self.ssaoNoise = [np.array([random.random() * 2.0 - 1.0, random.random() * 2.0 - 1.0, 0.0], np.float32) for i in range(16)] self.ssaoNoise = np.array(self.ssaoNoise, np.float32) # for i in range(16): # noise = np.array([random.random() * 2.0 - 1.0, random.random() * 2.0 - 1.0, 0.0], np.float32) self.noiseTexture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.noiseTexture) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 4, 4, 0, GL_RGB, GL_FLOAT, self.ssaoNoise) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glClearColor(0.0, 0.0, 0.0, 1.0)