示例#1
0
    def test_procedural_examples(self):
        from pyrr import quaternion, matrix44, vector3
        import numpy as np

        point = vector3.create(1.,2.,3.)
        orientation = quaternion.create()
        translation = vector3.create()
        scale = vector3.create(1,1,1)

        # translate along X by 1
        translation += [1.0, 0.0, 0.0]

        # rotate about Y by pi/2
        rotation = quaternion.create_from_y_rotation(np.pi / 2.0)
        orientation = quaternion.cross(rotation, orientation)

        # create a matrix
        # start our matrix off using the scale
        matrix = matrix44.create_from_scale(scale)

        # apply our orientation
        orientation = matrix44.create_from_quaternion(orientation)
        matrix = matrix44.multiply(matrix, orientation)

        # apply our translation
        translation_matrix = matrix44.create_from_translation(translation)
        matrix = matrix44.multiply(matrix, translation_matrix)

        # transform our point by the matrix
        point = matrix44.apply_to_vector(matrix, point)
示例#2
0
    def matrix(self):
        """A matrix representing the transform's translation,
        orientation and scale.

        The is an @property decorated method which allows
        retrieval and assignment of the scale value.
        """
        if self._matrix == None:
            # matrix transformations must be done in order
            # scaling
            # rotation
            # translation

            # apply our scale
            self._matrix = matrix44.create_from_scale(self.scale)

            # apply our quaternion
            self._matrix = matrix44.multiply(
                self._matrix,
                matrix44.create_from_quaternion(self.orientation))

            # apply our translation
            # we MUST do this after the orientation
            self._matrix = matrix44.multiply(
                self._matrix,
                matrix44.create_from_translation(self.translation))

        return self._matrix
示例#3
0
    def matrix( self ):
        """A matrix representing the transform's translation,
        orientation and scale.

        The is an @property decorated method which allows
        retrieval and assignment of the scale value.
        """
        if self._matrix == None:
            # matrix transformations must be done in order
            # scaling
            # rotation
            # translation

            # apply our scale
            self._matrix = matrix44.create_from_scale( self.scale )

            # apply our quaternion
            self._matrix = matrix44.multiply(
                self._matrix,
                matrix44.create_from_quaternion( self.orientation )
                )

            # apply our translation
            # we MUST do this after the orientation
            self._matrix = matrix44.multiply(
                self._matrix,
                matrix44.create_from_translation( self.translation )
                )

        return self._matrix
示例#4
0
    def __init__(self, data):
        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 is None:
            self.matrix = matrix44.create_identity()

        if self.translation is not None:
            self.matrix = matrix44.create_from_translation(self.translation)

        if self.rotation is not None:
            quat = quaternion.create(self.rotation[0], self.rotation[1],
                                     self.rotation[2], self.rotation[3])
            mat = matrix44.create_from_quaternion(quat)
            self.matrix = matrix44.multiply(mat, self.matrix)

        if self.scale is not None:
            self.matrix = matrix44.multiply(
                matrix44.create_from_scale(self.scale), self.matrix)
示例#5
0
    def test_procedural_examples(self):
        from pyrr import quaternion, matrix44, vector3
        import numpy as np

        point = vector3.create(1.,2.,3.)
        orientation = quaternion.create()
        translation = vector3.create()
        scale = vector3.create(1,1,1)

        # translate along X by 1
        translation += [1.0, 0.0, 0.0]

        # rotate about Y by pi/2
        rotation = quaternion.create_from_y_rotation(np.pi / 2.0)
        orientation = quaternion.cross(rotation, orientation)

        # create a matrix
        # start our matrix off using the scale
        matrix = matrix44.create_from_scale(scale)

        # apply our orientation
        orientation = matrix44.create_from_quaternion(orientation)
        matrix = matrix44.multiply(matrix, orientation)

        # apply our translation
        translation_matrix = matrix44.create_from_translation(translation)
        matrix = matrix44.multiply(matrix, translation_matrix)

        # transform our point by the matrix
        point = matrix44.apply_to_vector(matrix, point)
示例#6
0
文件: main.py 项目: einarf/pydis50000
    def render(self, time, frame_time):
        pyglet.clock.tick()
        time = self.timer.get_time()

        # Prepare camera matrix
        translation = matrix44.create_from_translation((
            self.track_cam_x.time_value(time),
            self.track_cam_y.time_value(time),
            self.track_cam_z.time_value(time),
        ),
                                                       dtype='f4')
        rotation = matrix44.create_from_eulers((
            math.radians(self.track_cam_rot_x.time_value(time)),
            math.radians(self.track_cam_rot_tilt.time_value(time)),
            math.radians(self.track_cam_rot_z.time_value(time)),
        ),
                                               dtype='f4')

        projection = self.camera.projection.matrix
        modelview = matrix44.multiply(matrix44.multiply(translation, rotation),
                                      self.camera.matrix)

        # Render active effects
        self.offscreen.use()
        self.offscreen.clear()
        for effect in self.router.gen_active_effects(time):
            effect.render(time=time,
                          projection=projection,
                          modelview=modelview)

        # # Postprocessing
        self.wnd.use()
        self.offscreen.color_attachments[0].use()
        self.screen_quad_prog['fade'].value = self.track_fade.time_value(time)
        self.screen_quad.render(self.screen_quad_prog)
示例#7
0
 def update_view_matrix(self):
     self.viewMatrix = matrix44.multiply(
         matrix44.create_from_x_rotation(math.radians(self.pitch)),
         matrix44.create_from_y_rotation(math.radians(self.yaw)))
     self.viewMatrix = matrix44.multiply(
         self.viewMatrix,
         matrix44.create_from_translation(
             Vector3([0, 0, -self.distanceFromPlayer.actual])))
