Example #1
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]
Example #2
0
    def _gl_look_at(self, pos, target, up) -> numpy.ndarray:
        """The standard lookAt method.

        Args:
            pos: current position
            target: target position to look at
            up: direction up
        Returns:
            numpy.ndarray: The matrix
        """
        z = vector.normalise(pos - target)
        x = vector.normalise(vector3.cross(vector.normalise(up), z))
        y = vector3.cross(z, x)

        translate = Matrix44.identity(dtype="f4")
        translate[3][0] = -pos.x
        translate[3][1] = -pos.y
        translate[3][2] = -pos.z

        rotate = Matrix44.identity(dtype="f4")
        rotate[0][0] = x[0]  # -- X
        rotate[1][0] = x[1]
        rotate[2][0] = x[2]
        rotate[0][1] = y[0]  # -- Y
        rotate[1][1] = y[1]
        rotate[2][1] = y[2]
        rotate[0][2] = z[0]  # -- Z
        rotate[1][2] = z[1]
        rotate[2][2] = z[2]

        return rotate * translate
Example #3
0
def get_rotation(x, y, z):
    logger.debug('Create rotation matrix with (x:{}, y:{}, z:{})'.format(
        x, y, z))
    x_rotation = Matrix44.from_x_rotation(x)
    y_rotation = Matrix44.from_y_rotation(y)
    z_rotation = Matrix44.from_z_rotation(z)
    return z_rotation * y_rotation * x_rotation
    def render(self, time: float, frame_time: float):
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)

        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1,
                                               1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        self.use_texture.value = False

        self.light.value = (67.69, -8.14, 52.49)
        self.mvp.write((proj * lookat * rotate).astype('f4').tobytes())

        self.color.value = (0.67, 0.49, 0.29)
        self.vao_ground.render()

        self.color.value = (0.46, 0.67, 0.29)
        self.vao_grass.render()

        self.color.value = (1.0, 1.0, 1.0)
        self.vao_billboard.render()

        self.color.value = (0.2, 0.2, 0.2)
        self.vao_holder.render()

        self.use_texture.value = True
        self.texture.use()

        self.vao_image.render()
Example #5
0
File: mesh.py Project: ksons/ln.py
 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)
Example #6
0
    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()
Example #7
0
 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 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
Example #9
0
    def render(self):
        if self.current_pointcloud < len(self.pointclouds):
            self.handle_mouse()
            self.handle_keys()

            self.ctx.viewport = self.wnd.viewport
            self.ctx.clear(0.0, 0.0, 0.0)
            self.ctx.enable(mgl.BLEND)

            vertices = np.load(file=self.pointclouds[self.current_pointcloud])
            self.vbo.write(vertices.astype('f4').tobytes())

            model = Matrix44.from_scale((self.zoom, self.zoom, self.zoom))
            model *= Matrix44.from_x_rotation(-self.theta[1])
            model *= Matrix44.from_y_rotation(-self.theta[0])
            view = Matrix44.look_at((0.0, 0.0, 1.0), (0.0, 0.0, 0.0),
                                    (0.0, 1.0, 0.0))
            projection = Matrix44.perspective_projection(
                45.0, self.wnd.ratio, 0.1, 100.0)

            self.mvp.write((projection * view * model).astype('f4').tobytes())
            self.vao.render(mode=mgl.POINTS)

            self.sleep_to_target_fps(60)
            self.current_pointcloud += 1
        else:
            if self.out_dir is None:
                self.current_pointcloud = 0
            else:
                QtCore.QCoreApplication.instance().quit()
Example #10
0
    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
Example #11
0
 def processData(data):
     if isinstance(data, Matrix44):
         return data
     elif isinstance(data, list) and len(data) == 3:
         return Matrix44([data[0], data[1], data[2], data[3]])
     else:
         return Matrix44()
Example #12
0
    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
Example #13
0
    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
Example #14
0
 def __init__(self):
     self.color = Color(0.0, 0.0, 0.0)
     self.aabb = aabb.create_from_bounds([0.0, 0.0, 0.0], [0.5, 0.5, 0.5])
     self.translation_matrix = Matrix44.identity()
     self.scale_matrix = Matrix44.identity()
     self.rotation_matrix = Matrix44.identity()
     self.selected = False
