def fit_inside(self, box: Box, anchor: Vector3): scale = np.amin(box.size() / self.bounding_box().size()) extra = box.size() - (self.bounding_box().size() * scale) matrix = Matrix44.from_translation(-self.bounding_box().min) matrix = Matrix44.from_scale([scale, scale, scale]) * matrix matrix = Matrix44.from_translation(box.min + (extra * anchor)) * matrix self.transform(matrix)
def createTransformationMatrix(position, rotX=0, rotY=0, rotZ=0, scale=1): if rotX == 0 and rotY == 0 and rotZ == 0: return Matrix44.from_translation(position) * Matrix44.from_scale( [scale, scale, scale]) return Matrix44.from_translation( position) * pyrr.matrix44.create_from_axis_rotation( (rotX, rotY, rotZ), rotY) * Matrix44.from_scale( [scale, scale, scale])
def applyTransforms(vector, projectionMat): r = time.clock() + vector[0] * 10 # rotation offset based on vector's 1st component rotX = Matrix44.from_x_rotation(r) rotY = Matrix44.from_y_rotation(r) rotZ = Matrix44.from_z_rotation(r) trans = Matrix44.from_translation(vector) * Matrix44.from_translation([1,1,-5]) # move view back by -5 scale = Matrix44.from_scale([.5,.5,.5]) # uniformly scale by 0.5 tMatrix = projectionMat * trans * scale * rotX * rotY * rotZ prog['transform'].write(tMatrix.astype('f4').tobytes())
def render(self, time, frametime): self.ctx.enable_only(moderngl.DEPTH_TEST | moderngl.CULL_FACE) self.lightpos = Vector3((math.sin(time) * 20, 5, math.cos(time) * 20), dtype='f4') scene_pos = Vector3((0, -5, -32), dtype='f4') # --- PASS 1: Render shadow map self.offscreen.clear() self.offscreen.use() depth_projection = Matrix44.orthogonal_projection(-20, 20, -20, 20, -20, 40, dtype='f4') depth_view = Matrix44.look_at(self.lightpos, (0, 0, 0), (0, 1, 0), dtype='f4') depth_mvp = depth_projection * depth_view self.shadowmap_program['mvp'].write(depth_mvp) self.floor.render(self.shadowmap_program) self.wall.render(self.shadowmap_program) self.sphere.render(self.shadowmap_program) # --- PASS 2: Render scene to screen self.wnd.use() self.basic_light['m_proj'].write(self.camera.projection.matrix) self.basic_light['m_camera'].write(self.camera.matrix) self.basic_light['m_model'].write( Matrix44.from_translation(scene_pos, dtype='f4')) bias_matrix = Matrix44( [[0.5, 0.0, 0.0, 0.0], [0.0, 0.5, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0], [0.5, 0.5, 0.5, 1.0]], dtype='f4', ) self.basic_light['m_shadow_bias'].write( matrix44.multiply(depth_mvp, bias_matrix)) self.basic_light['lightDir'].write(self.lightpos) self.offscreen_depth.use(location=0) self.floor.render(self.basic_light) self.wall.render(self.basic_light) self.sphere.render(self.basic_light) # Render the sun position self.sun_prog['m_proj'].write(self.camera.projection.matrix) self.sun_prog['m_camera'].write(self.camera.matrix) self.sun_prog['m_model'].write( Matrix44.from_translation(self.lightpos + scene_pos, dtype='f4')) self.sun.render(self.sun_prog) # --- PASS 3: Debug --- # self.ctx.enable_only(moderngl.NOTHING) self.offscreen_depth.use(location=0) self.offscreen_quad.render(self.raw_depth_prog)
def scatterCubes(vector, projectionMat): view = window.getViewMatrix() r = vector[0] * 10.0 # cube rotation offset based on vector's 1st component rotX = Matrix44.from_x_rotation(r*time.clock()/10.0) # rotate cubes over time rotY = Matrix44.from_y_rotation(r) rotZ = Matrix44.from_z_rotation(r) trans = Matrix44.from_translation(vector) * Matrix44.from_translation([1.0,1.0,-5.0]) scale = Matrix44.from_scale([.5,.5,.5]) # uniformly scale by 0.5 tMatrix = projectionMat * view * trans * scale * rotX * rotY * rotZ prog['transform'].write(tMatrix.astype('f4').tobytes())
def refresh_position(self): center = self.camera.scene.bounding_box.center dummy_cam = Camera() dummy_cam.matrix = self.default_matrix z_shift = dummy_cam.distance_to_point(center) self.camera.matrix = Matrix44.from_translation([self._shift_x, self._shift_y, self._distance]) * \ Matrix44.from_translation([0, 0, -z_shift]) * \ Matrix44.from_x_rotation(-self._angle_y) * \ Matrix44.from_y_rotation(-self._angle_x) * \ Matrix44.from_translation([0, 0, z_shift]) * \ self.default_matrix post_redisplay()
def __init__(self, data): self.name = data.get('name') self.children = data.get('children') self.matrix = data.get('matrix') self.mesh = data.get('mesh') self.camera = data.get('camera') self.translation = data.get('translation') self.rotation = data.get('rotation') self.scale = data.get('scale') if self.matrix: self.matrix = Matrix44(self.matrix) else: self.matrix = Matrix44.identity() if self.translation is not None: self.matrix = self.matrix * Matrix44.from_translation(self.translation) if self.rotation is not None: quat = quaternion.create( x=self.rotation[0], y=self.rotation[1], z=self.rotation[2], w=self.rotation[3], ) self.matrix = self.matrix * Matrix44.from_quaternion(quat).transpose() if self.scale is not None: self.matrix = self.matrix * Matrix44.from_scale(self.scale)
def __init__(self, **kwargs): super().__init__(**kwargs) self.camera = KeyboardCamera(self.wnd.keys, aspect_ratio=self.wnd.aspect_ratio) self.terrain_program = self.load_program('my_shader.glsl') self.ctx.front_face = 'cw' # self.ctx.wireframe = True self.translate = Matrix44.from_translation((0, 1., .25)) self.rotate = Matrix44.look_at((0., 1., .25), (0., 0., -1.), (0., 1., 0.)) self.projection = (self.camera.projection.matrix * (self.translate * self.rotate)).astype('f4') self.terrain_program['projection'].write(self.projection.tobytes()) terrain_resolution = 5 points = generate(terrain_resolution).astype('f4') self.buffer = self.ctx.buffer(points) indices = generate_index_buffer(terrain_resolution).astype('i4') print(indices) self.index_buffer = self.ctx.buffer(indices) self.vao_1 = VAO(name='vao_1') self.vao_1.buffer(self.buffer, '3f', ['in_position']) self.vao_1.index_buffer(self.index_buffer)
def render(self, camera): if self.geometry.has_index_array and self.geometry.has_vertex_array and self.visible: camera.push_matrix() camera.matrix *= Matrix44.from_translation(self.position) self.shader.pre_render(camera) glBindVertexArray(self.geometry.vertex_array_object) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.geometry.index_buffer) # Which kind of Geometry do we have? if isinstance(self.geometry, InstancedGeometry): self.shader.uniform3fv( "vertexScalars", 1, numpy.array(self.geometry.vertex_scalars)) self.shader.uniform3fv( "vertexOffsets", 1, numpy.array(self.geometry.vertex_offsets)) if self.geometry.num_instances: glDrawElementsInstanced(self.geometry.mode, self.geometry.num_indices, GL_UNSIGNED_INT, None, self.geometry.num_instances) elif isinstance(self.geometry, Geometry): glDrawElements(self.geometry.mode, self.geometry.num_indices, GL_UNSIGNED_INT, None) glBindVertexArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) camera.pop_matrix() self.shader.post_render(camera)
def on_render(self, gl_area, gl_context): glClearColor(0.0, 0.0, 0.0, 0.0) # Set the background colour for the window -> Black glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Clear the window background colour to black by resetting the COLOR_BUFFER and clear the DEPTH_BUFFER eye = (0.0, 5, 18.0) # Eye coordinates (location of the camera) target = (0.0, 7.0, 0.0) # Target coordinates (where the camera is looking) up = (0.0, 1.0, 0.0) # A vector representing the 'up' direction. view_matrix = Matrix44.look_at(eye, target, up) # Calculate the view matrix model_matrix = Matrix44.from_translation([0.0, 0.0, 0.0]) * pyrr.matrix44.create_from_axis_rotation((0.0, 1.0, 0.0), self.application_clock) * Matrix44.from_scale([1.0, 1.0, 1.0]) # self.camera.move() # for entity in list_of_entities_to_render: # self.renderer.processEntity(entity) # self.renderer.render(self.lights, self.camera) # self.guiRenderer.render(self.guis) glUseProgram(self.shader) # Tells OpenGL to use the shader program for rendering geometry glUniformMatrix4fv(self.viewMatrixLocationInShader, 1, GL_FALSE, view_matrix) glUniformMatrix4fv(self.modelMatrixLocationInShader, 1, GL_FALSE, model_matrix) glUniform3f(self.lightPositionLocationInShader, 0.0, 3.0, 10.0) glUniform3f(self.lightColourLocationInShader, 1.0, 1.0, 1.0) glUniform1f(self.useFakeLightingLocationInShader, 0.0) glBindVertexArray(self.vertex_array_object) # Binds the self.vertex_array_object to the OpenGL pipeline vertex target glDrawArrays(GL_TRIANGLES, 0, len(self.blenderModel.vertices)) glBindVertexArray(0) glUseProgram(0) # Tells OpenGL to use the shader program for rendering geometry self.queue_draw() # Schedules a redraw for Gtk.GLArea
def render(self, time, frame_time): self.ctx.clear(0.2, 0.2, 0.2) self.ctx.enable(moderngl.DEPTH_TEST) self.fps = 1 / frame_time self.control() proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0) lookat = Matrix44.look_at( (self.movX, self.movY, self.movZ), (200.0, 200.0, 0.0), (0.0, 0.0, 1.0), ) self.light.value = (100, 0, 200) self.texture.use(0) self.mvp_map.write((proj * lookat).astype('f4')) self.vao_map.render(moderngl.TRIANGLE_FAN) model_rot = Matrix44.from_z_rotation( 3.14 / 4) * Matrix44.from_x_rotation(-3.14 / 2) for x in range(int(self.positions.size / 3)): size = 1 + self.production[x] * (2.5 - 1) model_size = Matrix44.from_scale(np.array([size, size, size])) self.gradient.value = self.production[x] model = Matrix44.from_translation(np.array( self.positions[x])) * model_rot * model_size self.mvp.write((proj * lookat * model).astype('f4')) self.vao.render() self.render_ui()
def render(self, batch_size): warp = np.empty( (batch_size, self.height, self.width, 2), dtype=np.float32) for i in range(batch_size): translation = Matrix44.from_translation(( np.random.uniform(self.x_low, self.x_high), np.random.uniform(self.y_low, self.y_high), 0.0 )) rotation = Matrix44.from_matrix33( self.rand_rotation_matrix(self.deflection) ) view = Matrix44.look_at( (0.0, 0.0, np.random.uniform(self.close, self.far)), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0), ) projection = Matrix44.perspective_projection( 45.0, self.width / self.height, 0.1, 1000.0 ) # TODO: translation or rotation first? transform = projection * view * translation * rotation self.fbo.use() self.fbo.clear() self.mvp.write(transform.astype('f4').tobytes()) self.vao.render() framebuffer = self.fbo.read(components=2, floats=True) warp[i] = np.frombuffer(framebuffer, dtype=np.float32).reshape( (self.height, self.width, 2))[::-1] return warp
def load_point(self): self.point_vbo = self.ctx.buffer( np.array([0.0, 0.0, 0.0]).astype('f4').tobytes()) self.point_vao = self.ctx.simple_vertex_array(self.point_prog, self.point_vbo, 'in_vert') self.point_model = Matrix44.from_translation((0, 0, 0))
def generate_lines(obj: Object, camera: Camera, viewport: Polygon, front_brightness: float, back_brightness: float) -> List[Line]: # Create transformation matrix translation = Matrix44.from_translation(obj.translation) rotation = Matrix44.from_eulers(obj.rotation) projection = Matrix44.perspective_projection( camera.fovy, camera.aspect, camera.near, camera.far) cam = matrix44.create_look_at(camera.eye, camera.target, [0, 1.0, 0]) matrix = projection * cam * translation * rotation # Transform vertices, remove hidden faces and get edges for faces # TODO: Make the rendering pipeline more generic vertices = [matrix * vertex for vertex in obj.mesh.vertices] front_faces = [face for face in obj.mesh.faces if cull_face(vertices, face, 'front')] back_faces = [face for face in obj.mesh.faces if cull_face(vertices, face, 'back')] front_edges = find_edges(front_faces, obj.mesh.edges) back_edges = find_edges(back_faces, obj.mesh.edges) # Clip lines lines = edges_to_lines(front_edges, vertices, front_brightness) + \ edges_to_lines(back_edges, vertices, back_brightness) return [clipped for clipped in [clip_line(line, viewport) for line in lines] if clipped is not None]
def render(self, time, frame_time): self.ctx.clear(1.0, 1.0, 1.0) self.ctx.enable(moderngl.DEPTH_TEST) proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 100.0) camera_pos = np.array([ np.cos(self.angleY) * np.cos(self.angleX), np.sin(self.angleX), np.sin(self.angleY) ]) * self.distance lookat = Matrix44.look_at( tuple(camera_pos + self.origin), # eye tuple(self.origin), # target (0.0, 0.0, 1.0), # up ) self.light.value = (0, -3, 3) self.texture.use() for coord in self.coords: model = Matrix44.from_translation(coord) self.mvp.write((proj * lookat * model).astype('f4')) self.vao.render()
def render(self, time, frame_time): if SimpleRenderer.callback and frame_time > 0: SimpleRenderer.callback(frame_time) # print(time, frame_time) self.camera.update() self.ctx.clear(0.1, 0.1, 0.1) self.ctx.enable(moderngl.DEPTH_TEST) # print('---------') # print(self.camera.elevation, self.camera.azimuth) # print(self.camera.mat_lookat*Vector4([0,0,0,1])) # grid self.mvp.write((self.camera.mat_projection * self.camera.mat_lookat.inverse).astype('f4')) self.grid_vao.render(moderngl.LINES) # objects for obj in SimpleRenderer.objects: # model matrix scale = Matrix44.from_scale([obj.radius, obj.radius, obj.radius]) rotation = Matrix44.from_z_rotation( -np.arctan2(obj.vel.y, obj.vel.x)) translation = Matrix44.from_translation([obj.pos.x, obj.pos.y, 0]) model = translation * rotation * scale # render object self.mvp.write( (self.camera.mat_projection * self.camera.mat_lookat.inverse * model).astype('f4')) self.cyl_vao.render(moderngl.TRIANGLES)
def test_oo_examples(self): from pyrr import Quaternion, Matrix44, Vector3 import numpy as np point = Vector3([1., 2., 3.]) orientation = Quaternion() translation = Vector3() scale = Vector3([1., 1., 1.]) # translate along X by 1 translation += [1.0, 0.0, 0.0] # rotate about Y by pi/2 rotation = Quaternion.from_y_rotation(np.pi / 2.0) orientation = rotation * orientation # create a matrix # start our matrix off using the scale matrix = Matrix44.from_scale(scale) # apply our orientation # we can multiply matricies and quaternions directly! matrix = matrix * orientation # apply our translation translation = Matrix44.from_translation(translation) matrix = matrix * translation # transform our point by the matrix # vectors are transformable by matrices and quaternions directly point = matrix * point
def on_draw(self): self.ctx.enable_only(self.ctx.CULL_FACE, self.ctx.DEPTH_TEST) # Draw the current cube using the last one as a texture self.fbo1.use() self.fbo1.clear(color=(1.0, 1.0, 1.0, 1.0), normalized=True) rotate = Matrix44.from_eulers( (self.time, self.time * 0.77, self.time * 0.01), dtype='f4') translate = Matrix44.from_translation((0, 0, -1.75), dtype='f4') modelview = translate * rotate if self.frame > 0: self.program['use_texture'] = 1 self.fbo2.color_attachments[0].use() self.program['modelview'] = modelview.flatten() self.cube.render(self.program) self.ctx.disable(self.ctx.DEPTH_TEST) # Draw the current cube texture self.use() self.clear() self.fbo1.color_attachments[0].use() self.quad_fs.render(self.quad_program) # Swap offscreen buffers self.fbo1, self.fbo2 = self.fbo2, self.fbo1 self.frame += 1
def mouseMoveEvent(self, event): pos = event.pos() # compute point on sphere under pointer (w, h) = self.viewport t = (2*self.old_pos.x() - w) / float(w) u = -(2*self.old_pos.y() - h) / float(h) # compute inverse of view transform ignoring rotation m = Matrix44.from_translation(Vector3([0, 0, -self.zoom])) * self.projTransform m = matrix44.inverse(m) rayOri = m * Vector3([t, u, -1]) rayEnd = m * Vector3([t, u, 1]) rayDir = rayEnd - rayOri self.picked = intersectRayUnitSphere(rayOri, rayDir) # rotate on left-drag if event.buttons() & QtCore.Qt.LeftButton > 0: # the rotation vector is the displacement vector rotated by 90 degrees dx = pos.x() - self.old_pos.x() dy = pos.y() - self.old_pos.y() if dx == 0 and dy == 0: return v = Vector3([dy, dx, 0]) # update the current orientation self.layers.multiplyOrientation(Quaternion.from_axis_rotation( -v.normalised, -v.length * 0.002, )) elif event.buttons() & QtCore.Qt.RightButton > 0: dz = pos.y() - self.old_pos.y() self.zoom = max(0, self.zoom + dz / 100.0) self.old_pos = pos self.update()
def on_render(self, gl_area, gl_context): glClearColor(0.0, 0.0, 0.0, 0.0) # Set the background colour for the window -> Black glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) # Clear the window background colour to black by resetting the COLOR_BUFFER and clear the DEPTH_BUFFER eye = (0.0, 5, 18.0) # Eye coordinates (location of the camera) target = (0.0, 7.0, 0.0 ) # Target coordinates (where the camera is looking) up = (0.0, 1.0, 0.0) # A vector representing the 'up' direction. view_matrix = Matrix44.look_at(eye, target, up) # Calculate the view matrix glUniformMatrix4fv(self.__location_viewMatrix, 1, GL_FALSE, view_matrix) model_matrix = Matrix44.from_translation( [0.0, 0.0, 0.0]) * pyrr.matrix44.create_from_axis_rotation( (0.0, 1.0, 0.0), self.application_clock) * Matrix44.from_scale( [1.0, 1.0, 1.0]) glUniformMatrix4fv( self.__location_modelMatrix, 1, GL_FALSE, model_matrix ) # Update the value of the ModelViewPerspective matrix attribute variable in the vertex buffer glBindVertexArray(self.chibi[0]) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glBindTexture(GL_TEXTURE_2D, self.chibi[2]) glDrawArrays(GL_TRIANGLES, 0, self.chibi[1]) self.queue_draw() # Schedules a redraw for Gtk.GLArea
def select_object(self, camera, x, y): red = green = blue = 8 def make_mask(bits): return 0xFFFFFFFF >> (32 - bits) red_mask = make_mask(red) << (green + blue) green_mask = make_mask(green) << blue blue_mask = make_mask(blue) red_shift = green + blue green_shift = blue for i, obj in enumerate(self.objects): r = ((i & red_mask) >> red_shift) / 255.0 g = ((i & green_mask) >> green_shift) / 255.0 b = (i & blue_mask) / 255.0 camera.push_matrix() camera.matrix *= Matrix44.from_translation(obj.position) * Matrix44.from_scale(obj.scale) obj.render_for_selection_hit(camera, r, g, b) camera.pop_matrix() data = struct.unpack('b'*3, glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE)) index = (data[0] << red_shift) | (data[1] << green_shift) | data[2] if self.objects and 0 <= index < len(self.objects): return self.objects[index] return None
def pos(self, val): if len(val) == 2: self._pos = val + [0.0] else: self._pos = val self._tm = Matrix44.from_translation(self._pos) self.dirty = True
def __init__(self, data): self.name = data.get("name") self.children = data.get("children") self.matrix = data.get("matrix") self.mesh = data.get("mesh") self.camera = data.get("camera") self.translation = data.get("translation") self.rotation = data.get("rotation") self.scale = data.get("scale") if self.matrix: self.matrix = Matrix44(self.matrix) else: self.matrix = Matrix44.identity() if self.translation is not None: self.matrix = self.matrix * Matrix44.from_translation( self.translation) if self.rotation is not None: quat = quaternion.create( x=self.rotation[0], y=self.rotation[1], z=self.rotation[2], w=self.rotation[3], ) self.matrix = self.matrix * Matrix44.from_quaternion( quat).transpose() if self.scale is not None: self.matrix = self.matrix * Matrix44.from_scale(self.scale)
def test_oo_examples(self): from pyrr import Quaternion, Matrix44, Vector3 import numpy as np point = Vector3([1.,2.,3.]) orientation = Quaternion() translation = Vector3() scale = Vector3([1.,1.,1.]) # translate along X by 1 translation += [1.0, 0.0, 0.0] # rotate about Y by pi/2 rotation = Quaternion.from_y_rotation(np.pi / 2.0) orientation = rotation * orientation # create a matrix # start our matrix off using the scale matrix = Matrix44.from_scale(scale) # apply our orientation # we can multiply matricies and quaternions directly! matrix = matrix * orientation # apply our translation translation = Matrix44.from_translation(translation) matrix = matrix * translation # transform our point by the matrix # vectors are transformable by matrices and quaternions directly point = matrix * point
def __init__(self, **kwargs): super().__init__(**kwargs) self.wnd.mouse_exclusivity = True self.prog = self.load_program('programs/lines/lines.glsl') self.prog['color'].value = (1.0, 1.0, 1.0, 1.0) self.prog['m_model'].write( Matrix44.from_translation((0.0, 0.0, -3.5), dtype='f4')) N = 10 # Create lines geometry def gen_lines(): for i in range(N): # A yield -1.0 yield 1.0 - i * 2.0 / N yield 0.0 # b yield 1.0 yield 1.0 - i * 2.0 / N yield 0.0 buffer = self.ctx.buffer( numpy.fromiter(gen_lines(), dtype='f4', count=N * 6).tobytes()) self.lines = self.ctx.vertex_array( self.prog, [ (buffer, '3f', 'in_position'), ], )
def generate_twig_from_file(self, filepath): f = open(filepath, 'r') for line in f: if line.startswith("sphere"): arr = line.split(" ") if len(arr) > 10: self.needle_num += 1 zenith_rotation_angle = degree_to_rad(float(arr[13])) azimuth_rotation_angle = degree_to_rad(float(arr[18])) translate_vector = Vector3([float(arr[20]), float(arr[21]), float(arr[22])]) matrix = Matrix44.from_y_rotation(zenith_rotation_angle) matrix = matrix * Matrix44.from_z_rotation(azimuth_rotation_angle) matrix = matrix * Matrix44.from_translation(translate_vector) # applying rotation newNeedle_vertexes = list(map(lambda x: matrix * Vector3(x), self.prim_needle.vertexes)) self.vertexes += newNeedle_vertexes f.close() # generate twig r = math.pi * self.twig_diameter / 6.0 lower_plane, upper_plane = [], [] for i in range(0, 360, 60): angle_rad = degree_to_rad(i) x = r * math.cos(angle_rad) y = r * math.sin(angle_rad) lower_plane.append([x, y, 0]) upper_plane.append([x, y, self.twig_length]) self.twig_vertexes = lower_plane + upper_plane
def tf2matrix4(tf: carla.Transform) -> Matrix44: t = Matrix44.from_translation( [tf.location.x, tf.location.y, tf.location.z]) r = Matrix44.from_eulers([ tf.rotation.roll * math.pi / 180, tf.rotation.pitch * math.pi / 180, tf.rotation.yaw * math.pi / 180 ]) return r * t
def render(self, t): gl.glEnable(gl.GL_DEPTH_TEST) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) M = np.eye(4, dtype=np.float32) M = M * Matrix44.from_scale((.5, .5, .5)) M = M * Matrix44.from_translation((0, 0, -2)) M = M * Matrix44.from_x_rotation(0) M = M * Matrix44.from_scale((.4, .4, .4)) M = M * Matrix44.from_translation((0, 0, -50)) projection = pyrr.matrix44.create_perspective_projection( 3, 1, 0.001, 10000) self.tree.setProjection(projection) self.tree.setModelView(M) self.tree.render() gl.glDisable(gl.GL_DEPTH_TEST)
def buildTransMatrix(pos=[0, 0, 0], rot=[0, 0, 0], scale=[1, 1, 1]): trans = Matrix44.from_translation(pos) rotX = Matrix44.from_x_rotation(np.radians(rot[0])) rotY = Matrix44.from_y_rotation(np.radians(rot[1])) rotZ = Matrix44.from_z_rotation(np.radians(rot[2])) scale = Matrix44.from_scale(scale) tMatrix = trans * scale * rotX * rotY * rotZ return tMatrix
def buildBoneMatrices(tree, parentmat): trans = tree['transform'] translate = Matrix44.from_translation(trans['position']) rotate = Quaternion(trans['rotation']).matrix44 mat = mats[tree['bone']] = rotate * translate * parentmat for x in tree['children']: buildBoneMatrices(x, mat)
def build_matrix(self): """Builds and stores the viewport matrix internally Automatically builds the MVP matrix as well""" # Note that by nature, a camera perspective inverts everything # So we negate everything and also do it in reverse # Overrides PositionMatrix, reverse everything, ignore scale m = Matrix44.identity() m = Matrix44.from_translation(-1 * Vector3(self.position)) * m m = Matrix44.from_z_rotation(-math.radians(self.roll)) * m m = Matrix44.from_y_rotation(-math.radians(self.yaw)) * m m = Matrix44.from_x_rotation(-math.radians(self.pitch)) * m if self.tp: # Third person enabled m = Matrix44.from_translation([0, 0, -self.tp_distance]) * m self.m = m self.mvp = numpy.array(self.p * self.m).astype("f4")
def setTranslation(self, up, right, behind): #only done once by the Cube. #up=Vector3([0,up,0]) #right=Vector3([right,0,0]) #behind=Vector3([0,0,-1*behind]) self.translation = Matrix44.from_translation( [-right * 1.0 + 1.0, up * 1.0 - 1.0, 1.0 * behind - 1.0]) #print(self.translation) for i in self.faces: i.setTranslation(self.translation)
def resize (self: 'GLQuadRenderer', width: int, height: int) -> None: super ().resize (width, height) if not self.__loaded: return y = self.__image_height / self.__image_width * \ self.gl_widget.width / self.gl_widget.height x = self.__image_width / self.__image_height * \ self.gl_widget.height / self.gl_widget.width if self.gl_widget.height * self.__image_width / self.__image_height > self.gl_widget.width: self.world = Matrix44.from_scale ([1, y, 1]) * \ Matrix44.from_translation ([0, (1 - y) / 2, 0]) else: self.world = Matrix44.from_scale ([x, 1, 1]) * \ Matrix44.from_translation ([(1 - x) / 2, 0, 0]) GL.glUniformMatrix4fv (self.__uniform_world, 1, False, self.world)
def render(self, app, currentTime): glBindVertexArray(self._vao.identifier) try: glUseProgram(self._program.identifier) bg_color = ( math.sin(currentTime) * 0.5 + 0.5, math.cos(currentTime) * 0.5 + 0.5, 0.0, 1.0 ) glClearBufferfv(GL_COLOR, 0, bg_color) glClearBufferfv(GL_DEPTH, 0, [1]) f = currentTime * 0.3 mv_matrix = Matrix44.identity(dtype='f4') mv_matrix *= Matrix44.from_x_rotation( currentTime * math.radians(81)) mv_matrix *= Matrix44.from_y_rotation( currentTime * math.radians(45)) mv_matrix *= Matrix44.from_translation([ math.sin(2.1 * f) * 0.5, math.cos(1.7 * f) * 0.5, math.sin(1.3 * f) * math.cos(1.5 * f) * 2.0]) mv_matrix *= Matrix44.from_translation([0.0, 0.0, -4.0]) self._uniform_block.mv_matrix[:] = mv_matrix.reshape(16) glBufferSubData( GL_UNIFORM_BUFFER, 0, ctypes.sizeof(self._uniform_block), ctypes.byref(self._uniform_block)) self._torus_obj.render() finally: glBindVertexArray(NULL_GL_OBJECT)
def init(wid, hig): """Initialises the display.""" global modelmtx, chaem GL.glClearColor(0.0, 0.2, 0.15, 0.0) GL.glClearDepth(1.0) GL.glDepthFunc(GL.GL_LESS) GL.glEnable(GL.GL_DEPTH_TEST) GL.glShadeModel(GL.GL_SMOOTH) shades() rematr(wid, hig) modelmtx = matrix.from_scale([2, 2, 2]) * matrix.from_translation([0, 0, -.5]) chaem = Raimv((), deltam) chaem.rotspe = 2*pi GL.glUniformMatrix4fv(GL.glGetUniformLocation(shaderp, 'viewmatrix'), 1, False, chaem.lookat()) GL.glUniformMatrix4fv(GL.glGetUniformLocation(shaderp, 'modelmatrix'), 1, False, modelmtx)
def getModelMatrix(self): scale = mat4.from_scale([0.2, 0.2, 0.2]) roty = mat4.from_y_rotation(-self.hAngle) vdiff = self.vAngle - self.oldvAngle rotx = mat4.from_x_rotation(self.getxRot(vdiff)) zdiff = self.hAngle - self.oldhAngle rotz = mat4.from_z_rotation(-self.getzRot(zdiff)) trans = mat4.from_translation(self.position, dtype='f') self.oldhAngle = self.hAngle self.oldvAngle = self.vAngle return scale * rotz * rotx * roty * trans
def init(): """Initialises the display.""" global projectmatrix, modelmatrix, chaem GL.glClearColor(0.0, 0.2, 0.15, 0.0) GL.glClearDepth(1.0) GL.glDepthFunc(GL.GL_LESS) GL.glEnable(GL.GL_DEPTH_TEST) GL.glShadeModel(GL.GL_SMOOTH) shades() chaem = Fremv((), deltam) GL.glUniform3f(GL.glGetUniformLocation(shaderp, 'lightColour'), *[1.0, 1.0, 1.0]) modelmatrix = matrix.from_scale([2, 2, 2]) * matrix.from_translation([0, 0, -1]) wid, hig = window.get_size() hig = hig or 1 projectmatrix = matrix.perspective_projection(whel, wid/hig, 0.01, 100) rematr()
def draw(): """Put the main drawing code in here.""" global luxp chaem.mochae(timedelta) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glEnable(GL.GL_TEXTURE_2D) GL.glUseProgram(shaderp) luxp = [sin(lasttime) * 5, cos(lasttime) * 5, 0.0] GL.glUniform3f(GL.glGetUniformLocation(shaderp, 'lightPos'), *luxp) GL.glUniform3f(GL.glGetUniformLocation(shaderp, 'viewpos'), *chaem.pos) rematr() architincture.draw() mmoodd = modelmatrix * matrix.from_scale([0.2, 0.2, 0.2]) * matrix.from_translation(luxp) * \ matrix.from_eulers([lasttime, lasttime, lasttime]) lux.draw(rematr, mmoodd)
def paintGL(self): glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_CULL_FACE) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glFrontFace(GL_CCW) glCullFace(GL_BACK if self.zoom > 1.0 else GL_FRONT) self.mesh.bind() for layer in self.layers: layer.shader.bind() # show picked point array = (GLdouble * 3)() if layer.picked is None: array[0] = 0 array[1] = 0 array[2] = 0 else: p = layer.orientation.conjugate.matrix33 * layer.picked array[0] = p.x array[1] = p.y array[2] = p.z layer.shader.uniformf_vec3('picked', array) layer.shader.uniformf('alphaFactor', layer.alpha()) m = layer.orientation.matrix33 array = (GLdouble * 9)() for i in xrange(3): for j in xrange(3): array[3*i + j] = m[i,j] layer.shader.uniformf_m3x3('orientation', array) # setup view transform m = self.projTransform m = Matrix44.from_translation(Vector3([0, 0, -self.zoom])) * m array = (GLdouble * 16)() for i in xrange(4): for j in xrange(4): array[4*i + j] = m[i,j] layer.shader.uniformf_m4x4('viewTransform', array) glActiveTexture(GL_TEXTURE0 + layer.texture_id) layer.sphere.bind_glsl_texture(layer.texture_id, layer.shader) self.mesh.draw_triangles(layer.shader.handle)
def getModelMatrix(self): rot = mat4.from_y_rotation(self.rot, dtype='f') trans = mat4.from_translation(self.position, dtype='f') return rot * trans
def getModelMatrix(self): # TODO: maybe spin planet around another axis and add scaling rot = mat4.from_y_rotation(self.rot, dtype='f') trans = mat4.from_translation(self.position, dtype='f') return rot * trans
def matrix(self): return (Matrix44.from_translation(self._translation) * self._rotation.matrix44)