示例#8
0
 def gen_uniforms(self, M):
     """Generate standard camera uniforms."""
     if self.regen_prespective:
         self._regen_prespective()
     if self.regen_view:
         self._regen_view()
     MV = matrix44.multiply(M, self.V)
     MVP = matrix44.multiply(MV, self.P)
     return {"M": M, "V": self.V, "MV": MV, "MVP": MVP}
示例#9
0
    def test_multiply(self):
        m1 = Matrix44(np.arange(self._size))
        m2 = Matrix44(np.arange(self._size)[::-1])
        m = m1 * m2
        self.assertTrue(np.array_equal(m, matrix44.multiply(m2, m1)))

        m1 = Matrix44(np.arange(self._size))
        m2 = Matrix33(np.arange(9))
        m = m1 * m2
        self.assertTrue(np.array_equal(m, matrix44.multiply(matrix44.create_from_matrix33(m2), m1)))
示例#10
0
    def test_multiply(self):
        m1 = Matrix44(np.arange(self._size))
        m2 = Matrix44(np.arange(self._size)[::-1])
        m = m1 * m2
        self.assertTrue(np.array_equal(m, matrix44.multiply(m1, m2)))

        m1 = Matrix44(np.arange(self._size))
        m2 = Matrix33(np.arange(9))
        m = m1 * m2
        self.assertTrue(np.array_equal(m, matrix44.multiply(m1, matrix44.create_from_matrix33(m2))))
示例#11
0
    def model_matrix(terrain):
        translation_matrix = np.matrix([[1, 0, 0, terrain.x], [0, 1, 0, 0],
                                        [0, 0, 1, terrain.z], [0, 0, 0, 1]])
        rotation_matrix_x = matrix44.create_from_x_rotation(np.radians(0))
        rotation_matrix_y = matrix44.create_from_y_rotation(np.radians(0))
        rotation_matrix_z = matrix44.create_from_z_rotation(np.radians(0))
        scale_matrix = matrix44.create_from_scale([1, 1, 1])

        tx = matrix44.multiply(translation_matrix, rotation_matrix_x)
        txy = matrix44.multiply(tx, rotation_matrix_y)
        tr = matrix44.multiply(txy, rotation_matrix_z)
        model_matrix = matrix44.multiply(tr, scale_matrix)

        return model_matrix
示例#12
0
    def render_scene(self, camera):
        """Renders each renderable in the scene
        using the current projection and model
        view matrix.
        The original GL state will be restored
        upon leaving this function.
        """
        projection = camera.view_matrix.matrix
        model_view = camera.model_view

        # bind our diffuse texture
        glActiveTexture(GL_TEXTURE0)
        self.texture.bind()

        # iterate through our renderables
        for node, frame in zip(self.renderables, self.frames):
            # update the model view
            world_matrix = node.world_transform.matrix
            current_mv = matrix44.multiply(world_matrix, model_view)

            fraction, frame1 = math.modf(frame)
            frame2 = (frame1 + 1.0) % node.mesh.num_frames

            # update the frame
            node.mesh.frame_1 = int(frame1)
            node.mesh.frame_2 = int(frame2)
            node.mesh.interpolation = fraction

            # render a cube
            node.render(projection=projection, model_view=current_mv)

        glActiveTexture(GL_TEXTURE0)
        self.texture.unbind()
示例#13
0
    def test_operators_matrix44(self):
        m1 = Matrix44.identity()
        m2 = Matrix44.from_x_rotation(0.5)

        # add
        self.assertTrue(np.array_equal(m1 + m2, matrix44.create_identity() + matrix44.create_from_x_rotation(0.5)))

        # subtract
        self.assertTrue(np.array_equal(m1 - m2, matrix44.create_identity() - matrix44.create_from_x_rotation(0.5)))

        # multiply
        self.assertTrue(np.array_equal(m1 * m2, matrix44.multiply(matrix44.create_from_x_rotation(0.5), matrix44.create_identity())))

        # divide
        self.assertRaises(ValueError, lambda: m1 / m2)

        # inverse
        self.assertTrue(np.array_equal(~m2, matrix44.inverse(matrix44.create_from_x_rotation(0.5))))

        # ==
        self.assertTrue(Matrix44() == Matrix44())
        self.assertFalse(Matrix44() == Matrix44([1. for n in range(16)]))

        # !=
        self.assertTrue(Matrix44() != Matrix44([1. for n in range(16)]))
        self.assertFalse(Matrix44() != Matrix44())
示例#14
0
    def InitGL(self):
        # triangle = np.array([-0.5, -0.5, 0.0, 1.0, 0.0, 0.0,
        #                       0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
        #                       0.0, 0.5, 0.0, 0.0, 0.0, 1.0], dtype=np.float32)

        self.mesh = Cube()

        shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(self.vertex_shader, GL_VERTEX_SHADER), 
                                                  OpenGL.GL.shaders.compileShader(self.fragment_shader, GL_FRAGMENT_SHADER))

        glClearColor(0.0, 0.0, 0.0, 0.0)

        view = matrix44.create_from_translation(Vector3([0.0, 0.0, -2.0]))
        projection = matrix44.create_perspective_projection_matrix(45.0, self.aspect_ratio, 0.1, 100.0)

        vp = matrix44.multiply(view, projection)

        glUseProgram(shader)
        glEnable(GL_DEPTH_TEST)

        vp_loc = glGetUniformLocation(shader, "vp")
        glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp)

        self.model_location = glGetUniformLocation(shader, "model")
        self.Refresh()