Example #15
0
    def render(self):
        angle = self.wnd.time * 0.2
        width, height = self.wnd.size
        self.ctx.viewport = self.wnd.viewport
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST)

        camera_pos = (np.cos(angle) * 5.0, np.sin(angle) * 5.0, 2.0)

        proj = Matrix44.perspective_projection(45.0, width / height, 0.1,
                                               1000.0)
        lookat = Matrix44.look_at(
            camera_pos,
            (0.0, 0.0, 0.5),
            (0.0, 0.0, 1.0),
        )

        self.mvp.write((proj * lookat).astype('f4').tobytes())
        self.light.value = camera_pos

        crate_z = np.sin(self.crate_a * self.wnd.time + self.crate_b) * 0.2
        coordinates = np.dstack([self.crate_x, self.crate_y, crate_z])

        self.vbo2.write(coordinates.astype('f4').tobytes())
        self.vao.render(instances=1024)
Example #16
0
    def look_at(self, position, target, world_up):
        # 1.Position = known
        # 2.Calculate cameraDirection
        zaxis = vector.normalise(position - target)
        # 3.Get positive right axis vector
        xaxis = vector.normalise(
            vector3.cross(vector.normalise(world_up), zaxis))
        # 4.Calculate the camera up vector
        yaxis = vector3.cross(zaxis, xaxis)

        # create translation and rotation matrix
        translation = Matrix44.identity()
        translation[3][0] = -position.x
        translation[3][1] = -position.y
        translation[3][2] = -position.z

        rotation = Matrix44.identity()
        rotation[0][0] = xaxis[0]
        rotation[1][0] = xaxis[1]
        rotation[2][0] = xaxis[2]
        rotation[0][1] = yaxis[0]
        rotation[1][1] = yaxis[1]
        rotation[2][1] = yaxis[2]
        rotation[0][2] = zaxis[0]
        rotation[1][2] = zaxis[1]
        rotation[2][2] = zaxis[2]

        return translation * rotation
Example #17
0
    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
Example #18
0
def render(ctx, prog, objects, fbo, q, x, img):
    print(q)
    m = q.rotation_matrix
    #q から 回転ベクトルだけ取り出して 変換かければ良さそう
    eye = np.array([47.697, -8.147, 24.498])
    eyedir = np.array([-47.7, 8.15, -16.5])
    up = np.array([0.0, 0.0, 1.0])
    mvp = prog['Mvp']
    proj = Matrix44.perspective_projection(58.0, float(W) / H, 0.1, 1000.0)
    lookat = Matrix44.look_at(
        eye,
        np.dot(m, eyedir) + eye,
        np.dot(m, up),
    )
    print(m)

    mvp.write((proj * lookat).astype('f4').tobytes())

    color = prog['Color']
    fbo.clear(0.0, 0.0, 0.0, 0.0)

    color.value = (0.67, 0.49, 0.29)
    objects['ground'].render()

    color.value = (0.46, 0.67, 0.29)
    objects['grass'].render()

    myimg = np.asarray(
        Image.frombytes('RGBA', fbo.size, fbo.read(components=4)))
    obj_mask = myimg[:, :, 3]
    obj_img = myimg[:, :, 0:3]
    idx = (obj_mask != 0)
    img[idx] = obj_img[idx]
    cv2.imshow('RealSense', img)
    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)
Example #20
0
    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)
Example #21
0
    def __init__(self,
                 width=1280,
                 height=720,
                 name='OpenGL Window',
                 cameraSpeed=0.1,
                 mouseSpeed=0.3,
                 invertMouse=False,
                 resizable=False,
                 vsync=False):
        super().__init__(width, height, name, resizable=resizable, vsync=vsync)
        self.cameraSpeed = cameraSpeed
        self.mouseSpeed = mouseSpeed
        self.invertMouse = invertMouse
        self.cameraPos = Vector3([0.0, 0.0, 0.0])
        self.cameraTarget = Vector3([0.0, 0.0, -1.0])
        self.cameraUp = Vector3([0.0, 1.0, 0.0])
        self.worldUp = Vector3([0.0, 1.0, 0.0])
        self.yaw = -90.0
        self.pitch = 0.0
        self.pressedKeys = []

        self.set_mouse_visible(False)
        self.set_exclusive_mouse(True)

        # Matrices
        self.projection = Matrix44.perspective_projection(
            45.0, width / height, 0.1, 1000.0)
        self.view = Matrix44.look_at(self.cameraPos, self.cameraTarget,
                                     self.cameraUp)
