Пример #1
0
 def processData(data):
     if isinstance(data, Matrix33):
         return data
     elif isinstance(data, list) and len(data) == 3:
         return Matrix33([data[0], data[1], data[2]])
     else:
         return Matrix33()
Пример #2
0
 def test_euler_equivalence(self):
     eulers = euler.create_from_x_rotation(np.pi / 2.)
     m = Matrix33.from_x_rotation(np.pi / 2.)
     q = Quaternion.from_x_rotation(np.pi / 2.)
     qm = Matrix33.from_quaternion(q)
     em = Matrix33.from_eulers(eulers)
     self.assertTrue(np.allclose(qm, m))
     self.assertTrue(np.allclose(qm, em))
     self.assertTrue(np.allclose(m, em))
Пример #3
0
 def test_euler_equivalence(self):
     eulers = euler.create_from_x_rotation(np.pi / 2.)
     m = Matrix33.from_x_rotation(np.pi / 2.)
     q = Quaternion.from_x_rotation(np.pi / 2.)
     qm = Matrix33.from_quaternion(q)
     em = Matrix33.from_eulers(eulers)
     self.assertTrue(np.allclose(qm, m))
     self.assertTrue(np.allclose(qm, em))
     self.assertTrue(np.allclose(m, em))
Пример #4
0
 def __apply_transformation_vec3(self, a_point):
     '''
     Applies the transformation to a given Verctor3.
     :param a_point: Vector3
     '''
     return (Matrix33.from_quaternion(self.__rotation_quaternion).T *
             a_point) + Vector3.from_vector4(self.__translation)[0]