示例#15
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.create_identity()
        translate[3][0] = -pos.x
        translate[3][1] = -pos.y
        translate[3][2] = -pos.z

        rotate = matrix44.create_identity()
        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 matrix44.multiply(translate, rotate)
示例#16
0
    def test_operators_matrix44(self):
        m1 = Matrix44.identity()
        m2 = Matrix44.from_x_rotation(0.5)

        # add
        self.assertTrue(
            np.array_equal(
                m1 + m2,
                matrix44.create_identity() +
                matrix44.create_from_x_rotation(0.5)))

        # subtract
        self.assertTrue(
            np.array_equal(
                m1 - m2,
                matrix44.create_identity() -
                matrix44.create_from_x_rotation(0.5)))

        # multiply
        self.assertTrue(
            np.array_equal(
                m1 * m2,
                matrix44.multiply(matrix44.create_identity(),
                                  matrix44.create_from_x_rotation(0.5))))

        # divide
        self.assertRaises(ValueError, lambda: m1 / m2)

        # inverse
        self.assertTrue(
            np.array_equal(
                ~m2, matrix44.inverse(matrix44.create_from_x_rotation(0.5))))
示例#17
0
    def render_lights(self, camera_matrix, projection):
        """Render light volumes"""
        # Disable culling so lights can be rendered when inside volumes
        GL.glEnable(GL.GL_CULL_FACE)
        GL.glFrontFace(GL.GL_CW)
        # No depth testing
        GL.glDisable(GL.GL_DEPTH_TEST)
        # Enable additive blending
        GL.glEnable(GL.GL_BLEND)
        GL.glBlendFunc(GL.GL_ONE, GL.GL_ONE)

        with self.lightbuffer:
            for light in self.point_lights:
                # Calc light properties
                light_size = light.radius
                m_light = matrix44.multiply(light.matrix, camera_matrix)
                # Draw the light volume
                with self.unit_cube.bind(self.point_light_shader) as s:
                    s.uniform_mat4("m_proj", projection.matrix)
                    s.uniform_mat4("m_light", m_light)
                    s.uniform_sampler_2d(0, "g_normal",
                                         self.gbuffer.color_buffers[1])
                    s.uniform_sampler_2d(1, "g_depth",
                                         self.gbuffer.depth_buffer)
                    s.uniform_2f("screensize", self.width, self.height)
                    s.uniform_2f("proj_const",
                                 *projection.projection_constants)
                    s.uniform_1f("radius", light_size)
                self.unit_cube.draw()

        GL.glDisable(GL.GL_BLEND)
        GL.glDisable(GL.GL_CULL_FACE)
 def create_perspective_projection():
     view = matrix44.create_from_translation(Vector3([0.0, 0.0, -2.0]))
     projection = matrix44.create_perspective_projection_matrix(45.0, 1280.0 / 720.0, 0.1, 100.0)
     vp = matrix44.multiply(view, projection).flatten().astype("float32")
     c_vp = numpy.ctypeslib.as_ctypes(vp)
     vp_loc = glGetUniformLocation(InitShader.shader, b"vp")
     glUniformMatrix4fv(vp_loc, 1, GL_FALSE, c_vp)
    def render(self, time: float, frametime: float):
        """Render the scene"""
        self.ctx.enable_only(moderngl.DEPTH_TEST)  # | moderngl.CULL_FACE)

        # Create camera matrix with rotation and translation
        translation = matrix44.create_from_translation((0, 0, -1.5))
        # rotation = matrix44.create_from_eulers((time, time, time))
        rotation = matrix44.create_from_eulers((0, 0, 0))
        model_matrix = matrix44.multiply(rotation, translation)

        camera_matrix = matrix44.multiply(model_matrix, self.camera.matrix)

        self.scene.draw(
            projection_matrix=self.camera.projection.matrix,
            camera_matrix=camera_matrix,
            time=time,
        )
示例#20
0
	def GetWorldMatrix(self):
		if self.worldMatrix is None or self.isDirty:
			self.isDirty = False
			translation = matrix44.create_from_translation(vector3.create(self.position[0], self.position[1], 0.0))
			rotation = matrix44.create_from_z_rotation(self.rotation)
			self.worldMatrix = matrix44.multiply(rotation, translation)

		return self.worldMatrix
示例#21
0
    def rotate(self):
        ct = time.clock()
        rot_y = Matrix44.from_y_rotation(ct)
        transform = matrix44.multiply(
            rot_y, self.translation).flatten().astype("float32")
        c_transform = numpy.ctypeslib.as_ctypes(transform)

        glUniformMatrix4fv(self.model_loc, 1, GL_FALSE, c_transform)