Example #22
0
    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
Example #23
0
    def init(self, width, height, render_samples=16):
        if not self._initialized:
            self.ctx = ContextManager.get_offscreen_context()

            self._scene = Scene(self.ctx)
            self._scene.init()

            # A fullscreen quad just for rendering one pass to offscreen textures
            self.quad_fs = QuadFS(self.ctx)
            self.quad_fs.m_model.write(
                Matrix44.identity().astype('f4').tobytes())
            self.quad_fs.m_view.write(
                Matrix44.identity().astype('f4').tobytes())
            self.quad_fs.m_proj.write(
                Matrix44.orthogonal_projection(-1, 1, 1, -1, 1,
                                               10).astype('f4').tobytes())
            self.quad_fs.flip_v.value = 0

            # aa sampler
            self.setRenderSamples(render_samples)

            self._initialized = True
            print("Workbench initialized")

        if (self._width, self._height) != (width, height):
            self.resize(width, height)
Example #24
0
    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
Example #25
0
    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)
Example #26
0
    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, time: float, frame_time: float):
        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, 1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        self.use_texture.value = False

        self.light.value = (67.69, -8.14, 52.49)
        self.mvp.write((proj * lookat * rotate).astype('f4').tobytes())

        self.color.value = (0.67, 0.49, 0.29)
        self.objects['ground'].render()

        self.color.value = (0.46, 0.67, 0.29)
        self.objects['grass'].render()

        self.color.value = (1.0, 1.0, 1.0)
        self.objects['billboard'].render()

        self.color.value = (0.2, 0.2, 0.2)
        self.objects['billboard-holder'].render()

        self.use_texture.value = True
        self.texture.use()

        self.objects['billboard-image'].render()
Example #28
0
    def __init__(self, cam_intrinsic_settings = CameraIntrinsicSettings(), scene_object = None):
        super(Camera, self).__init__(scene_object)

        self.camera_matrix = Matrix44.identity()
        self.projection_matrix = Matrix44.identity()

        self.set_instrinsic_settings(cam_intrinsic_settings)
Example #29
0
    def update(self):
        """
        Updates the camera's view matricies to match the camera's settings.
        """
        eye = self.eye
        at = self.at
        up = self.up

        # orthonormalization of camera axes
        n = (eye - at).normalised
        u = up.cross(n).normalised
        v = n.cross(u)
        # camera view matrix
        self.view = Matrix44([[u.x, u.y, u.z, -u.dot(eye)],
                              [v.x, v.y, v.z, -v.dot(eye)],
                              [n.x, n.y, n.z, -n.dot(eye)], [0, 0, 0, 1]])

        fovx = self.fovx
        aspect = self.aspect
        near = self.near
        far = self.far

        # symmetrical perspective projection matrix
        recip_tan_fov = 1 / np.tan(fovx / 2)
        a = recip_tan_fov
        b = aspect * recip_tan_fov
        c = -(far + near) / (far - near)
        d = -2 * far * near / (far - near)
        self.proj = Matrix44([[a, 0, 0, 0], [0, b, 0, 0], [0, 0, c, d],
                              [0, 0, -1, 0]])