Пример #5
0
 def key_event(self, key, action, modifiers):
     if action == self.wnd.keys.ACTION_RELEASE:
         # perspective
         if key == self.wnd.keys.Y:
             self._perspective_matrix = Matrix33(
                 [[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype="f4"
             )
             self._camera_position = (0, 0, 100)
             self._logger.log("Perspective changed to side view")
         elif key == self.wnd.keys.Z:
             self._perspective_matrix = Matrix33(
                 [[1, 0, 0], [0, 0, 1], [0, 1, 0]], dtype="f4"
             )
             self._camera_position = (0, 0, 100)
             self._logger.log("Perspective changed to top view")
         # zoom reset
         elif key == self.wnd.keys.SPACE:
             self._zoom_level = 1
             self._logger.log("Zoom level reset")
         # checkerboard
         elif key == self.wnd.keys.TAB:
             self._show_checkerboard = not self.show_checkerboard
             self._logger.log(
                 "Checkerboard has been " + "shown"
                 if self.show_checkerboard
                 else "hidden"
             )
         # presets
         elif key == self.wnd.keys.NUMBER_1:
             self.load_preset("preset1.json")
         elif key == self.wnd.keys.NUMBER_2:
             self.load_preset("preset2.json")
         elif key == self.wnd.keys.NUMBER_3:
             self.load_preset("preset3.json")
         elif key == self.wnd.keys.NUMBER_4:
             self.load_preset("preset4.json")
         elif key == self.wnd.keys.NUMBER_5:
             self.load_preset("preset5.json")
         elif key == self.wnd.keys.NUMBER_6:
             self.load_preset("preset6.json")
         elif key == self.wnd.keys.NUMBER_7:
             self.load_preset("preset7.json")
         elif key == self.wnd.keys.NUMBER_8:
             self.load_preset("preset8.json")
         elif key == self.wnd.keys.NUMBER_9:
             self.load_preset("preset9.json")
Пример #6
0
 def render(self, time: float, frametime: float):
     self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
     self.ctx.clear(1.0, 1.0, 0.5, 1.0)
     self.rotation.value = tuple(
         Matrix33.from_eulers((time/2, time/2, time/2)).reshape(9).tolist())
     self.prog['time'].value = time
     self.texture.use(location=0)
     self.cube.render(self.prog)
Пример #7
0
 def setData(self, data):
     if isinstance(data, Matrix33):
         self._data = data
     elif isinstance(data, list) and len(data) == 3:
         self._data = Matrix33([data[0], data[1], data[2]])
     else:
         self._data = self.defaultValue()
     PinWidgetBase.setData(self, self._data)
Пример #8
0
    def test_conversions(self):
        from pyrr import Quaternion, Matrix33, Matrix44, Vector3, Vector4

        v3 = Vector3([1., 0., 0.])
        v4 = Vector4.from_vector3(v3, w=1.0)
        v3, w = Vector3.from_vector4(v4)

        m44 = Matrix44()
        q = Quaternion(m44)
        m33 = Matrix33(q)

        m33 = Matrix44().matrix33
        m44 = Matrix33().matrix44
        q = Matrix44().quaternion
        q = Matrix33().quaternion

        m33 = Quaternion().matrix33
        m44 = Quaternion().matrix44
Пример #9
0
    def render(self, _time, frame_time):
        self.move_camera()

        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST)
        self.mn.write(Matrix33(self.camera.mat_lookat).inverse.transpose().astype('f4').tobytes())
        self.mv.write(self.camera.mat_lookat.astype('f4').tobytes())
        self.mvp.write((self.camera.mat_projection * self.camera.mat_lookat).astype('f4').tobytes())
        self.prog['N'].value = N
        self.prog['timer'].value = time.localtime().tm_sec
        self.vao.render()
Пример #10
0
    def create_normal_matrix(self, modelview):
        """
        Convert to mat3 and return inverse transpose.
        These are normally needed when dealing with normals in shaders.

        :param modelview: The modelview matrix
        :return: Normal matrix
        """
        normal_m = Matrix33.from_matrix44(modelview)
        normal_m = normal_m.inverse
        normal_m = normal_m.transpose()
        return normal_m
Пример #11
0
def parse_input(input_file: TextIO) -> list[Scanner]:
    scanners = []
    for line in input_file:
        line = line.strip()
        if line.startswith("---"):
            res = parse("--- scanner {idx:d} ---", line)
            scanner = Scanner(res.named["idx"], [], Vector3(),
                              Matrix33.identity())
            scanners.append(scanner)
        elif line:
            scanner.beacons.append(
                Vector3([int(p) for p in line.split(",")], dtype=np.int_))
    return scanners
Пример #12
0
    def create_normal_matrix(self, modelview):
        """
        Creates a normal matrix from modelview matrix

        Args:
            modelview: The modelview matrix

        Returns:
            A 3x3 Normal matrix as a :py:class:`numpy.array`
        """
        normal_m = Matrix33.from_matrix44(modelview)
        normal_m = normal_m.inverse
        normal_m = normal_m.transpose()
        return normal_m
Пример #13
0
    def render(self, *, projection_matrix, camera_matrix, model_matrix=None):
        """Render out the voxel to the screen"""

        translate = Matrix44.from_translation(
            (-self._size[0] / 2, -self._size[0] / 2, -self._size[0] * 2),
            dtype='f4',
        )
        mat = camera_matrix * translate
        normal = Matrix33.from_matrix44(mat).inverse.transpose().astype(
            "f4").tobytes()
        self.voxel_light_prog["m_proj"].write(projection_matrix)
        self.voxel_light_prog["m_modelview"].write(mat)
        self.voxel_light_prog["m_normal"].write(normal)
        self.cube.render(self.voxel_light_prog, instances=self._num_instances)
Пример #14
0
    def test_operators(self):
        from pyrr import Quaternion, Matrix44, Matrix33, Vector3, Vector4
        import numpy as np

        # matrix multiplication
        m = Matrix44() * Matrix33()
        m = Matrix44() * Quaternion()
        m = Matrix33() * Quaternion()

        # matrix inverse
        m = ~Matrix44.from_x_rotation(np.pi)

        # quaternion multiplication
        q = Quaternion() * Quaternion()
        q = Quaternion() * Matrix44()
        q = Quaternion() * Matrix33()

        # quaternion inverse (conjugate)
        q = ~Quaternion()

        # quaternion dot product
        d = Quaternion() | Quaternion()

        # vector oprations
        v = Vector3() + Vector3()
        v = Vector4() - Vector4()

        # vector transform
        v = Quaternion() * Vector3()
        v = Matrix44() * Vector3()
        v = Matrix44() * Vector4()
        v = Matrix33() * Vector3()

        # dot and cross products
        dot = Vector3() | Vector3()
        cross = Vector3() ^ Vector3()
Пример #15
0
    def drag_camera(self):
        if not imgui.is_any_item_active():
            mx, my = imgui.get_mouse_drag_delta()
        else:
            mx, my = 0, 0

        # if we just released the mouse, save the new camera position
        if self.camera['mouse_down'] and not self.io.mouse_down[0]:
            self.camera['saved_center'] = self.camera['center']
        self.camera['mouse_down'] = self.io.mouse_down[0]

        # no drag, don't do anything
        if mx == 0 and my == 0:
            return False

        # calculate the camera position according to the current drag
        # this is a rotation relative to the saved position
        self.camera['center'] = Matrix33.from_y_rotation(self.camera['rot_speed'] * mx / self.width) \
            * Matrix33.from_x_rotation(self.camera['rot_speed'] * my / self.height) \
            * self.camera['saved_center']
        self.update_camera()

        # camera has changed
        return True
Пример #16
0
    def render(self, time, frame_time):
        self.ctx.clear()
        self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
        angle = time * 0.2

        lookat = Matrix44.look_at(
            (np.cos(angle), np.sin(angle), 0.4),
            (0.0, 0.0, 0.0),
            (0.0, 0.0, 1.0),
            dtype='f4',
        )
        normal_matrix = Matrix33.from_matrix44(lookat).inverse.transpose()

        self.prog['modelview'].write(lookat)
        self.prog['normal_matrix'].write(normal_matrix.astype('f4').tobytes())
        self.heightmap.use(0)
        self.vao.render(moderngl.POINTS, vertices=(self.dim - 1)**2)
Пример #17
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self._path = os.path.dirname(__file__)

        # logger instance for logging events
        self._logger = Logger(os.path.dirname(self._path), "algol.log")
        self._logger.log("Program started")
        self._active_preset = None
        self.load_preset("preset1.json")

        # used to store texture data when calculating luminance
        self._temp_texture_buffer = np.empty(1280 * 720 * 4, dtype="uint8")
        # used to log data measured
        self._data_file = open("data.csv", "w")

        # shaders preparation
        vertex_source = self.shader_source("vertex.glsl")
        fragment_source = self.shader_source("fragment.glsl")
        self._quad_program = self.ctx.program(
            vertex_shader=vertex_source, fragment_shader=fragment_source
        )
        self._quad_fs = mglw.geometry.quad_fs()
        self._texture = self.ctx.texture((1280, 720), 4)

        compute_source = self.shader_source(
            "compute.glsl", {"NUMBER_OF_OBJECTS": self._world.size}
        )
        self._compute = self.ctx.compute_shader(compute_source)

        # variables remembering some user settings for runtime
        self._perspective_matrix = Matrix33(
            [[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype="f4"
        )
        self._camera_position = (0, 0, 100)
        self._zoom_level = 1
        self._show_checkerboard = False
import sys
import numpy as np
from pyrr import Quaternion, Matrix33, Matrix44, Vector3, Vector4

if True:
    file_name = sys.argv[1]

    data = np.loadtxt(file_name)

    data_size = data.shape[0]
    all_motion = np.zeros((data_size - 1, 7))
    pose_last = Matrix44(np.eye(4))
    pose_last[0:3, 0:3] = Matrix33(data[0, 3:7])
    pose_last[0:3, 3] = data[0, 0:3].T
    for i in range(1, data_size):
        pose_curr = Matrix44(np.eye(4))
        pose_curr[0:3, 0:3] = Matrix33(data[i, 3:7])
        pose_curr[0:3, 3] = data[i, 0:3].T
        print(pose_last)
        motion = ~pose_last * pose_curr
        quaternion = Quaternion(motion[0:3, 0:3])
        trans = motion[0:3, 3].T
        trans_quat = np.zeros(7)
        trans_quat[0:3] = trans
        trans_quat[3:7] = quaternion
        all_motion[i - 1, :] = trans_quat
        pose_last = pose_curr.copy()
        #print pose_line
    np.savetxt(sys.argv[2], all_motion)
    print('done')
Пример #19
0
    def bundle_adjust(self, n):
        i = len(self.mapmem.patch_3d_pts) - n
        count = 0
        cameras = []
        list3d = []
        for feats in range(len(self.mapmem.patch_3d_pts[i])):
            featpt = self.mapmem.patch_3d_pts[i][feats]
            list3d.append([featpt[0], featpt[1], featpt[2]])
        fx = self.camera_matrix[0, 0]
        fy = self.camera_matrix[1, 1]
        cx = self.camera_matrix[0, 2]
        cy = self.camera_matrix[1, 2]
        ar = fy / fx
        s = 0
        ds1 = self.distortion_coeff[0]
        ds2 = self.distortion_coeff[1]
        ds3 = self.distortion_coeff[2]
        ds4 = self.distortion_coeff[3]
        ds5 = self.distortion_coeff[4]
        x = np.zeros((len(list3d), n, 2), dtype=np.double)
        vmask = np.zeros((len(list3d), n), dtype=np.byte)
        for j in range(i, len(self.mapmem.patch_3d_pts)):
            # print 'mat',self.mapmem.rot_mats[j]
            quat = Quaternion(self.mapmem.rot_mats[j])
            # a = Matrix33(quat)
            # print type(a)
            # print a
            # print a[0]
            # print a[2][1]
            # print 'quat',quat
            trans = self.mapmem.trans_mats[j]
            tx = trans[0]
            ty = trans[1]
            tz = trans[2]
            # trans = self.mapmem.cam_poses[j]
            # tx = trans[0]
            # ty = trans[1]
            # tz = trans[2]
            q1 = quat[0]
            q2 = quat[1]
            q3 = quat[2]
            # fx cx cy AR s r2 r4 t1 t2 r6 qi qj qk tx ty tz
            cameras.append((fx, cx, cy, ar, s, ds1, ds2, ds3, ds4, ds5, q1, q2,
                            q3, tx, ty, tz))
            for val in range(len(self.mapmem.patch_3d_pts[j])):
                obj = self.mapmem.patch_3d_pts[j][val]
                imgpt = self.mapmem.patch_2d_pts[j][val]
                # ind = np.where(np.all(vals==list3d,axis=1))[0][0]
                ind = list3d.index([obj[0], obj[1], obj[2]])
                x[ind][count][0] = imgpt[0]
                x[ind][count][1] = imgpt[1]
                vmask[ind][count] = 1
            count += 1
        # print sba.Cameras(cameras)
        # print len(list3d)
        # print x
        # print cameras
        if count != n:
            print 'count error in bundle adjustment!!'
        # print vmask.shape
        sba_points = sba.Points(list3d, x, vmask)
        sba_cameras = sba.Cameras(cameras)
        # print sba_cameras.camarray
        # print 'pts',sba_points.X
        # print 'cams',sba_cameras
        # print sba.Options.optsToC
        # options = sba.Options
        # print options.optsToC

        newcams, newpts, info = sba.SparseBundleAdjust(sba_cameras, sba_points)
        for count, real_idx in enumerate(
                range(i, len(self.mapmem.patch_3d_pts))):
            new_cam_tr = np.array([[newcams.camarray[count, 13]],
                                   [newcams.camarray[count, 14]],
                                   [newcams.camarray[count, 15]]])
            quatr = Quaternion()
            # print 'newcam_',new_cam_tr
            quatr.x = newcams.camarray[count, 10]
            quatr.y = newcams.camarray[count, 11]
            quatr.z = newcams.camarray[count, 12]
            quatr.w = math.sqrt(1 - float(quatr.x)**2 - float(quatr.y)**2 -
                                float(quatr.z)**2)
            rot = Matrix33(quatr)
            rot_mat = np.array([[rot[0][0], rot[0][1], rot[0][2]],
                                [rot[1][0], rot[1][1], rot[1][2]],
                                [rot[2][0], rot[2][1], rot[2][2]]])
            pose = np.dot(-(self.mapmem.rot_mats[real_idx].T), new_cam_tr)
            self.mapmem.replace_cam_poses_sba(pose[:, 0], real_idx)
            print pose
            # print 'qss',quatr
            # print newcams.camarray[count]

            # print math.sqrt(1-0^2-0^2)
            # new_cam_quat =
            # print quat.normalised
            # new_cam_rot = Matrix33(Quaternion())
            # print newcams.camarray[count]
            # print Matrix33(quat)
            # print new_cam_tr
        # print newcams.camarray
        # print sba.Options.optsToC
        # for camera_array,new_pts in zip(newcams.camarray,newpts.X:
        # for a in range(n):
        #     new2dpts = newpts.X[:,a,:]

        # print newpts.X
        # print info
        print 'done'
Пример #20
0
 def __init__(self, name, parent, dataType, direction, **kwargs):
     super(Matrix33Pin, self).__init__(name, parent, dataType, direction,
                                       **kwargs)
     self.setDefaultValue(Matrix33())
def calculateSegment(p0, p1):

    new_points = []

    v0 = Vector3(p0)
    v1 = Vector3(p1)
    v_smer = v1 - v0
    v_smer_n = Vector3(pyrr.vector3.normalize(v_smer))

    distance_of_bridge_segment = distanceBetwenTwoPoints(np.array(p0), np.array(p1))

    current_point_on_path = v0
    next_point_on_path = v0 + (.25 / D * v_smer_n)  # gostota točk vzdolž mostu

    while (distance_of_bridge_segment + 1.75 >= distanceBetwenTwoPoints(
            np.array((next_point_on_path.x, next_point_on_path.y, next_point_on_path.z)),
            p0)):

        rotation_matrix_90_counterclockwise = Matrix33.from_z_rotation(np.pi / 2)
        v_smer_n_90_counterclockwise = rotation_matrix_90_counterclockwise * v_smer_n
        new_point_on_left_edge = current_point_on_path + (
                    v_smer_n_90_counterclockwise * (sirces / 1.5))  # polovica širine mostu
        new_point_on_left_edge[2] -= sirces / 11  # debelina mostu

        z = new_point_on_left_edge[2] - (0.2 / D)
        while (z <= current_point_on_path.z):
            new_point = Vector3(new_point_on_left_edge).copy()
            new_point[2] = z + (0.2 / D)  # gostota točk v višino mostu
            new_points.append(new_point)
            z = new_point[2]

        rotation_matrix_90_clockwise = Matrix33.from_z_rotation(-(np.pi / 2))
        v_smer_n_90_clockwise = rotation_matrix_90_clockwise * v_smer_n
        new_point_on_right_edge = current_point_on_path + (
                    v_smer_n_90_clockwise * (sirces / 1.5))  # polovica širine mostu
        new_point_on_right_edge[2] -= sirces / 11  # debelina mostu

        z = new_point_on_right_edge[2] - (0.2 / D)
        while (z <= current_point_on_path.z):
            new_point = Vector3(new_point_on_right_edge).copy()
            new_point[2] = z + (0.2 / D)  # gostota točk v višino mostu
            new_points.append(new_point)
            z = new_point[2]

        for point_i in np.arange(0.0, 1.0, 0.02 / D):  # gostota točk v širino mostu
            new_points.append(
                pyrr.vector3.interpolate(new_point_on_left_edge, new_point_on_right_edge, point_i))

        terrain_point_left = new_point_on_left_edge + (v_smer_n_90_counterclockwise * (1.3))
        terrain_point_right = new_point_on_right_edge + (v_smer_n_90_clockwise * (1.3))
        terrain_point_left_z = getLocalMinZ(points_in_bbox, terrain_point_left)
        terrain_point_right_z = getLocalMinZ(points_in_bbox, terrain_point_right)

        if (abs(new_point_on_left_edge.z - terrain_point_left_z) <= 1.25 or abs(
                new_point_on_right_edge.z - terrain_point_right_z) <= 1.25):
            new_z = min(terrain_point_left_z, terrain_point_right_z)
            terrain_point_left[2] = new_z
            terrain_point_right[2] = new_z
        else:
            terrain_point_left[2] = terrain_point_left_z
            terrain_point_right[2] = terrain_point_right_z

        for point_i in np.arange(0.0, 1.0, 0.02 / D):
            new_points.append(
                pyrr.vector3.interpolate(terrain_point_left, terrain_point_right, point_i))

        current_point_on_path = next_point_on_path
        next_point_on_path = next_point_on_path + ((.25 / D) * v_smer_n)

    return new_points
Пример #22
0
 def pinDataTypeHint():
     return DataTypes.Matrix33, Matrix33()
Пример #23
0
 def object_hook(self, m33Dict):
     return Matrix33(m33Dict[Matrix33.__name__])
Пример #24
0
def main():

    skybox_vertices = [
        -1.0, 1.0, -1.0,
        -1.0, -1.0, -1.0,
        1.0, -1.0, -1.0,
        1.0, -1.0, -1.0,
        1.0, 1.0, -1.0,
        -1.0, 1.0, -1.0,

        -1.0, -1.0, 1.0,
        -1.0, -1.0, -1.0,
        -1.0, 1.0, -1.0,
        -1.0, 1.0, -1.0,
        -1.0, 1.0, 1.0,
        -1.0, -1.0, 1.0,

        1.0, -1.0, -1.0,
        1.0, -1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, -1.0,
        1.0, -1.0, -1.0,

        -1.0, -1.0, 1.0,
        -1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, -1.0, 1.0,
        -1.0, -1.0, 1.0,

        -1.0, 1.0, -1.0,
        1.0, 1.0, -1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,
        -1.0, 1.0, -1.0,

        -1.0, -1.0, -1.0,
        -1.0, -1.0, 1.0,
        1.0, -1.0, -1.0,
        1.0, -1.0, -1.0,
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0
    ]

    skybox_vertices = np.array(skybox_vertices, dtype=np.float32)

    framebuffer_vertices = [
        -1.0,  1.0, 0.0, 1.0,
        -1.0, -1.0, 0.0, 0.0,
         1.0, -1.0, 1.0, 0.0,
        -1.0,  1.0, 0.0, 1.0,
         1.0, -1.0, 1.0, 0.0,
         1.0,  1.0, 1.0, 1.0
    ]

    framebuffer_vertices = np.array(framebuffer_vertices, dtype=np.float32)

    offset = 2
    block_positions = []
    for y in range(-10, 10, 2):
        for x in range(-10, 10, 2):
            translation = Vector3([x + offset, y + offset, 0], dtype=np.float32)
            block_positions.append(translation)

    glfw.init()

    window_width = 1920
    window_height = 1080
    aspect_ratio = window_width / window_height
    glfw.window_hint(glfw.SAMPLES, 4)
    window = glfw.create_window(window_width, window_height, "Learning", glfw.get_primary_monitor(), None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    glViewport(0, 0, window_width, window_height)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)
    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, mouse_callback)

    glEnable(GL_STENCIL_TEST)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_MULTISAMPLE)
    glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
    glEnable(GL_CULL_FACE)
    glCullFace(GL_FRONT)
    glFrontFace(GL_CW)

    shader = Shader("shaders\\vertex.vs", "shaders\\fragment.fs")
    lighting_shader = Shader("shaders\\lighting_vertex.vs", "shaders\\lighting_fragment.fs")
    outline_shader = Shader("shaders\\outline_vertex.vs", "shaders\\outline_fragment.fs")
    skybox_shader = Shader("shaders\\skybox_vertex.vs", "shaders\\skybox_fragment.fs")
    screen_shader = Shader("shaders\\framebuffer_vertex.vs", "shaders\\framebuffer_fragment.fs")

    block = ObjLoader("models\\block.obj", "block")
    block.load_mesh()
    plane = ObjLoader("models\\grass.obj", "plane")
    plane.load_mesh()

    # Skybox buffers
    skybox_vao = glGenVertexArrays(1)
    skybox_vbo = glGenBuffers(1)
    glBindVertexArray(skybox_vao)
    glBindBuffer(GL_ARRAY_BUFFER, skybox_vbo)
    glBufferData(GL_ARRAY_BUFFER, skybox_vertices.nbytes, skybox_vertices, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * skybox_vertices.itemsize, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    # Framebuffer buffers
    framebuffer_vao = glGenVertexArrays(1)
    framebuffer_vbo = glGenBuffers(1)
    glBindVertexArray(framebuffer_vao)
    glBindBuffer(GL_ARRAY_BUFFER, framebuffer_vbo)
    glBufferData(GL_ARRAY_BUFFER, framebuffer_vertices.nbytes, framebuffer_vertices, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * framebuffer_vertices.itemsize, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * framebuffer_vertices.itemsize, ctypes.c_void_p(2 * framebuffer_vertices.itemsize))
    glEnableVertexAttribArray(1)

    glUseProgram(screen_shader.shader_program)
    screen_shader.set_int("screenTexture", 0)

    # Generating texture
    container = Texture("resources\\cobblestone_texture.png", True).tex_ID

    # Framebuffer
    fbo = glGenFramebuffers(1)
    glBindFramebuffer(GL_FRAMEBUFFER, fbo)

    tex_color_buffer = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, tex_color_buffer)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, window_width, window_height, 0, GL_RGB, GL_UNSIGNED_BYTE, None)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glBindTexture(GL_TEXTURE_2D, 0)

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_color_buffer, 0)

    # Renderbuffer
    rbo = glGenRenderbuffers(1)
    glBindRenderbuffer(GL_RENDERBUFFER, rbo)
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, window_width, window_height)
    glBindRenderbuffer(GL_RENDERBUFFER, 0)

    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo)

    if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE:
        print("ERROR: FRAMEBUFFER: Framebuffer is not complete!")

    glBindFramebuffer(GL_FRAMEBUFFER, 0)

    # Cubemap
    skybox = [
        "resources\\right.jpg",
        "resources\\left.jpg",
        "resources\\top.jpg",
        "resources\\bottom.jpg",
        "resources\\back.jpg",
        "resources\\front.jpg"
    ]
    cubemap = load_cubemap(skybox)

    last_frame = 0.0

    while not glfw.window_should_close(window):
        global delta_time
        glfw.poll_events()
        move()

        glBindFramebuffer(GL_FRAMEBUFFER, fbo)

        glClearColor(.1, .1, .1, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glEnable(GL_DEPTH_TEST)

        time = glfw.get_time()
        delta_time = (time - last_frame) * 200
        last_frame = time

        # Set view/projection matrices
        view_matrix = cam.get_view_matrix()
        view_matrix = np.array(view_matrix, dtype=np.float32)
        projection_matrix = Matrix44.perspective_projection(45.0, aspect_ratio, 0.1, 500.0)
        projection_matrix = np.array(projection_matrix, dtype=np.float32)

        glUseProgram(shader.shader_program)

        # Send view pos
        shader.set_vec3("viewPos", cam.camera_pos)

        # Send light to shader
        shader.set_vec3("dirLight.direction", Vector3([-.2, -1.0, -.3]))
        shader.set_vec3("dirLight.ambient", Vector3([.05, .05, .05]))
        shader.set_vec3("dirLight.diffuse", Vector3([.4, .4, .4]))
        shader.set_vec3("dirLight.specular", Vector3([.5, .5, .5]))

        shader.set_vec3("pointLights[0].position", point_light_positions[0])
        shader.set_vec3("pointLights[0].ambient", Vector3([.05, .05, .05]))
        shader.set_vec3("pointLights[0].diffuse", Vector3([.8, .8, .8]))
        shader.set_vec3("pointLights[0].specular", Vector3([1.0, 1.0, 1.0]))
        shader.set_float("pointLights[0].constant", 1.0)
        shader.set_float("pointLights[0].linear", .09)
        shader.set_float("pointLights[0].quadratic", .032)

        shader.set_vec3("pointLights[1].position", point_light_positions[1])
        shader.set_vec3("pointLights[1].ambient", Vector3([.05, .05, .05]))
        shader.set_vec3("pointLights[1].diffuse", Vector3([.8, .8, .8]))
        shader.set_vec3("pointLights[1].specular", Vector3([1.0, 1.0, 1.0]))
        shader.set_float("pointLights[1].constant", 1.0)
        shader.set_float("pointLights[1].linear", .09)
        shader.set_float("pointLights[1].quadratic", .032)

        shader.set_vec3("pointLights[2].position", point_light_positions[2])
        shader.set_vec3("pointLights[2].ambient", Vector3([.05, .05, .05]))
        shader.set_vec3("pointLights[2].diffuse", Vector3([.8, .8, .8]))
        shader.set_vec3("pointLights[2].specular", Vector3([1.0, 1.0, 1.0]))
        shader.set_float("pointLights[2].constant", 1.0)
        shader.set_float("pointLights[2].linear", .09)
        shader.set_float("pointLights[2].quadratic", .032)

        shader.set_vec3("pointLights[3].position", point_light_positions[3])
        shader.set_vec3("pointLights[3].ambient", Vector3([.05, .05, .05]))
        shader.set_vec3("pointLights[3].diffuse", Vector3([.8, .8, .8]))
        shader.set_vec3("pointLights[3].specular", Vector3([1.0, 1.0, 1.0]))
        shader.set_float("pointLights[3].constant", 1.0)
        shader.set_float("pointLights[3].linear", .09)
        shader.set_float("pointLights[3].quadratic", .032)

        # Send material to shader
        shader.set_float("material.shininess", 32.0)

        # Send maps to shader
        shader.set_int("diffuse", 0)

        # Send view, projection transformations to shader
        shader.set_Matrix44f("view", view_matrix)
        shader.set_Matrix44f("projection", projection_matrix)

        # Texture
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, container)

        # Draw block
        block.draw_mesh()

        # Draw grass
        # glActiveTexture(GL_TEXTURE0)
        # glBindTexture(GL_TEXTURE_2D, grass_texture)
        # model_matrix = Matrix44.from_scale(Vector3([1., 1., 1.]))
        # model_translation = Matrix44.from_translation(Vector3([0., -2., 0.]))
        # model_rotation_x = Quaternion.from_x_rotation(radians(-90))
        # model_orientation_x = model_rotation_x * Quaternion()
        # model_matrix = model_matrix * model_orientation_x
        # model_matrix = model_matrix * model_translation
        # model_matrix = np.array(model_matrix, dtype=np.float32)
        # shader.set_Matrix44f("model", model_matrix)
        # plane.draw_mesh()

        # Draw outline
        # glUseProgram(outline_shader.shader_program)
        # glStencilFunc(GL_NOTEQUAL, 1, 0xFF)
        # glStencilMask(0x00)
        # glDisable(GL_DEPTH_TEST)
        #
        # # Send view projection transformations to shader
        # outline_shader.set_Matrix44f("view", view_matrix)
        # outline_shader.set_Matrix44f("projection", projection_matrix)
        # for each_block in range(len(block_positions) - 2, len(block_positions)):
        #     # Create model matrix
        #     model_matrix = Matrix44.from_scale(Vector3([1.05, 1.05, 1.05]))  # Scale model by 1
        #
        #     model_rotation_x = Quaternion.from_x_rotation(0 * each_block)  # Rotate about x
        #     model_orientation_x = model_rotation_x * Quaternion()  # Create orientation matrix x
        #     model_rotation_y = Quaternion.from_y_rotation(0 * each_block)  # Rotate about y
        #     model_orientation_y = model_rotation_y * Quaternion()  # Create orientation matrix y
        #     model_rotation_z = Quaternion.from_z_rotation(0 * each_block)  # Rotate about z
        #     model_orientation_z = model_rotation_z * Quaternion()  # Create orientation matrix z
        #
        #     model_translation = block_positions[each_block]
        #     model_translation = Matrix44.from_translation(2 * model_translation)
        #
        #     model_matrix = model_matrix * model_orientation_x  # Apply orientation x
        #     model_matrix = model_matrix * model_orientation_y  # Apply orientation y
        #     model_matrix = model_matrix * model_orientation_z  # Apply orientation z
        #     model_matrix = model_matrix * model_translation  # Apply translation
        #     model_matrix = np.array(model_matrix, dtype=np.float32)  # Convert to opengl data type
        #
        #     # Send model transform to shader
        #     outline_shader.set_Matrix44f("model", model_matrix)
        #     block.draw_mesh()
        #
        # glStencilMask(0xFF)
        # glEnable(GL_DEPTH_TEST)

        # Draw skybox
        glDepthFunc(GL_LEQUAL)
        glUseProgram(skybox_shader.shader_program)
        view_matrix = Matrix44(Matrix33.from_matrix44(view_matrix))
        view_matrix = np.array(view_matrix, dtype=np.float32)
        skybox_shader.set_int("skybox", 0)
        skybox_shader.set_Matrix44f("view", view_matrix)
        skybox_shader.set_Matrix44f("projection", projection_matrix)
        glBindVertexArray(skybox_vao)
        glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap)
        glDrawArrays(GL_TRIANGLES, 0, 36)
        glBindVertexArray(0)
        glDepthFunc(GL_LESS)

        glBindFramebuffer(GL_FRAMEBUFFER, 0)
        glDisable(GL_DEPTH_TEST)
        glClearColor(1.0, 1.0, 1.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        glUseProgram(screen_shader.shader_program)
        glBindVertexArray(framebuffer_vao)
        glBindTexture(GL_TEXTURE_2D, tex_color_buffer)
        glDrawArrays(GL_TRIANGLES, 0, 6)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Пример #25
0
 def pinDataTypeHint():
     return 'Matrix33Pin', Matrix33()
Пример #26
0
    def render_gate(self, view, min_dist):
        '''
            Randomly move the gate around, while keeping it inside the
            boundaries
        '''
        gate_translation = None
        too_close = True
        # Prevent gates from spawning too close to each other
        while too_close:
            too_close = False
            gate_translation = Vector3([
                random.uniform(-self.boundaries['x'], self.boundaries['x']),
                random.uniform(-self.boundaries['y'], self.boundaries['y']),
                0
            ])
            for gate_pose in self.gate_poses:
                if (np.linalg.norm(gate_pose - gate_translation)
                        <= float(min_dist)):
                    too_close = True
                    break

        self.gate_poses.append(gate_translation)

        ''' Randomly rotate the gate horizontally, around the Z-axis '''
        gate_rotation = Quaternion.from_z_rotation(random.random() * np.pi)

        model = Matrix44.from_translation(gate_translation) * gate_rotation
        # With respect to the camera, for the annotation
        gate_orientation = Matrix33(
            self.drone_pose.orientation) * Matrix33(gate_rotation)
        gate_orientation = Quaternion.from_matrix(gate_orientation)
        # Model View Projection matrix
        mvp = self.projection * view * model

        # Shader program
        vertex_shader_source = open('data/shader.vert').read()
        fragment_shader_source = open('data/shader.frag').read()
        prog = self.context.program(vertex_shader=vertex_shader_source,
                                    fragment_shader=fragment_shader_source)

        prog['Light1'].value = (
            random.uniform(-self.boundaries['x'], self.boundaries['x']),
            random.uniform(-self.boundaries['y'], self.boundaries['y']),
            random.uniform(5, 7))
        # prog['Light2'].value = (
            # random.uniform(-self.boundaries['x'], self.boundaries['x']),
            # random.uniform(-self.boundaries['y'], self.boundaries['y']),
            # random.uniform(4, 7))
        # prog['Light3'].value = (
            # random.uniform(-self.boundaries['x'], self.boundaries['x']),
            # random.uniform(-self.boundaries['y'], self.boundaries['y']),
                # random.uniform(4, 7))
            # prog['Light4'].value = (
            # random.uniform(-self.boundaries['x'], self.boundaries['x']),
            # random.uniform(-self.boundaries['y'], self.boundaries['y']),
            # random.uniform(4, 7))
        prog['MVP'].write(mvp.astype('f4').tobytes())

        mesh = self.meshes[random.choice(list(self.meshes.keys()))]
        frame_vbo = self.context.buffer(
            mesh['obj'].pack('vx vy vz nx ny nz tx ty'))
        frame_vao = self.context.simple_vertex_array(
            prog, frame_vbo, 'in_vert', 'in_norm', 'in_text')
        contour_front_vbo = self.context.buffer(
            mesh['contour_obj_front'].pack('vx vy vz nx ny nz tx ty'))
        contour_front_vao = self.context.simple_vertex_array(
            prog, contour_front_vbo, 'in_vert', 'in_norm', 'in_text')
        contour_back_vbo = self.context.buffer(
            mesh['contour_obj_back'].pack('vx vy vz nx ny nz tx ty'))
        contour_back_vao = self.context.simple_vertex_array(
            prog, contour_back_vbo, 'in_vert', 'in_norm', 'in_text')

        prog['viewPos'].value = (
            self.drone_pose.translation.x,
            self.drone_pose.translation.y,
            self.drone_pose.translation.z
        )
        prog['Color'].value = (random.uniform(0, 0.7),
                               random.uniform(0, 0.7),
                               random.uniform(0, 0.7))
        prog['UseTexture'].value = False
        frame_vao.render()
        prog['Color'].value = (0.8, 0.8, 0.8)
        contour_back_vao.render()
        mesh['contour_texture'].use()
        prog['UseTexture'].value = True
        contour_front_vao.render()

        return mesh, model, gate_translation, gate_orientation
Пример #27
0
import os
from dataclasses import dataclass, field
from itertools import combinations
from typing import Any, TextIO

import numpy as np
from parse import parse
from pyrr import Matrix33, Vector3


class ScannerMatched(Exception):
    pass


ROTATIONS = [
    Matrix33.from_eulers((0, 0, 0), dtype=np.int_),
    Matrix33.from_eulers((np.pi / 2, 0, 0), dtype=np.int_),
    Matrix33.from_eulers((np.pi, 0, 0), dtype=np.int_),
    Matrix33.from_eulers((3 * np.pi / 2, 0, 0), dtype=np.int_),
    Matrix33.from_eulers((0, 0, np.pi / 2), dtype=np.int_),
    Matrix33.from_eulers((np.pi / 2, 0, np.pi / 2), dtype=np.int_),
    Matrix33.from_eulers((np.pi, 0, np.pi / 2), dtype=np.int_),
    Matrix33.from_eulers((3 * np.pi / 2, 0, np.pi / 2), dtype=np.int_),
    Matrix33.from_eulers((0, 0, np.pi), dtype=np.int_),
    Matrix33.from_eulers((np.pi / 2, 0, np.pi), dtype=np.int_),
    Matrix33.from_eulers((np.pi, 0, np.pi), dtype=np.int_),
    Matrix33.from_eulers((3 * np.pi / 2, 0, np.pi), dtype=np.int_),
    Matrix33.from_eulers((0, 0, 3 * np.pi / 2), dtype=np.int_),
    Matrix33.from_eulers((np.pi / 2, 0, 3 * np.pi / 2), dtype=np.int_),
    Matrix33.from_eulers((np.pi, 0, 3 * np.pi / 2), dtype=np.int_),
    Matrix33.from_eulers((3 * np.pi / 2, 0, 3 * np.pi / 2), dtype=np.int_),