示例#22
0
def init():
    global shaderProgram
    global vao
    global vbo
    global mvp

    glClearColor(0, 0, 0, 0)

    vertex_code = readShaderFile('piramide.vp')
    fragment_code = readShaderFile('piramide.fp')

    # compile shaders and program
    vertexShader = shaders.compileShader(vertex_code, GL_VERTEX_SHADER)
    fragmentShader = shaders.compileShader(fragment_code, GL_FRAGMENT_SHADER)
    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    # Create and bind the Vertex Array Object
    vao = GLuint(0)
    glGenVertexArrays(1, vao)
    glBindVertexArray(vao)

    # Create and bind the Vertex Buffer Object
    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, piramide['vertices'], GL_STATIC_DRAW)
    glVertexAttribPointer(
        0, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(0))  # first 0 is the location in shader
    glVertexAttribPointer(
        1, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(3 *
                        sizeof(GLfloat)))  # first 0 is the location in shader

    glEnableVertexAttribArray(0)
    # 0=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao
    glEnableVertexAttribArray(1)
    # 1=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao

    # cria a matriz de transformação
    mvp['model'] = matrix44.create_identity()

    # rotacao
    rot = matrix44.create_from_y_rotation(math.radians(10))

    mvp['model'] = matrix44.multiply(mvp['model'], rot)  # matrix model
    mvp['view'] = matrix44.create_identity()  # matrix view
    mvp['projection'] = matrix44.create_identity()  # matrix projection

    # atribui uma variavel uniforme para cada matriz
    mvp['idMod'] = glGetUniformLocation(shaderProgram, "model")
    mvp['idView'] = glGetUniformLocation(shaderProgram, "view")
    mvp['idProj'] = glGetUniformLocation(shaderProgram, "projection")

    # Note that this is allowed, the call to glVertexAttribPointer registered VBO
    # as the currently bound vertex buffer object so afterwards we can safely unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    # Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
    glBindVertexArray(0)
示例#23
0
    def draw_bbox(self, m_proj, m_mv, shader, vao):
        if self.matrix is not None:
            m_mv = matrix44.multiply(self.matrix, m_mv)

        if self.mesh:
            self.mesh.draw_bbox(m_proj, m_mv, shader, vao)

        for child in self.children:
            child.draw_bbox(m_proj, m_mv, shader, vao)
示例#24
0
    def draw(self, m_proj, m_mv, time=0):
        if self.matrix is not None:
            m_mv = matrix44.multiply(self.matrix, m_mv)

        if self.mesh:
            self.mesh.draw(m_proj, m_mv, time=time)

        for child in self.children:
            child.draw(m_proj, m_mv)
示例#25
0
    def view_matrix(camera):
        translation_matrix = np.matrix([[1, 0, 0, -camera.position[0]],
                                        [0, 1, 0, -camera.position[1]],
                                        [0, 0, 1, -camera.position[2]],
                                        [0, 0, 0, 1]])
        rotation_matrix_x = matrix44.create_from_x_rotation(
            np.radians(camera.pitch))
        rotation_matrix_y = matrix44.create_from_y_rotation(
            np.radians(camera.yaw))
        rotation_matrix_z = matrix44.create_from_z_rotation(
            np.radians(camera.roll))

        rot = np.dot(rotation_matrix_x,
                     np.dot(rotation_matrix_y, rotation_matrix_z))
        txy = matrix44.multiply(rot, translation_matrix)
        view_matrix = matrix44.multiply(txy, rotation_matrix_z)

        return view_matrix
示例#26
0
    def randomize_dining_geometry(self, side):
        if side:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, 1.55])
        else:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, -1.75])

        if random.random() < 0.125:
            area_pos[1] = -3
            for table in self.geometry["tables"]:
                table.visible = False
            for chair in self.geometry["chairs"]:
                chair.visible = False

        self.dining_pos = area_pos
        dining_transform = m44.multiply(m44.create_from_y_rotation(random.random() * 2 * np.pi), m44.create_from_translation(area_pos))

        # Randomize table
        self.table_index = int(random.random() * len(self.geometry["tables"])) 
        for idx in range(len(self.geometry["tables"])):
            if idx == self.table_index:
                self.geometry["tables"][idx].transform = dining_transform
                self.geometry["tables"][idx].visible = True
            else:
                self.geometry["tables"][idx].transform = self.hide_transform
                self.geometry["tables"][idx].visible = False

        # Randomize chairs
        chairTranslations = np.array([[-0.45, 0, -0.75], [0.25, 0, -0.75], [-.45, 0, 0.75], [0.25, 0, 0.75]])
        chairTransformations = [m44.create_from_translation(x) for x in chairTranslations]
        chair_index = int(random.random() * self.num_chair_models)
        counter = 0
        for idx in range(len(self.geometry["chairs"])):
            if idx // self.num_chair_models == chair_index and random.random() > 0.25:
                matrix = chairTransformations[counter]
                if counter < 2:
                    matrix = m44.multiply(m44.create_from_y_rotation(np.pi), matrix)
                matrix = m44.multiply(m44.create_from_y_rotation((random.random() - 0.5) * np.pi / 6), matrix)
                matrix = m44.multiply(matrix, dining_transform)
                self.geometry["chairs"][idx].transform = matrix
                self.geometry["chairs"][idx].visible = True
                counter += 1
            else:
                self.geometry["chairs"][idx].transform = self.hide_transform
                self.geometry["chairs"][idx].visible = False