Example #30
0
 def rotate_relative(self, rotation):
     pos = self.get_position()
     rotate_matrix = Matrix44.from_x_rotation(rotation.x) * \
                     Matrix44.from_y_rotation(rotation.y) * \
                     Matrix44.from_z_rotation(rotation.z)
     self.matrix = rotate_matrix * self.matrix
     self.set_position(pos)
    def __init__(self, ctx, width, height, Type, id):
        self.ctx = ctx
        self.type = Type
        self.ParentCube = id
        self.color = self.fromTypeToColor(self.type)
        self.width = width
        self.height = height
        self.x_rot = 0
        self.y_rot = 0
        self.x_last = 0
        self.y_last = 0
        self.x_cur = 0
        self.y_cur = 0
        self.isRotating = False
        self.orientation = pyrr.quaternion.create(0.0, 0.0, 0.0, 1.0)
        self.proj = Matrix44.perspective_projection(45.0,
                                                    self.width / self.height,
                                                    0.1, 100.0)
        self.camera_pos = [0, 3, -8.0]
        self.vertexes = VERTICES[self.fromTypeTOIndex(Type)]
        self.rotation = Matrix44.identity()
        self.rotationLayer = Matrix44.identity()
        self.degree = 0
        self.translation = Matrix44.identity()
        self.view = Matrix44.look_at(
            self.camera_pos,  # position of camera in world coordinate
            (0.0, 0.0, 0.0),  # target
            (0.0, 1.0, 0.0),
        )
        self.prog = self.ctx.program(
            vertex_shader='''
                #version 330

                uniform mat4 Mvp;
                in vec3 in_vert;
                in vec3 in_color;
                out vec3 v_color;  
                out vec4 Position;
                void main() {
                    gl_Position = Mvp*vec4(in_vert, 1.0);
                    v_color = in_color;
                    Position=vec4(in_vert,1.0);
                }
            ''',
            fragment_shader='''
                #version 330
                in vec3 v_color;
                in vec4 Position;
                out vec4 f_color;
                
                void main() 
                {
                    f_color=vec4(v_color,1);
                   
                    
                }

            ''',
        )
Example #32
0
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 update(dt):
    ctx.viewport = (0, 0, wnd.width, wnd.height)
    ctx.clear(0.9, 0.9, 0.9)
    ctx.enable(ModernGL.DEPTH_TEST)

    proj = Matrix44.perspective_projection(45.0, wnd.width / wnd.height, 0.1, 1000.0)
    lookat = Matrix44.look_at(
        (40.0, 30.0, 20.0),
        (0.0, 0.0, 0.0),
        (0.0, 0.0, 1.0),
    def draw(self, *args):
        width, height = Window.size
        self.ctx.viewport = (0, 0, width, height)
        self.ctx.clear(0.9, 0.9, 0.9)
        self.ctx.enable(ModernGL.DEPTH_TEST)

        proj = Matrix44.perspective_projection(45.0, width / height, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            (40.0, 30.0, 20.0),
            (0.0, 0.0, 0.0),
            (0.0, 0.0, 1.0),
Example #35
0
    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, 1000.0)
        lookat = Matrix44.look_at(
            (40.0, 30.0, 30.0),
            (0.0, 0.0, 0.0),
            (0.0, 0.0, 1.0),
        )

        self.mvp.write((proj * lookat).astype('f4').tobytes())
        self.vao.render(moderngl.LINES)
Example #36
0
    def render(self):
        self.ctx.screen.viewport = self.wnd.viewport
        self.ctx.clear(1.0, 1.0, 1.0)
        with self.ctx.scope(mgl.DEPTH_TEST):
            proj = Matrix44.perspective_projection(45.0, self.wnd.ratio, 0.1, 1000.0)
            lookat = Matrix44.look_at(
                (40.0, 30.0, 30.0),
                (0.0, 0.0, 0.0),
                (0.0, 0.0, 1.0),
            )

            self.prog['Mvp'] = (proj * lookat).astype('f4').tobytes()
            self.vao.render(mgl.LINES)
    def render(self, time, frame_time):
        angle = time * 0.2
        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, 1000.0)
        lookat = Matrix44.look_at(
            (np.cos(angle), np.sin(angle), 0.8),
            (0.0, 0.0, 0.1),
            (0.0, 0.0, 1.0),
        )

        self.mvp.write((proj * lookat).astype('f4').tobytes())
        self.vao.render(moderngl.TRIANGLE_STRIP)
Example #38
0
    def render(self, time: float, frame_time: float):
        camera_pos = (np.cos(time) * 300.0, np.sin(time) * 300.0, 120.0)
        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            camera_pos,
            (0.0, 0.0, 50.0),
            (0.0, 0.0, 1.0),
        )

        with self.scope:
            self.prog['Mvp'] = (proj * lookat).astype('f4').tobytes()
            self.prog['Eye'] = camera_pos
            self.ctx.clear(1.0, 1.0, 1.0)
            self.vao.render()
Example #39
0
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)
Example #40
0
 def resizeGL(self, w, h):
     glViewport(0, 0, w, h)
     self.viewport = (w, h)
     self.projTransform = Matrix44.perspective_projection(
         50, float(w) / h,
         0.01, 100.0,
     )
Example #41
0
 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()
