def __init__(self, name='_', color=glm.vec4(1.0, 1.0, 1.0, 1.0), highlight_color=glm.vec4(1.0, 1.0, 1.0, 1.0), intensity=1.0, fresnel=1.0, sharpness=1.0): super().__init__(name, color, highlight_color) self.sharpness = sharpness self.intensity = intensity self.fresnel = fresnel
def calculate_vertices(self, recursive=False, space=WORLD, pack=True): try: rc = self.resource except AttributeError: rc = self.data data = rc.data sz = len(data) // rc.width r = [None] * sz for i in range(sz): j = i * rc.width vert = vec3(*data[j:j + 3]) uv = vec2(*data[j + 3:j + 5]) if type(space) is mat4: vert = (space * vec4(vert, 1.0)).xyz elif space == WORLD: vert = (self.world_matrix * vec4(vert, 1.0)).xyz elif space == PARENT: vert = (self.matrix * vec4(vert, 1.0)).xyz else: assert False if pack: r[i] = [*vert, *uv] else: r[i] = [vert, uv] if recursive: for ch in self.children: r += ch.calculate_vertices(recursive=recursive) return r
def voxel_to_ray(self, x, y): """Return tuple with ray-origin and normalized ray-direction for input render-res x, y""" st = glm.vec2(x / self.width, y / self.height) * 2. - 1. if self.is_perspective(): near, far = -self.near, -self.far else: near, far = -1, 1 pos = self.inverse_projection_matrix * glm.vec4(st.x, st.y, near, 1) pos /= pos.w dirf = self.inverse_projection_matrix * glm.vec4(st.x, st.y, far, 1) dirf /= dirf.w dir = glm.normalize(glm.vec3(dirf - pos)) t = glm.inverse(self.transformation_matrix) ro, rd = glm.vec3(t * pos), glm.normalize( glm.vec3(t * glm.vec4(dir, 0))) if self.is_perspective(): rd = -rd if 0: def _v(v): return "(%s)" % ", ".join("%s" % round(x, 2) for x in v) print("near", _v(pos), "far", _v(dirf), "ro", _v(ro), "rd", _v(rd)) return ro, rd
def InitDemoScene(self): self.camera.LookAt(glm.vec3(10, 10, 20), glm.vec3(0, 0, 0), glm.vec3(0, 1, 0)) from objects import Sphere, Plane min_sphere_radius = 2 max_sphere_radius = 3 cell_size = 2 * max_sphere_radius + 1 for x in range(-1, 2): for y in range(-1, 2): sphere = Sphere.GenerateRandomSphere() sphere.radius = random_in_range(min_sphere_radius, max_sphere_radius) sphere.position = glm.vec4( x * cell_size + random_in_range(2, 4), random_in_range(2, 4), y * cell_size + random_in_range(2, 4), 1) self.AddObject(sphere) material = Lambertian() plane = Plane(glm.vec3(0, 1, 0), glm.vec3(0, 0, 0), material) self.AddObject(plane) light = LightSource(glm.vec4(-10, 10, 10, 1)) self.AddObject(light)
def rotate(self, deltaDegree): # WIP if deltaDegree == 0: return dx = self.x * 2 / display[0] dy = self.y * 2 / display[1] transform = glm.mat4(1) transform = glm.translate(transform, glm.vec3(dx, dy, 0)) transform = glm.rotate(transform, glm.radians(deltaDegree), glm.vec3(0.0, 0.0, 1.0)) transform = glm.translate(transform, glm.vec3(-dx, -dy, 0)) xy1 = glm.vec4(self.pos_data[0], self.pos_data[1], 0, 1) xy2 = glm.vec4(self.pos_data[3], self.pos_data[4], 0, 1) xy3 = glm.vec4(self.pos_data[6], self.pos_data[7], 0, 1) xy4 = glm.vec4(self.pos_data[9], self.pos_data[10], 0, 1) res_xy1 = transform * xy1 res_xy2 = transform * xy2 res_xy3 = transform * xy3 res_xy4 = transform * xy4 glBindBuffer(GL_ARRAY_BUFFER, self.vbo[0]) self.pos_data[0] = res_xy1[0] self.pos_data[1] = res_xy1[1] self.pos_data[3] = res_xy2[0] self.pos_data[4] = res_xy2[1] self.pos_data[6] = res_xy3[0] self.pos_data[7] = res_xy3[1] self.pos_data[9] = res_xy4[0] self.pos_data[10] = res_xy4[1] glBufferData(GL_ARRAY_BUFFER, self.pos_data.nbytes, self.pos_data, GL_DYNAMIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0)
def mandelboxSDF(pos, scale): orbitTrap = glm.vec4(10000) iterations = 17 #0 to 300 colorIterations = 3 #0 to 300 minRad2 = 0.25 #0.0 to 2.0 scale = glm.vec4(scale, scale, scale, abs(scale)) / minRad2 rotVector = glm.vec3(1, 1, 1) #(0, 0, 0) to (1, 1, 1) rotAngle = 0 #0 to 180(?) rot = rotationMatrix3(glm.normalize(rotVector), rotAngle) absScalem1 = abs(scale - 1) absScaleRaisedTo1mIters = pow(abs(scale), float(1 - iterations)) p = pos w = 1 p0 = p w0 = w for i in range(iterations): p *= rot p = glm.clamp(p, -1, 1) * 2 - p r2 = glm.dot(p, p) if i < colorIterations: orbitTrap = glm.min(orbitTrap, abs(glm.vec4(p, r2))) p *= glm.clamp(glm.max(minRad2 / r2, minRad2), 0, 1) w *= glm.clamp(glm.max(minRad2 / r2, minRad2), 0, 1) p = p * glm.vec3(scale[0], scale[1], scale[2]) + p0 w = w * scale[3] + w0 if r2 > 1000: break return (glm.length(p) - absScalem1[3]) / w - absScaleRaisedTo1mIters[3]
def mandelbulbSDF(pos, iterations, power): julia = False juliaC = glm.vec3(0, 0, 0) #(-2, -2, -2) to (2, 2, 2) orbitTrap = glm.vec4(10000) colorIterations = 9 #0 to 100 bailout = 5 #0 to 30 alternateVersion = False rotVector = glm.vec3(1, 1, 1) #(0, 0, 0) to (1, 1, 1) rotAngle = 0 #0 to 180(?) rot = rotationMatrix3(glm.normalize(rotVector), rotAngle) z = pos dr = 1 i = 0 r = glm.length(z) while r < bailout and i < iterations: if alternateVersion: z, dr = powN2(z, r, dr, power) else: z, dr = powN1(z, r, dr, power) z += juliaC if julia else pos r = glm.length(z) z *= rot if i < colorIterations: orbitTrap = min(orbitTrap, abs(glm.vec4(z.x, z.y, z.z, r * r))) i += 1 return 0.5 * numpy.log(r) * r / dr
def _setup_ligthing(self): """Setup shading colors""" self._diffuse_color = glm.vec4(0.26, 0.80, 0.26, 1.0) self._ambient_color = self._diffuse_color * 0.3 self._specular_color = glm.vec4(0.84, 0.30, 0.74, 1.0) self._shininess = 64
def __init__(self, basePos: glm.vec2, duration: float, maxCount: int): self.basePos = basePos self.baseRot = 0.0 self.duration = duration self.velocity = glm.vec2(0.0) self.rotationVelocity = 0.0 self._sizeBegin = glm.vec2(0.0) self._sizeEnd = glm.vec2(0.0) self.sizeChange = False self._colorBegin = glm.vec4(1.0) self._colorEnd = glm.vec4(1.0) self.colorChange = False self.randomizeMovement = False self.fadeOut = False self.__texture = None self.maxCount = max(maxCount, ParticleSystemComponent.MaxCount) self.particlePool = [] for _ in range(self.maxCount): self.particlePool.append(Particle()) self.activeParticleIdx = self.maxCount - 1
def mainloop(): vp_valid, vp_size, view, projection = glut_navigation.update() angle1 = elapsed_ms() * math.pi * 2 / 5000.0 angle2 = elapsed_ms() * math.pi * 2 / 7333.0 model_matrices = [] for i in range(no_of_meshes): if i == 0: model = glm.mat4(1) model = glm.translate(model, glm.vec3(0, 0, -1)) else: angleY = angle1 + math.pi*2 * (i-1) / (no_of_meshes-1) model = glm.mat4(1) model = glm.rotate(model, angleY, glm.vec3(0, 0, 0.5)) model = glm.translate(model, glm.vec3(diameter/2, 0, 0.5)) model = glm.rotate(model, angle2, glm.vec3(0, 1, 0)) model_matrices.append(model) light_pos = glm.vec3(0, 0, 3) light_dir = glm.vec3(0, 0, -1) light_cone_angle_degree = 60 light_cone_cos = math.cos(math.radians(light_cone_angle_degree) / 2) shadow_proj = glm.perspective(glm.radians(light_cone_angle_degree + 1), 1, 0.1, 100.0) shadow_view = glm.lookAt(light_pos, light_pos+light_dir, glm.vec3(0,1,0)) glBindBuffer(GL_SHADER_STORAGE_BUFFER, model_ssbo) for i, model in enumerate(model_matrices): glBufferSubData(GL_SHADER_STORAGE_BUFFER, i*4*16, glm.sizeof(glm.mat4), glm.value_ptr(model)) glBindFramebuffer(GL_FRAMEBUFFER, shadow_fbo) glViewport(0, 0, *shadow_buffer_size) glClear(GL_DEPTH_BUFFER_BIT) glUseProgram(shadow_program) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(shadow_proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(shadow_view)) glEnable(GL_POLYGON_OFFSET_FILL) glPolygonOffset(1.0, 1.0) model_multimesh.draw() glDisable(GL_POLYGON_OFFSET_FILL) glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(0, 0, *vp_size) glClearColor(0.2, 0.3, 0.3, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(phong_program) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(projection)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(view)) glUniformMatrix4fv(2, 1, GL_FALSE, glm.value_ptr(shadow_proj)) glUniformMatrix4fv(3, 1, GL_FALSE, glm.value_ptr(shadow_view)) glUniform4fv(4, 1, glm.value_ptr(glm.vec4(light_pos, 1))) glUniform4fv(5, 1, glm.value_ptr(glm.vec4(light_dir, light_cone_cos))) glBindTextureUnit(1, shadow_depth_to) model_multimesh.draw() glutSwapBuffers() glutPostRedisplay()
def _generate_nodeview_matrix2( rsm_version: int, node: AbstractNode) -> Tuple[glm.mat4, glm.mat4]: # Transformations which are inherited by children local_transform_matrix = glm.mat4() rsm_node = node.impl # Scaling if len(rsm_node.scale_key_frames) > 0: local_transform_matrix = glm.scale( local_transform_matrix, glm.vec3(rsm_node.scale_key_frames[0].scale)) # Rotation if len(rsm_node.rot_key_frames) > 0: # Animated model key_frame = rsm_node.rot_key_frames[0] quaternion = glm.quat(key_frame.quaternion[3], key_frame.quaternion[0], key_frame.quaternion[1], key_frame.quaternion[2]) local_transform_matrix *= glm.mat4_cast(quaternion) else: # Static model local_transform_matrix = rag_mat4_mul( local_transform_matrix, mat3tomat4(rsm_node.info.offset_matrix)) if node.parent: parent_offset_matrix = mat3tomat4( node.parent.impl.info.offset_matrix) local_transform_matrix = rag_mat4_mul( local_transform_matrix, glm.inverse(parent_offset_matrix)) # Translation if rsm_version >= 0x203 and len(rsm_node.pos_key_frames) > 0: key_frame = rsm_node.pos_key_frames[0] position = glm.vec3(key_frame.position) elif node.parent: position = glm.vec3(rsm_node.info.offset_vector) - \ glm.vec3(node.parent.impl.info.offset_vector) parent_offset_matrix = mat3tomat4(node.parent.impl.info.offset_matrix) position = glm.vec3( glm.inverse(parent_offset_matrix) * glm.vec4(position, 1.0)) else: position = glm.vec3(rsm_node.info.offset_vector) # Transformations which are applied only to this node final_transform_matrix = copy.copy(local_transform_matrix) # Reset translation transformation to `position` final_transform_matrix[3] = glm.vec4(position, 1.0) # Inherit transformations from ancestors parent = node.parent while parent: final_transform_matrix = rag_mat4_mul(final_transform_matrix, parent.local_transform_matrix) parent = parent.parent if node.parent: parent_translation = glm.vec3(node.parent.final_transform_matrix[3]) final_transform_matrix[3] += glm.vec4(parent_translation, 0.0) return (local_transform_matrix, final_transform_matrix)
def get_tx_point(self, offset): body_pos = self.body.position angle = self.body.angle tx = glm.mat4() tx = glm.rotate(tx, angle, glm.vec3(0, 0, 1)) rel_pos = tx * glm.vec4(offset[0], offset[1], 0, 1) pos = rel_pos + glm.vec4(body_pos[0], body_pos[1], 0, 1) return (pos[0], pos[1])
def get_box(self): minimums = [min(self.vertex_info[::, i]) for i in range(5, 8)] maximums = [max(self.vertex_info[::, i]) for i in range(5, 8)] lx, ly, lz = glm.vec3(self.translated * self.scaled * glm.vec4(minimums + [1])) ux, uy, uz = glm.vec3(self.translated * self.scaled * glm.vec4(maximums + [1])) self.box = Box(lx, ux, ly, uy, lz, uz)
def c2v(color, alpha=1.): if type(color) is str: color = parse_webcolor(color) if len(color) == 3: color = glm.vec4(color, alpha) return glm.vec4(color)
def tint(self, tint: glm.vec4): if tint is None: tint = self.default_tint if len(tint) == 3: tint = glm.vec4(*tint, 1) else: tint = glm.vec4(*tint) self._tint = tint
def __init__(self, vkdevice, queue): self.vulkanDevice = vkdevice self.queue = queue self.descriptorPool = None # We will be using separate descriptor sets (and bindings) # for material and scene related uniforms self.descriptorSetLayouts = {'material': None, 'scene': None} # We will be using one single index and vertex buffer # containing vertices and indices for all meshes in the scene # This allows us to keep memory allocations down self.vertexShape = np.dtype([('pos', np.float32, (3, )), ('normal', np.float32, (3, )), ('uv', np.float32, (2, )), ('color', np.float32, (3, )) ]) #position, normal, uv, color self.vertexBuffer = None self.indexBuffer = None self.descriptorSetScene = None self.aScene = None self.assetPath = "" # Shader properites for a material # Will be passed to the shaders using push constant self.scenematerialShape = { 'ambient': glm.vec4(0.0), 'diffuse': glm.vec4(0.0), 'specular': glm.vec4(0.0), 'opacity': glm.vec1(0.0) } self.materials = [] self.meshes = [] # Shared ubo containing matrices used by all # materials and meshes self.uniformBuffer = None self.uniformData = { 'projection': glm.mat4(), 'view': glm.mat4(), 'model': glm.mat4(), 'lightPos': glm.vec4(1.25, 8.35, 0.0, 0.0) } # Scene uses multiple pipelines self.pipelines = {'solid': None, 'blending': None, 'wireframe': None} # Shared pipeline layout self.pipelineLayout = None # For displaying only a single part of the scene self.renderSingleScenePart = False self.scenePartIndex = 0 # TODO if that does not work, do not use createvksBuffer but do it by hand as in the demo uboSize = sum([glm.sizeof(ubo) for ubo in self.uniformData.values()]) self.uniformBuffer = self.vulkanDevice.createvksBuffer( vk.VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, uboSize) self.uniformBuffer.map()
def project(point, mvp_matrix, width, height): pos = np.array(mvp_matrix, dtype=np.float).dot(glm.vec4(point.x, point.y, point.z, 1.0)) if pos[3] == 0.0: return glm.vec4(0.0) pos /= pos[3] value = glm.vec3((pos[0] * 0.5 + 0.5) * width, (pos[1] * 0.5 + 0.5) * height, (1.0 + pos[2]) * 0.5) return value
def unproject(screen_point, mvp_matrix, width, height): mvp_matrix_inv = np.array(glm.inverse(mvp_matrix), dtype=np.float32) x = screen_point.x / width * 2.0 - 1.0 y = screen_point.y / height * 2.0 - 1.0 z = screen_point.z * 2.0 - 1.0 point = mvp_matrix_inv.dot(glm.vec4(x, y, z, 1.0)) if point[2] == 0.0: return glm.vec4(0.0) point /= point[2] return glm.vec3(point[0], point[1], point[2])
def _expand_color(c): if len(c) == 1: return glm.vec4(c[0], c[0], c[0], 1) elif len(c) == 2: return glm.vec4(c[0], c[0], c[0], c[1]) elif len(c) == 3: return glm.vec4(c[0], c[1], c[2], 1) elif len(c) == 4: return c return glm.vec4(1)
def on_mouse_move(self, dx, dy): yaw_axis = glm.vec3(0.0, 1.0, 0.0) pitch_axis = glm.cross(self._direction, yaw_axis) # TODO radians conversion can be avoided w/ lower sensibility yaw_angle = math.radians(-dx * self._mouse_sensibility) pitch_angle = math.radians(-dy * self._mouse_sensibility) self._direction = (glm.rotate(glm.mat4(1.0), yaw_angle, yaw_axis) * glm.vec4(self._direction, 1.0)).xyz self._direction = (glm.rotate(glm.mat4(1.0), pitch_angle, pitch_axis) * glm.vec4(self._direction, 1.0)).xyz
def getCubeRay(self, wnd_pos): ndc_xy = wnd_pos[0] * 2 / self.__vp_size[0] - 1, wnd_pos[ 1] * 2 / self.__vp_size[1] - 1 cube_mv = self.__view * self.__model * self.__voxel_map.cube_model cube_space = glm.inverse(cube_mv) inverse_prj = glm.inverse(self.__proj) view_dir1_h = inverse_prj * glm.vec4(*ndc_xy, 1, 1) view_dir0_h = inverse_prj * glm.vec4(*ndc_xy, -1, 1) view_dir = view_dir1_h.xyz / view_dir1_h.w - view_dir0_h.xyz / view_dir0_h.w cube_origin = cube_space[3].xyz cube_dir = glm.mat3(cube_space) * view_dir return (cube_origin, cube_dir)
def read_vertices(self): self.vertices = np.array( [ *vec4(-1.0, -1.0, 0.0, 1.0), *vec4(+1.0, -1.0, 0.0, 1.0), *vec4(-1.0, +1.0, 0.0, 1.0), *vec4(+1.0, +1.0, 0.0, 1.0), ], dtype=np.float32, ) self.indices = self.gl.buffer(np.array([0, 1, 2, 2, 1, 3], dtype=np.int32)) self.vertex_description = [(self.gl.buffer(self.vertices), "4f", "in_pos")]
def remove_child(self, child): self.children.remove(child) child_center = glm.vec3(self.M * glm.vec4(child.center, 1)) child_radius = child.radius * glm.length(self.M * glm.vec4(1, 1, 1, 0)) / glm.sqrt(3) if len(self.children) > 1: centers = [self.M * glm.vec4(child.center, 1) for child in self.children] self.min_x = min([center[0] for center in centers]) self.max_x = max([center[0] for center in centers]) self.min_y = min([center[1] for center in centers]) self.max_y = max([center[1] for center in centers]) self.min_z = min([center[2] for center in centers]) self.max_z = max([center[2] for center in centers]) self.center = glm.vec3((self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2, (self.min_z + self.max_z) / 2) self.radius = max([glm.length(self.center - child.center) + child.radius for child in self.children])
def rotate(self, deg, x, y, z): # Shift the cube so that it's pivot resides at the origin shift = (-self.pivot[0], -self.pivot[1], -self.pivot[2]) self.move(shift) # Create a vec3 using the components of the orientation vector axis = glm.vec3(x, y, z) a = radians(deg) m = glm.mat4(1.0) # Identity matrix # Construct the rotation matrix using the identity m = glm.rotate(m, a, axis) # Rotate each of the vertices for vertex in self.vertices: # Perform the rotation v = glm.vec4(vertex[0], vertex[1], vertex[2], 1) v = m*v # Update the location of the vertices vertex[0] = v[0] vertex[1] = v[1] vertex[2] = v[2] # Move the cube back and its pivot back to the original location shift = (-shift[0], -shift[1], -shift[2]) self.move(shift)
def LerpVec4(factor: float, a: glm.vec4, b: glm.vec4) -> glm.vec4: _x = LerpFloat(factor, a.x, b.x) _y = LerpFloat(factor, a.y, b.y) _z = LerpFloat(factor, a.z, b.z) _w = LerpFloat(factor, a.w, b.w) return glm.vec4(_x, _y, _z, _w)
def test_color_names(): assert fcmp(Color("black"), vec4(0, 0, 0, 1)) assert fcmp(Color("white"), vec4(1, 1, 1, 1)) assert fcmp(Color("red"), vec4(1, 0, 0, 1)) # assert fcmp(Color('green'), vec4(0,1,0,1)) assert fcmp(Color("blue"), vec4(0, 0, 1, 1)) assert fcmp(Color("black", 0.5), vec4(0, 0, 0, 0.5)) assert Color(Color(Color("red"))) == Color("red") == "red" assert "green" == Color("green") assert "red" != Color("blue") col = Color(Color("red").bgr) assert col == "blue"
def MoveOnLineOfSight(self, cursor_pos, delta): # get viewport rectangle #vp_rect = self.VpRect() # get view, projection and window matrix proj, inv_proj = self.ProjectionMat() view, inv_view = self.ViewMat() wnd, inv_wnd = self.WindowMat() # get world space position on view ray pt_wnd = glm.vec3(*cursor_pos, 1.0) #pt_world = glm.unProject(pt_wnd, view, proj, vp_rect) pt_h_world = inv_view * inv_proj * inv_wnd * glm.vec4(*pt_wnd, 1) pt_world = glm.vec3(pt_h_world) / pt_h_world.w # get view position eye = glm.vec3(inv_view[3]) # get "zoom" direction and amount ray_cursor = glm.normalize(pt_world - eye) # translate view position and update view matrix inv_view = glm.translate(glm.mat4(1), ray_cursor * delta) * inv_view # return new view matrix return glm.inverse(inv_view), True
def pg_color(c): tc = type(c) if tc == pygame.Color: return c elif tc == vec3: c = vec4(c, 0) elif tc == ivec3: c = vec4(c, 0) elif tc == ivec4: c = vec4(c, 0) elif tc == tuple: return c elif tc == str: return pygame.Color(c) c = tuple(int(clamp(x * 255, 0, 255)) for x in c) return c
def draw_panel(self, sz, col=(0, 0, 0)): w, h = sz surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context(surface) rad = 18.5 deg = math.pi / 180 x, y = 0, 0 ctx.new_sub_path() ctx.arc(x + w - rad, y + rad, rad, -90 * deg, 0 * deg) ctx.arc(x + w - rad, y + h - rad, rad, 0 * deg, 90 * deg) ctx.arc(x + rad, y + h - rad, rad, 90 * deg, 180 * deg) ctx.arc(x + rad, y + rad, rad, 180 * deg, 270 * deg) ctx.close_path() ctx.set_source_rgba(*(vec4(vec3(col) / 255, 0.5))) ctx.fill_preserve() # ctx.set_line_width(4.0) # ctx.set_source_rgba(*(vec4(vec3(col)/255, 0.8))) ctx.stroke() # scale = self.icon_sz[0]/dim[0] # ctx.scale(scale,scale) # svg.render_cairo(ctx) im = Image.frombuffer("RGBA", (w, h), surface.get_data().tobytes(), "raw", "BGRA", 0, 0) buf = im.tobytes() return pygame.image.fromstring(buf, (w, h), "RGBA").convert_alpha()
def __init__(self, opengl_frame, view, fov_y, near, far, get_depth_callback): self.opengl_frame = opengl_frame cx, cy = self.opengl_frame.width, self.opengl_frame.height self.__vp_size = (cx, cy) self.__fov_y = fov_y self.__depth_range = [near, far] self.__view = view self.__proj = glm.perspective(glm.radians(self.__fov_y), cx / cy, *self.__depth_range) self.__navigate_control = NavigationController( lambda: self.__view, lambda: self.__proj, lambda: glm.vec4(0, 0, *self.__vp_size), lambda x, y: self.__get_depth(x, y), lambda _, __: glm.vec3(0, 0, 0)) self.__get_depth_callback = get_depth_callback self.opengl_frame.bind('<Button-1>', self.__mouse_button_left_down) self.opengl_frame.bind('<ButtonRelease-1>', self.__mouse_button_left_up) self.opengl_frame.bind('<Button-3>', self.__mouse_button_right_down) self.opengl_frame.bind('<ButtonRelease-3>', self.__mouse_button_right_up) self.opengl_frame.bind('<Motion>', self.__mouse_motion) self.opengl_frame.bind('<MouseWheel>', self.__mouse_wheel)
def V(*args): lenargs = len(args) if lenargs == 2: return glm.vec2(*args) elif lenargs == 4: return glm.vec4(*args) return glm.vec3(*args)
def color(p1 = None, p2 = None, p3 = None, p4 = None): global _color if p1 is None: _color = glm.vec4(1) _vbo.data(bytes(_color) * 4, s_f2_4) elif p2 is None: _color = _expand_color(p1) _vbo.data(bytes(_color) * 4, s_f2_4) elif p3 is None or p4 is None: raise Exception('Color must specify 1 point or all four.') else: _vbo.data(bytes(_expand_color(p1)) + bytes(_expand_color(p2)) + bytes(_expand_color(p3)) + bytes(_expand_color(p4)), s_f2_4)
def translate(matrix, x, y, z): translation = glm.types.mat4x4.identity() translation.col3_vec4(glm.vec4(x, y, z, 1)) return translation.mul_mat(matrix)
def _setup(wd): global _wd, _program, _font_program, _vao, _font_vbo, _font_vao, _vbo, _initstate, _matrix, _white, _img, _color _wd = wd _font_vshader = scge.shader('vertex', '''#version 330 core in vec2 coords; in vec2 texcoords; uniform mat4 matrix; out vec2 texcoord; void main() { texcoord = texcoords; gl_Position = matrix * vec4(coords, 0.0, 1.0); } ''') _font_fshader = scge.shader('fragment', '''#version 330 core #extension GL_ARB_texture_rectangle : require in vec2 texcoord; uniform sampler2DRect tex; uniform vec4 color; out vec4 frag; void main() { frag = color; frag.a *= texture2DRect(tex, texcoord).r; if(frag.a == 0.) discard; } ''') _font_program = scge.program() _font_program.attach(_font_vshader) _font_program.attach(_font_fshader) _font_program.attribute(0, 'coords') _font_program.attribute(1, 'texcoords') _font_program.attribute(2, 'ink') _font_program.link() _vshader = scge.shader('vertex', '''#version 330 core in vec2 coords; in vec4 colors; in vec2 texcoords; uniform mat4 matrix; out vec4 color; out vec2 texcoord; void main() { color = colors; texcoord = texcoords; gl_Position = matrix * vec4(coords, 0.0, 1.0); } ''') _fshader = scge.shader('fragment', '''#version 330 core in vec4 color; in vec2 texcoord; uniform sampler2D tex; out vec4 frag; void main() { frag = texture2D(tex, texcoord) * color; if(frag.a == 0.) discard; } ''') _program = scge.program() _program.attach(_vshader) _program.attach(_fshader) _program.attribute(0, 'coords') _program.attribute(1, 'colors') _program.attribute(2, 'texcoords') _program.link() _vbo = scge.vbo(s_f8_4, 'stream draw') _vao = scge.vao() _wd.use(_vao) _vao.enable(0) _vao.enable(1) _vao.enable(2) _vao.attribute(0, _vbo, 'float', 2, 0) _vao.attribute(1, _vbo, 'float', 4, s_f2_4) _vao.attribute(2, _vbo, 'float', 2, s_f6_4) _font_vbo = scge.vbo(s_f6_4, 'stream draw') _font_vao = scge.vao() _wd.use(_font_vao) _font_vao.enable(0) _font_vao.enable(1) _font_vao.attribute(0, _font_vbo, 'float', 2, 0, s_f * 4) _font_vao.attribute(1, _font_vbo, 'float', 4, s_f * 2, s_f * 4) p = scge.pixelcache(glm.ivec2(1, 1)) p.pixel(glm.ivec2(0, 0), glm.vec4(1)) _white = scge.image(p) _program.uniform('tex', _white) _img = _white _matrix = glm.ortho(0, wd.size().x, 0, wd.size().y, -1, 1) _usingDefaultProgram = True color(glm.vec4(1)) _initstate = 1