示例#27
0
    def render(self, time, frametime):
        self.ctx.enable_only(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
        self.lightpos = Vector3((math.sin(time) * 20, 5, math.cos(time) * 20),
                                dtype='f4')
        scene_pos = Vector3((0, -5, -32), dtype='f4')

        # --- PASS 1: Render shadow map
        self.offscreen.clear()
        self.offscreen.use()

        depth_projection = Matrix44.orthogonal_projection(-20,
                                                          20,
                                                          -20,
                                                          20,
                                                          -20,
                                                          40,
                                                          dtype='f4')
        depth_view = Matrix44.look_at(self.lightpos, (0, 0, 0), (0, 1, 0),
                                      dtype='f4')
        depth_mvp = depth_projection * depth_view
        self.shadowmap_program['mvp'].write(depth_mvp)

        self.floor.render(self.shadowmap_program)
        self.wall.render(self.shadowmap_program)
        self.sphere.render(self.shadowmap_program)

        # --- PASS 2: Render scene to screen
        self.wnd.use()
        self.basic_light['m_proj'].write(self.camera.projection.matrix)
        self.basic_light['m_camera'].write(self.camera.matrix)
        self.basic_light['m_model'].write(
            Matrix44.from_translation(scene_pos, dtype='f4'))
        bias_matrix = Matrix44(
            [[0.5, 0.0, 0.0, 0.0], [0.0, 0.5, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0],
             [0.5, 0.5, 0.5, 1.0]],
            dtype='f4',
        )
        self.basic_light['m_shadow_bias'].write(
            matrix44.multiply(depth_mvp, bias_matrix))
        self.basic_light['lightDir'].write(self.lightpos)
        self.offscreen_depth.use(location=0)
        self.floor.render(self.basic_light)
        self.wall.render(self.basic_light)
        self.sphere.render(self.basic_light)

        # Render the sun position
        self.sun_prog['m_proj'].write(self.camera.projection.matrix)
        self.sun_prog['m_camera'].write(self.camera.matrix)
        self.sun_prog['m_model'].write(
            Matrix44.from_translation(self.lightpos + scene_pos, dtype='f4'))
        self.sun.render(self.sun_prog)

        # --- PASS 3: Debug ---
        # self.ctx.enable_only(moderngl.NOTHING)
        self.offscreen_depth.use(location=0)
        self.offscreen_quad.render(self.raw_depth_prog)
示例#28
0
    def model_matrix(thing):
        translation_matrix = np.matrix([[1, 0, 0, thing.position[0]],
                                        [0, 1, 0, thing.position[1]],
                                        [0, 0, 1, thing.position[2]],
                                        [0, 0, 0, 1]])
        rotation_matrix_x = matrix44.create_from_x_rotation(
            np.radians(thing.rotX))
        rotation_matrix_y = matrix44.create_from_y_rotation(
            np.radians(thing.rotY))
        rotation_matrix_z = matrix44.create_from_z_rotation(
            np.radians(thing.rotZ))
        scale_matrix = matrix44.create_from_scale(thing.scale)

        tx = matrix44.multiply(translation_matrix, rotation_matrix_x)
        txy = matrix44.multiply(tx, rotation_matrix_y)
        tr = matrix44.multiply(txy, rotation_matrix_z)
        model_matrix = matrix44.multiply(tr, scale_matrix)

        return model_matrix
示例#29
0
    def render(self, time: float, frametime: float):
        self.ctx.enable_only(moderngl.CULL_FACE | moderngl.DEPTH_TEST)

        m_rot = Matrix44.from_eulers(Vector3((time, time, time)))
        m_trans = matrix44.create_from_translation(Vector3((0.0, 0.0, -3.0)))
        m_mv = matrix44.multiply(m_rot, m_trans)

        self.prog['m_model'].write(m_mv.astype('f4').tobytes())
        self.prog['m_camera'].write(self.camera.matrix.astype('f4').tobytes())
        self.cube.render(self.prog)
示例#30
0
    def randomize_living_geometry(self, side):
        if side:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, -1.75])
        else:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, 1.25])

        if random.random() < 0.125:
            area_pos[1] = -3
            for sofa in self.geometry["sofas"]:
                sofa.visible = False
            self.geometry["armchair"][0].visible = False
            self.geometry["rug"][0].visible = False
            for coffee_table in self.geometry["coffee_tables"]:
                coffee_table.visible = False

        self.living_pos = area_pos
        living_transform = m44.multiply(m44.create_from_y_rotation(random.random() * 2 * np.pi), m44.create_from_translation(area_pos))
        
        # Select sofa and transform
        sofa_index = int(random.random() * len(self.geometry["sofas"]))
        sofa_transform = m44.multiply(m44.create_from_y_rotation(0.5 * np.pi), m44.create_from_translation(np.array([1.05, 0, 0.05])))
        for idx in range(len(self.geometry["sofas"])):
            if idx == sofa_index:
                self.geometry["sofas"][idx].transform = m44.multiply(sofa_transform, living_transform)
                self.geometry["sofas"][idx].visible = True
            else:
                self.geometry["sofas"][idx].transform = self.hide_transform
                self.geometry["sofas"][idx].visible = False
        
        armchair_transform = m44.multiply(m44.create_from_y_rotation(-0.83 * np.pi + 0.1 * np.pi * (random.random() - 0.5)), m44.create_from_translation(np.array([-0.9, 0, 0.65])))
        self.geometry["armchair"][0].transform = m44.multiply(armchair_transform, living_transform)
        self.geometry["armchair"][0].visible = True

        rug_transform = m44.multiply(m44.create_from_y_rotation(0.05 * np.pi * (random.random() - 0.5)), m44.create_from_translation(np.array([0, 0.005, 0])))
        self.geometry["rug"][0].transform = m44.multiply(rug_transform, living_transform)
        self.geometry["rug"][0].visible = True

        # Select coffee table and transform
        coffee_table_transform = m44.multiply(m44.create_from_y_rotation(-0.5 * np.pi), m44.create_from_translation(np.array([0.1, 0.006, 0])))
        coffee_table_index = int(random.random() * len(self.geometry["coffee_tables"]))
        for idx in range(len(self.geometry["coffee_tables"])):
            if idx == coffee_table_index:
                self.geometry["coffee_tables"][idx].transform = m44.multiply(coffee_table_transform, living_transform)
                self.geometry["coffee_tables"][idx].visible = True
            else:
                self.geometry["coffee_tables"][idx].transform = self.hide_transform
                self.geometry["coffee_tables"][idx].visible = False