Example #42
0
def rematr(wid, hig):
    """Resets the projection matrix."""
    if hig == 0:
        hig = 1
    # This method has FOV in degrees for some reason???
    pm = matrix.perspective_projection(whel, wid/hig, 0.01, 100)
    GL.glUniformMatrix4fv(GL.glGetUniformLocation(shaderp, 'projectmatrix'), 1, False, pm)
Example #43
0
def onsc(window, yof):
    """Wheels. """
    global whel
    sz = window.get_size()
    whel = clip(whel - yof, 1, 180)
    pm = matrix.perspective_projection(whel, sz[0] / sz[1], 0.01, 100)
    GL.glUniformMatrix4fv(GL.glGetUniformLocation(shaderp, 'projectmatrix'), 1, False, pm)
Example #44
0
  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
Example #45
0
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 render(self, time, frame_time):
        angle = time
        self.ctx.clear(1.0, 1.0, 1.0)

        camera_pos = (np.cos(angle) * 5.0, np.sin(angle) * 5.0, 2.0)

        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            camera_pos,
            (0.0, 0.0, 0.0),
            (0.0, 0.0, 1.0),
        )

        self.prog['Mvp'] = (proj * lookat).astype('f4').tobytes()
        self.prog['Light'] = camera_pos
        self.vao.render()
Example #47
0
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 render(self, time, frame_time):
        self.ctx.clear(1.0, 1.0, 1.0)
        # self.ctx.enable(mgl.DEPTH_TEST)
        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        w, h = self.texture.size
        gw, gh = 16, 16
        nx, ny, nz = int(w/gw), int(h/gh), 1

        print('=' * 50)

        self.compute['time'] = time
        GL_WRITE_ONLY = 0x88B9
        GL_R32F = 0x822E
        self.texture.bind_to_image(0,GL_WRITE_ONLY, GL_R32F)
        self.compute.run(nx, ny, nz)
        print('-' * 50)

        with self.scope:
            self.prog['UseTexture'] = False

            self.prog['Light'] = (67.69, -8.14, 52.49)
            self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

            self.prog['Color'] = (0.67, 0.49, 0.29)
            self.objects['ground'].render()

            self.prog['Color'] = (0.46, 0.67, 0.29)
            self.objects['grass'].render()

            self.prog['Color'] = (1.0, 1.0, 1.0)
            self.objects['billboard'].render()

            self.prog['Color'] = (0.2, 0.2, 0.2)
            self.objects['billboard-holder'].render()

            self.prog['UseTexture'] = True

            self.objects['billboard-image'].render()
    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, 1000.0)
        lookat = Matrix44.look_at(
            (-85, -180, 140),
            (0.0, 0.0, 65.0),
            (0.0, 0.0, 1.0),
        )

        self.light.value = (-140.0, -300.0, 350.0)
        self.color.value = (1.0, 1.0, 1.0, 0.25)
        self.mvp.write((proj * lookat).astype('f4').tobytes())

        self.texture.use()
        self.vao.render()
    def render(self):
        angle = self.wnd.time
        self.ctx.screen.viewport = self.wnd.viewport

        camera_pos = (np.cos(angle) * 5.0, np.sin(angle) * 5.0, 2.0)

        proj = Matrix44.perspective_projection(45.0, self.wnd.ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            camera_pos,
            (0.0, 0.0, 0.5),
            (0.0, 0.0, 1.0),
        )

        self.prog['Mvp'] = (proj * lookat).astype('f4').tobytes()
        self.prog['Light'] = camera_pos

        self.ctx.replay(self.bytecode)
Example #51
0
    def test_m44_q_equivalence(self):
        """Test for equivalance of matrix and quaternion rotations.

        Create a matrix and quaternion, rotate each by the same values
        then convert matrix<->quaternion and check the results are the same.
        """
        m = Matrix44.from_x_rotation(np.pi / 2.)
        mq = Quaternion.from_matrix(m)

        q = Quaternion.from_x_rotation(np.pi / 2.)
        qm = Matrix44.from_quaternion(q)

        self.assertTrue(np.allclose(np.dot([1., 0., 0., 1.], m), [1., 0., 0., 1.]))
        self.assertTrue(np.allclose(np.dot([1., 0., 0., 1.], qm), [1., 0., 0., 1.]))

        self.assertTrue(np.allclose(q * Vector4([1., 0., 0., 1.]), [1., 0., 0., 1.]))
        self.assertTrue(np.allclose(mq * Vector4([1., 0., 0., 1.]), [1., 0., 0., 1.]))

        np.testing.assert_almost_equal(np.array(q), np.array(mq), decimal=5)
        np.testing.assert_almost_equal(np.array(m), np.array(qm), decimal=5)
    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)
Example #53
0
    def render(self, time, frame_time):
        self.ctx.clear(1.0, 1.0, 1.0)
        self.bg_texture.use()
        self.ctx.enable_only(moderngl.BLEND)
        self.canvas_vao.render(moderngl.TRIANGLE_STRIP)
        self.ctx.enable_only(moderngl.DEPTH_TEST)

        proj = Matrix44.perspective_projection(30.0, self.aspect_ratio, 1.0, 1000.0)
        lookat = Matrix44.look_at(
            (46.748, -280.619, 154.391),
            (-23.844, 2.698, 44.493),
            (0.0, 0.0, 1.0),
        )

        self.mvp.write((proj * lookat).astype('f4').tobytes())
        self.light.value = (-143.438, -159.072, 213.268)
        self.mug_texture.use()
        self.mug_vao.render()
        self.ctx.enable_only(moderngl.DEPTH_TEST | moderngl.BLEND)
        self.sticker_texture.use()
        self.sticker_vao.render(moderngl.TRIANGLE_STRIP)
    def render(self, time, frame_time):
        angle = time * 0.2
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST)

        camera_pos = (np.cos(angle) * 5.0, np.sin(angle) * 5.0, 2.0)

        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            camera_pos,
            (0.0, 0.0, 0.5),
            (0.0, 0.0, 1.0),
        )

        self.mvp.write((proj * lookat).astype('f4').tobytes())
        self.light.value = camera_pos

        crate_z = np.sin(self.crate_a * time + self.crate_b) * 0.2
        coordinates = np.dstack([self.crate_x, self.crate_y, crate_z])

        self.vbo2.write(coordinates.astype('f4').tobytes())
        self.vao.render(instances=1024)
Example #55
0
def main():
    window = initWindow()
    classicProgram, normalMapProgram, skyboxProgram, asteroidProgram = initShaders()
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LESS)

    # Initialize objects
    planets, spaceship, skybox, belt = initObjects(classicProgram, normalMapProgram,
                                             skyboxProgram, asteroidProgram)

    projMatrix = mat4.perspective_projection(60,
                                             float(WIDTH/HEIGHT),
                                             0.1,
                                             10000.0,
                                             dtype='f')
    eye, viewMatrix = initCamera()

    dt, oldTime = 0.0, glfw.GetTime()
    animation_speed = 800
    while not glfw.WindowShouldClose(window):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        currentTime = glfw.GetTime()
        dt = currentTime - oldTime
        oldTime = currentTime

        hAngle, vAngle, eye, direction, right, up, viewMatrix, animation_speed = getNewViewMatrixAndEye(window,
                                                                  animation_speed,
                                                                  dt,
                                                                  eye,
                                                                  WIDTH,
                                                                  HEIGHT)

        for planet in planets:
            planet.update(animation_speed)
            planet.draw(eye, viewMatrix, projMatrix)

        spaceship.update(eye, direction, right, up, hAngle, vAngle)
        spaceship.draw(eye, viewMatrix, projMatrix)

        belt.update(0.1)
        belt.draw(eye, viewMatrix, projMatrix)

        skybox.draw(viewMatrix, projMatrix)
        # Swap front and back buffers
        glfw.SwapBuffers(window)

        # Poll for and process events
        glfw.PollEvents()

    glfw.Terminate()