示例#31
0
    def check_projection_classifies_point_correctly( self, matrix, point, is_inside ):
        transformed = matrix44.multiply( point, matrix )

        # Avoid division by zero warning
        if transformed[ 3 ] == 0:
            assert not is_inside
        else:
            transformed[ 0:3 ] /= transformed[ 3 ]

            max_coordinate = max( abs( c ) for c in transformed[ 0:3 ] )
            assert is_inside == ( max_coordinate <= 1.0 )
示例#32
0
def on_draw():
    global time
    time += 0.01
    game_window.clear()
    ctx.screen.use()

    trans = matrix44.create_from_translation(
        (math.cos(time), math.sin(time / 5) * 5 - 6, 0))
    rot = matrix44.create_from_y_rotation(math.pi / 2)
    mat = matrix44.multiply(trans, rot)

    ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
    scene.draw(
        projection_matrix=projection,
        camera_matrix=mat,
    )

    fbo.use()
    fbo.clear()

    gl.glUseProgram(0)
    gl.glBindVertexArray(0)

    main_batch.draw()
    counter.draw()

    trans = matrix44.create_from_translation([0, 0, -1])
    rot = matrix44.create_from_axis_rotation(
        [math.sin(time) / 4,
         math.cos(time) / 4,
         math.sin(time) / 20],
        math.sin(time) / 5)
    mat = matrix44.multiply(trans, rot)

    ctx.screen.use()
    fbo.color_attachments[0].use(location=0)
    texture_program['scale'].value = (800 / window_x, 600 / window_y)
    texture_program['m_proj'].write(projection)
    texture_program['m_view'].write(mat.astype('f4').tobytes())
    quad.render(texture_program)
    def render(self):
        # creating a rotation matrix for the monkey
        ct = time.clock()
        rot_y = Matrix44.from_y_rotation(ct*0.5)
        rot_y = matrix44.multiply(rot_y, InitShader.monkey_model).flatten().astype("float32")
        c_rotate = numpy.ctypeslib.as_ctypes(rot_y)

        # to draw the monkey, we need to rebind the monkey's vao
        glBindVertexArray(self.vao_monkey)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        glUniformMatrix4fv(InitShader.model_loc, 1, GL_FALSE, c_rotate)
        glDrawArrays(GL_TRIANGLES, 0, self.num_verts)
        glBindVertexArray(0)