Example #56
0
    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 render(self):
        angle = self.wnd.time
        self.ctx.screen.viewport = self.wnd.viewport
        self.ctx.clear(1.0, 1.0, 1.0)

        with self.ctx.scope(mgl.DEPTH_TEST):
            camera_pos = (np.cos(angle) * 20.0, np.sin(angle) * 20.0, 5.0)

            proj = Matrix44.perspective_projection(45.0, self.wnd.ratio, 0.1, 1000.0)
            lookat = Matrix44.look_at(
                camera_pos,
                (0.0, 0.0, 0.5),
                (0.0, 0.0, 1.0),
            )

            self.prog['Mvp'] = (proj * lookat).astype('f4').tobytes()
            self.prog['Light'] = camera_pos

            # self.vbo2.write(Matrix33.from_z_rotation(self.wnd.time).astype('f4').tobytes(), offset=24)
            self.vbo2.write(b''.join(struct.pack(
                '15f',
                *car['color'],
                *car['pos'],
                1.0, 0.0, 0.0,
                0.0, 1.0, 0.0,
                0.0, 0.0, 1.0,
            ) for car in cars))
            self.vao.render(instances=len(cars))
            self.vbo2.write(b''.join(struct.pack(
                '15f',
                0.0, 0.0, 0.0,
                *car['pos'],
                1.0, 0.0, 0.0,
                0.0, 1.0, 0.0,
                0.3, 0.6, 0.0,
            ) for car in cars))
            self.vao.render(instances=len(cars))
    def render(self):
        width, height = self.wnd.size
        self.ctx.screen.viewport = self.wnd.viewport
        self.ctx.clear(1.0, 1.0, 1.0)
        with self.ctx.scope(mgl.DEPTH_TEST):

            proj = Matrix44.perspective_projection(45.0, width / height, 0.1, 1000.0)
            lookat = Matrix44.look_at(
                (47.697, -8.147, 24.498),
                (0.0, 0.0, 8.0),
                (0.0, 0.0, 1.0),
            )

            rotate = Matrix44.from_z_rotation(np.sin(self.wnd.time) * 0.5 + 0.2)

            self.prog['UseTexture'] = False

            self.prog['Light'] = (67.69, -8.14, 52.49)
            self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

            self.prog['Color'] = (0.67, 0.49, 0.29)
            self.objects['ground'].render()

            self.prog['Color'] = (0.46, 0.67, 0.29)
            self.objects['grass'].render()

            self.prog['Color'] = (1.0, 1.0, 1.0)
            self.objects['billboard'].render()

            self.prog['Color'] = (0.2, 0.2, 0.2)
            self.objects['billboard-holder'].render()

            self.prog['UseTexture'] = True
            # self.texture.use()
            self.sampler.use()

            self.objects['billboard-image'].render()
    def render(self, time, frame_time):
        self.ctx.clear(1.0, 1.0, 1.0)
        # self.ctx.enable(mgl.DEPTH_TEST)
        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        self.fbo.clear(0, (1.0, 1.0, 1.0))
        self.fbo.clear(-1, 1.0)
        for scope in [self.scope1, self.scope2]:
            with scope:
                self.prog['UseTexture'] = False

                self.prog['Light'] = (67.69, -8.14, 52.49)
                self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

                self.prog['Color'] = (0.67, 0.49, 0.29)
                self.objects['ground'].render()

                self.prog['Color'] = (0.46, 0.67, 0.29)
                self.objects['grass'].render()

                self.prog['Color'] = (1.0, 1.0, 1.0)
                self.objects['billboard'].render()

                self.prog['Color'] = (0.2, 0.2, 0.2)
                self.objects['billboard-holder'].render()

                self.prog['UseTexture'] = True

                self.objects['billboard-image'].render()
    def render(self, time, frame_time):
        angle = time
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST)

        camera_pos = (np.cos(angle) * 20.0, np.sin(angle) * 20.0, 5.0)

        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            camera_pos,
            (0.0, 0.0, 0.5),
            (0.0, 0.0, 1.0),
        )

        self.mvp.write((proj * lookat).astype('f4').tobytes())
        self.light.value = camera_pos

        # self.vbo2.write(Matrix33.from_z_rotation(self.wnd.time).astype('f4').tobytes(), offset=24)
        self.vbo2.write(b''.join(struct.pack(
            '15f',
            *car['color'],
            *car['pos'],
            1.0, 0.0, 0.0,
            0.0, 1.0, 0.0,
            0.0, 0.0, 1.0,
        ) for car in cars))
        self.vao.render(instances=len(cars))
        self.vbo2.write(b''.join(struct.pack(
            '15f',
            0.0, 0.0, 0.0,
            *car['pos'],
            1.0, 0.0, 0.0,
            0.0, 1.0, 0.0,
            0.3, 0.6, 0.0,
        ) for car in cars))
        self.vao.render(instances=len(cars))