示例#34
0
    def render(self, time, frametime):
        # time = self.wnd.frames / 30

        self.ctx.enable_only(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
        self.render_pygame(time)

        rotate = matrix44.create_from_eulers((time, time * 1.2, time * 1.3), dtype='f4')
        translate = matrix44.create_from_translation((0, 0, -3.5), dtype='f4')
        camera = matrix44.multiply(rotate, translate)

        self.texture_prog['m_camera'].write(camera)
        self.pg_texture.use()
        self.cube.render(self.texture_prog)
示例#35
0
    def render(self, camera, time, frame_time):
        """Custom render method to gain exact control over the scene"""
        self.process_events(time, frame_time)
        cam = camera.matrix
        translate = matrix44.create_from_translation((0, -2, -10), dtype='f4')
        cam = matrix44.multiply(translate, cam)

        # Draw static geometry with default scene shader
        self.highway.draw(projection_matrix=camera.projection.matrix,
                          camera_matrix=cam)

        # Inner rings
        self.inner_ring_prog['m_cam'].write(cam)
        self.inner_ring_prog['rotation'] = self.inner_rings_rotation
        self.inner_ring_prog['ring_spacing'] = self.inner_ring_spacing
        self.inner_ring_vao.render(self.inner_ring_prog, instances=20)

        # Outer rings
        self.outer_ring_prog['m_cam'].write(cam)
        self.outer_ring_prog['rotation'] = -self.inner_rings_rotation
        self.outer_ring_vao.render(self.outer_ring_prog, instances=11)

        # Ring neons
        self.ring_neon_prog['m_cam'].write(cam)
        self.ring_neon_prog['rotation'] = -self.inner_rings_rotation
        self.ring_neon_prog['color'] = self.light_ring_color
        self.ring_neon_1.render(self.ring_neon_prog, instances=11)
        self.ring_neon_2.render(self.ring_neon_prog, instances=11)
        self.ring_neon_3.render(self.ring_neon_prog, instances=11)
        self.ring_neon_4.render(self.ring_neon_prog, instances=11)

        # Light - static
        self.light_static_prog['m_cam'].write(cam)
        self.light_static_prog['color'] = self.laser_left_color
        self.light_left_static_vao.render(self.light_static_prog)
        self.light_static_prog['color'] = self.laser_right_color
        self.light_right_static_vao.render(self.light_static_prog)
        self.light_static_prog['color'] = self.light_center_color
        self.light_center_static_vao.render(self.light_static_prog)
        self.light_static_prog['color'] = self.light_back_color
        self.light_back_static_vao.render(self.light_static_prog)

        # Light - Moving lasers
        self.laser_prog['m_cam'].write(cam)
        self.laser_prog['color'] = self.laser_left_color
        self.laser_prog['rotation'] = self.left_laser_rot
        self.laser_prog['time'] = time
        self.laser_left_1.render(self.laser_prog, instances=4)
        self.laser_prog['color'] = self.laser_right_color
        self.laser_prog['rotation'] = self.right_laser_rot
        self.laser_right_1.render(self.laser_prog, instances=4)
示例#36
0
    def matrix(self):
        """
        Returns a matrix representing the node's
        object translation, orientation and
        scale.
        """
        if self._matrix == None:
            if self.parent == None:
                self._matrix = self._transform.matrix.copy()
            else:
                self._matrix = matrix44.multiply(self._transform.matrix,
                                                 self.parent.matrix)

        return self._matrix
示例#37
0
文件: camera.py 项目: neumic/game01
def lookAtMatrix( camera, target, up ):
   forward = vector.normalise(target - camera)
   side = vector.normalise( vector.cross( forward, up ) )
   #shifts 'up' to the camera's up
   up = vector.cross( side, forward )

   matrix2 = array(
      [[ side[0], up[0], -forward[0], 0.0 ],
       [ side[1], up[1], -forward[1], 0.0 ], 
       [ side[2], up[2], -forward[2], 0.0 ], 
       [     0.0,   0.0,         0.0, 1.0 ]],
      dtype = float32)

   return array(mat4.multiply( mat4.create_from_translation( -camera ), matrix2 ), dtype=float32)
示例#38
0
	def render(self):
		t = clock()
		self.time_parameter.set_value(t)

		data = (
			((-0.5, -0.5, 0), (0.0, 0.0)),
			((0.5, -0.5, 0), (1.0, 0.0)),
			((0, 0.5, 0), (0.5, 1.0)),
		)

		proj = matrix44.create_perspective_projection_matrix(
			90, 4.0 / 3.0, 0.01, 100.0)

		mv = matrix44.multiply(
			matrix44.create_from_translation((sin(t * 10), 0.0, -3.0 * abs(sin(t * 30)))),
			matrix44.create_from_z_rotation(t * 50),
		)
 
		mvp = matrix44.multiply(mv, proj)

		self.model_view_proj.set_value(mvp)

		for pass_ in self.technique.passes:
			pass_.begin()

			gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

			gl.glBegin(gl.GL_TRIANGLES)

			for position, texcoord in data:
				gl.glMultiTexCoord2fv(gl.GL_TEXTURE0, texcoord)
				gl.glVertex3fv(position)

			gl.glEnd()

			pass_.end()
示例#39
0
    def test_operators_matrix33(self):
        m1 = Matrix44.identity()
        m2 = Matrix33.from_x_rotation(0.5)

        # add
        self.assertTrue(np.array_equal(m1 + m2, matrix44.create_identity() + matrix44.create_from_x_rotation(0.5)))

        # subtract
        self.assertTrue(np.array_equal(m1 - m2, matrix44.create_identity() - matrix44.create_from_x_rotation(0.5)))

        # multiply
        self.assertTrue(np.array_equal(m1 * m2, matrix44.multiply(matrix44.create_identity(), matrix44.create_from_x_rotation(0.5))))

        # divide
        self.assertRaises(ValueError, lambda: m1 / m2)
示例#40
0
    def test_operators_quaternion(self):
        m = Matrix44.identity()
        q = Quaternion.from_x_rotation(0.7)
        
        # add
        self.assertRaises(ValueError, lambda: m + q)

        # subtract
        self.assertRaises(ValueError, lambda: m - q)

        # multiply
        self.assertTrue(np.array_equal(m * q, matrix44.multiply(matrix44.create_identity(), matrix44.create_from_quaternion(quaternion.create_from_x_rotation(0.7)))))

        # divide
        self.assertRaises(ValueError, lambda: m / q)
示例#41
0
    def matrix( self ):
        """
        Returns a matrix representing the node's
        object translation, orientation and
        scale.
        """
        if self._matrix == None:
            if self.parent == None:
                self._matrix = self._transform.matrix.copy()
            else:
                self._matrix = matrix44.multiply(
                    self._transform.matrix,
                    self.parent.matrix
                    )

        return self._matrix
示例#42
0
    def render_scene( self, camera ):
        """Renders each renderable in the scene
        using the current projection and model
        view matrix.
        The original GL state will be restored
        upon leaving this function.
        """
        projection = camera.view_matrix.matrix
        model_view = camera.model_view

        # update the model view
        world_matrix = self.mesh_node.world_transform.matrix
        current_mv = matrix44.multiply(
            world_matrix,
            model_view
            )

        # render a cube
        self.mesh_node.render(
            projection = projection,
            model_view = current_mv
            )
示例#43
0
    def render_scene( self, camera ):
        """Renders each renderable in the scene
        using the current projection and model
        view matrix.
        The original GL state will be restored
        upon leaving this function.
        """
        projection = camera.view_matrix.matrix
        model_view = camera.model_view

        # bind our diffuse texture
        glActiveTexture( GL_TEXTURE0 )
        self.texture.bind()

        # iterate through our renderables
        for node, frame in zip(self.renderables, self.frames):
            # update the model view
            world_matrix = node.world_transform.matrix
            current_mv = matrix44.multiply(
                world_matrix,
                model_view
                )

            fraction, frame1 = math.modf( frame )
            frame2 = (frame1 + 1.0) % node.mesh.num_frames

            # update the frame
            node.mesh.frame_1 = int(frame1)
            node.mesh.frame_2 = int(frame2)
            node.mesh.interpolation = fraction

            # render a cube
            node.render(
                projection = projection,
                model_view = current_mv
                )

        glActiveTexture( GL_TEXTURE0 )
        self.texture.unbind()
示例#44
0
文件: camera.py 项目: neumic/game01
   def regenViewMatrix(self):
      forward = array([ math.cos( self.verticalAngle ) * math.sin( self.horizontalAngle ),
                        math.sin( self.verticalAngle ),
                        math.cos( self.verticalAngle ) * math.cos( self.horizontalAngle ) ])
      up = array([0.,-1.,0.,])
      side = -vector.normalise( vector.cross( forward, up ) )
      #shifts 'up' to the camera's up
      up = vector.cross( side, forward )

      matrix2 = array(
         [[ side[0], up[0], forward[0], 0.0 ],
          [ side[1], up[1], forward[1], 0.0 ], 
          [ side[2], up[2], forward[2], 0.0 ], 
          [     0.0,   0.0,         0.0, 1.0 ]],
         dtype = float32)

      self.position += forward * self.xMovement
      self.position += side    * self.yMovement

      self.xMovement = self.yMovement = 0.

      self.viewMatrix =  array(mat4.multiply( mat4.create_from_translation( self.position ), matrix2 ), dtype=float32)
示例#45
0
 def test_multiply_rotation(self):
     m1 = matrix44.create_from_x_rotation(np.pi)
     m2 = matrix44.create_from_y_rotation(np.pi / 2.0)
     result = matrix44.multiply(m1, m2)
     self.assertTrue(np.allclose(result, np.dot(m1,m2)))
示例#46
0
    def test_rotation( self ):
        """
        Rotation and Inheritance
        """

        # we'll add a child to a root node
        # we'll move the child
        # rotate the root
        # and check the child is where it should be
        # the child should be moved somewhere that will
        # make it easy to check

        root = SceneNode( '/root' )
        child = SceneNode( '/child' )
        
        root.add_child( child )

        #
        # Rotate 180 deg (1 * pi) about the Y axis (yaw)
        #
        root.transform.object.rotate_y( math.pi )

        identity = matrix44.identity()
        root_matrix = matrix44.create_from_y_rotation( math.pi )

        # root object
        test_axis( self, root.transform.object, root_matrix )
        test_axis( self, root.transform.inertial, identity )
        test_axis( self, root.world_transform.object, root_matrix )
        test_axis( self, root.world_transform.inertial, identity )

        child_matrix = matrix44.identity()
        test_axis( self, child.transform.object, child_matrix )
        test_axis( self, child.transform.inertial, identity )
        test_axis( self, child.world_transform.object, root_matrix )
        test_axis( self, child.world_transform.inertial, identity )


        # check the node matrix matches what we're seeing in
        # the transform axis values
        self.assertTrue(
            numpy.allclose( root.transform.matrix, root_matrix ),
            "Root Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( root.world_transform.matrix, root_matrix ),
            "Root RootMatrix incorrect"
            )

        self.assertTrue(
            numpy.allclose( child.transform.matrix, identity ),
            "Child Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( child.world_transform.matrix, root_matrix ),
            "Child RootMatrix incorrect"
            )


        #
        # Rotate 180 deg (1 * pi) about the X axis (pitch)
        #
        # rotate 180 deg / 1pi about the x axis (pitch)
        child.transform.object.rotate_x( math.pi )

        child_matrix = matrix44.multiply(
            matrix44.create_from_x_rotation( math.pi ),
            child_matrix
            )

        child_world = matrix44.multiply( child_matrix, root_matrix )

        # root object
        test_axis( self, root.transform.object, root_matrix )
        test_axis( self, root.transform.inertial, identity )
        test_axis( self, root.world_transform.object, root_matrix )
        test_axis( self, root.world_transform.inertial, identity )

        test_axis( self, child.transform.object, child_matrix )
        test_axis( self, child.transform.inertial, identity )
        test_axis( self, child.world_transform.object, child_world )
        test_axis( self, child.world_transform.inertial, identity )

        # check the node matrix matches what we're seeing in
        # the transform axis values
        self.assertTrue(
            numpy.allclose( root.transform.matrix, root_matrix ),
            "Root Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( root.world_transform.matrix, root_matrix ),
            "Root RootMatrix incorrect"
            )

        self.assertTrue(
            numpy.allclose( child.transform.matrix, child_matrix ),
            "Child Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( child.world_transform.matrix, child_world ),
            "Child RootMatrix incorrect"
            )
示例#47
0
	def _CreateMatrix(self):
		self.worldMatrix = matrix44.multiply(
								matrix44.create_from_translation(self.position), 
								matrix44.create_from_quaternion(self.rotation)
							)
示例#48
0
 def test_multiply_identity(self):
     m1 = matrix44.create_identity()
     m2 = matrix44.create_identity()
     result = matrix44.multiply(m1, m2)
     self.assertTrue(np.allclose(result, np.dot(m1,m2)))
示例#49
0
文件: main.py 项目: neumic/game01
   inputHandler.handleInput()
   
   glBindFramebuffer(GL_FRAMEBUFFER, framebufferName);
   glViewport(0,0,HEIGHT,WIDTH)
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )

   glUseProgram( programId )

   timePassed = clock.tick()

   camera.regenProjectionMatrix()
   projection = camera.getProjectionMatrix()
   camera.regenViewMatrix()
   view = camera.getViewMatrix()
   model = array(mat4.create_identity(), dtype=float32)
   MVP = array( mat4.multiply(mat4.multiply(model, view), projection ), dtype=float32)

   glUniformMatrix4fv( matrixId, 1, GL_FALSE, MVP )
   glActiveTexture(GL_TEXTURE0)
   glBindTexture(GL_TEXTURE_2D, textureId)
   glUniform1i(textureSamplerId, 0);

   glEnableClientState(GL_VERTEX_ARRAY)
   glEnableClientState(GL_NORMAL_ARRAY)
   vert_norm_vbo.bind()
   index_vbo.bind()

   glVertexPointerf( vert_norm_vbo )
   glNormalPointerf( vert_norm_vbo + len(vert_array) )

   glDrawElements( GL_TRIANGLES, len(index_vbo.flat), GL_UNSIGNED_INT, index_vbo )