Ejemplo n.º 1
0
def test_decompose():
    # define expectations
    expected_scale = pyrr.Vector3([1, 1, 2], dtype='f4')
    expected_rotation = pyrr.Quaternion.from_y_rotation(np.pi, dtype='f4')
    expected_translation = pyrr.Vector3([10, 0, -5], dtype='f4')
    expected_model = pyrr.Matrix44([
        [-1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, -2, 0],
        [10, 0, -5, 1],
    ],
                                   dtype='f4')

    # compose matrix using Pyrr
    s = pyrr.Matrix44.from_scale(expected_scale, dtype='f4')
    r = pyrr.Matrix44.from_quaternion(expected_rotation, dtype='f4')
    t = pyrr.Matrix44.from_translation(expected_translation, dtype='f4')
    model = t * r * s
    npt.assert_almost_equal(model, expected_model)
    assert model.dtype == expected_model.dtype

    # decompose matrix
    scale, rotation, translation = maths.decompose(model)
    npt.assert_almost_equal(scale, expected_scale)
    assert scale.dtype == expected_scale.dtype
    npt.assert_almost_equal(rotation, expected_rotation)
    assert rotation.dtype == expected_rotation.dtype
    npt.assert_almost_equal(translation, expected_translation)
    assert translation.dtype == expected_translation.dtype
Ejemplo n.º 2
0
 def asDataTypeClass(self):
     return pyrr.Matrix44([[
         self.dsbm11.value(),
         self.dsbm12.value(),
         self.dsbm13.value(),
         self.dsbm14.value()
     ],
                           [
                               self.dsbm21.value(),
                               self.dsbm22.value(),
                               self.dsbm23.value(),
                               self.dsbm24.value()
                           ],
                           [
                               self.dsbm31.value(),
                               self.dsbm32.value(),
                               self.dsbm33.value(),
                               self.dsbm34.value()
                           ],
                           [
                               self.dsbm41.value(),
                               self.dsbm42.value(),
                               self.dsbm43.value(),
                               self.dsbm44.value()
                           ]])
Ejemplo n.º 3
0
def test_model_setter():
    a = radiant.Object3D()
    assert a.dirty is True
    a.update()
    assert a.dirty is False

    # define expectations
    expected_scale = pyrr.Vector3([1, 1, 2], dtype='f4')
    expected_rotation = pyrr.Quaternion.from_y_rotation(np.pi, dtype='f4')
    expected_translation = pyrr.Vector3([10, 0, -5], dtype='f4')
    expected_model = pyrr.Matrix44([
        [-1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, -2, 0],
        [10, 0, -5, 1],
    ], dtype='f4')

    # call setter
    a.model = expected_model
    assert a.dirty is True
    a.update()
    assert a.dirty is False

    # assertions
    npt.assert_almost_equal(a.scale, expected_scale)
    assert a.scale.dtype == expected_scale.dtype
    npt.assert_almost_equal(a.rotation, expected_rotation)
    assert a.rotation.dtype == expected_rotation.dtype
    npt.assert_almost_equal(a.position, expected_translation)
    assert a.position.dtype == expected_translation.dtype
Ejemplo n.º 4
0
def sun_shadowmap_matrix(sun_from_world_matrix, view_from_world_matrix, near,
                         far):
    INFINITY = float('inf')
    aabb = {
        'min': pyrr.Vector3([INFINITY, INFINITY, INFINITY]),
        'max': pyrr.Vector3([-INFINITY, -INFINITY, -INFINITY])
    }

    for corner in frustum_corners(view_from_world_matrix, near, far):
        corner = sun_from_world_matrix * corner
        aabb['min'].x = min(aabb['min'].x, corner.x)
        aabb['min'].y = min(aabb['min'].y, corner.y)
        aabb['min'].z = min(aabb['min'].z, corner.z)
        aabb['max'].x = max(aabb['max'].x, corner.x)
        aabb['max'].y = max(aabb['max'].y, corner.y)
        aabb['max'].z = max(aabb['max'].z, corner.z)

    world_from_light_space = sun_from_world_matrix.inverse

    size = aabb['max'] - aabb['min']
    aabb['min'] = world_from_light_space * pyrr.Vector4(
        [*aabb['min'].tolist(), 1.0])
    aabb['max'] = world_from_light_space * pyrr.Vector4(
        [*aabb['max'].tolist(), 1.0])
    center = (aabb['min'] + aabb['max']) / 2.0
    center = pyrr.Vector3(center.tolist()[:3])

    scale = pyrr.Matrix44.from_scale(size)
    translate = pyrr.Matrix44.from_translation(center)

    matrix = translate * world_from_light_space * scale

    screen = pyrr.Matrix44([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1])

    return screen * matrix.inverse
Ejemplo n.º 5
0
def make_projection_matrix(fov, aspect_ratio, near, far):
    x_scale = 1.0 / math.tan(fov / 2.0)
    y_scale = x_scale * aspect_ratio
    return pyrr.Matrix44([
        x_scale, 0, 0, 0, 0, y_scale,
        0, 0, 0, 0, (-(far + near)) / (far - near), -1, 0, 0,
        (-2.0 * far * near) / (far - near), 0
    ])
Ejemplo n.º 6
0
 def m44GetComp(m=(DataTypes.Matrix44, pyrr.Matrix44()),
                r=(DataTypes.Int, 1),
                c=(DataTypes.Int, 1)):
     '''Returns single scalar from matrix44. r and c taken as abs and clamped in range 1-4.'''
     _r = clamp(abs(r), 1, 4)
     _c = clamp(abs(c), 1, 4)
     name = 'm{0}{1}'.format(_r, _c)
     return getattr(m, name)
Ejemplo n.º 7
0
    def test_imports(self):
        import pyrr
        pyrr.Matrix44()
        pyrr.matrix44.Matrix44()
        pyrr.objects.matrix44.Matrix44()

        from pyrr import Matrix44
        from pyrr.objects import Matrix44
        from pyrr.objects.matrix44 import Matrix44
Ejemplo n.º 8
0
 def m44Decompose(m=('Matrix44Pin', pyrr.Matrix44()),
                  t=("Reference", ('FloatVector3Pin', pyrr.Vector3())),
                  r=("Reference", ('QuatPin', pyrr.Quaternion())),
                  s=("Reference", ('FloatVector3Pin', pyrr.Vector3()))):
     '''Decomposes an affine transformation matrix into its scale, rotation and translation components.'''
     _s, _r, _t = pyrr.matrix44.decompose(m)
     t(pyrr.Vector3(_t))
     r(pyrr.Quaternion(_r))
     s(pyrr.Vector3(_s))
Ejemplo n.º 9
0
 def m44PerspProjBounds(left=(DataTypes.Float, -5.0), right=(DataTypes.Float, 5.0), bottom=(DataTypes.Float, -5.0), top=(DataTypes.Float, 5.0), near=(DataTypes.Float, 0.0), far=(DataTypes.Float, 10.0), result=(DataTypes.Reference, (DataTypes.Bool, False))):
     '''Creates a perspective projection matrix using the specified near plane dimensions.\n\nleft (float) - The left of the near plane relative to the planes centre.\n\nright (float) - The right of the near plane relative to the planes centre.\n\ntop (float) - The top of the near plane relative to the planes centre.\n\nbottom (float) - The bottom of the near plane relative to the planes centre.\n\nnear (float) - The distance of the near plane from the cameras origin. It is recommended that the near plane is set to 1.0 or above to avoid rendering issues at close range.\n\nfar (float) - The distance of the far plane from the cameras origin.'''
     try:
         m = pyrr.Matrix44(pyrr.matrix44.create_perspective_projection_from_bounds(left, right, bottom, top, near, far))
         result(True)
         return m
     except:
         result(False)
         return pyrr.Matrix44.identity()
Ejemplo n.º 10
0
 def m44PerspProj(fovy=(DataTypes.Float, 0.0), aspect=(DataTypes.Float, 0.0), near=(DataTypes.Float, 0.0), far=(DataTypes.Float, 0.0)):
     '''Creates perspective projection matrix.\n\nfovy (float) - field of view in y direction in degrees\n\naspect (float) - aspect ratio of the view (width / height)\n\nnear (float) - distance from the viewer to the near clipping plane (only positive)\n\nfar (float) - distance from the viewer to the far clipping plane (only positive).'''
     try:
         m = pyrr.Matrix44(pyrr.matrix44.create_perspective_projection(fovy, aspect, near, far))
         result(True)
         return m
     except:
         result(False)
         return pyrr.Matrix44.identity()
Ejemplo n.º 11
0
 def set_transform(self):
     transform = pyrr.Matrix44([[self.zoom * 2 / self.width, 0, 0, 0],
                                [0, self.zoom * 2 / self.height, 0, 0],
                                [0, 0, 0, 0],
                                [
                                    -1 + 2 * self.pos[0] / self.width,
                                    -1 + 2 * self.pos[1] / self.height, 0, 1
                                ]])
     tmp = transform.flatten()
     glLoadMatrixf((GLfloat * len(tmp))(*tmp))
Ejemplo n.º 12
0
 def m44Decompose(m=(DataTypes.Matrix44, pyrr.Matrix44()),
                  t=(DataTypes.Reference, (DataTypes.FloatVector3,
                                           pyrr.Vector3())),
                  r=(DataTypes.Reference, (DataTypes.Quaternion,
                                           pyrr.Quaternion())),
                  s=(DataTypes.Reference, (DataTypes.FloatVector3,
                                           pyrr.Vector3()))):
     '''Decomposes an affine transformation matrix into its scale, rotation and translation components.'''
     _s, _r, _t = pyrr.matrix44.decompose(m)
     t(pyrr.Vector3(_t))
     r(pyrr.Quaternion(_r))
     s(pyrr.Vector3(_s))
Ejemplo n.º 13
0
    def on_draw(self):
        glClearColor(0.1, 0.1, 0.1, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
        self.projection = pyrr.matrix44.create_perspective_projection(
            radians(self.camera.zoom), self.width / self.height, 0.1, 1000.0)
        self.view = self.camera.get_view_matrix()
        self.shader.set_uniform("projection", self.projection)
        self.shader.set_uniform("view", self.view)

        # Draw!
        glBindVertexArray(self.chunk.vao)
        # Normally we'd translate before drawing a chunk
        model = pyrr.Matrix44()
        self.shader.set_uniform("model", model)
        glDrawArrays(GL_TRIANGLES, 0, len(self.chunk.vertices) // 3)
Ejemplo n.º 14
0
 def m44OrthoProj(left=('FloatPin', -5.0),
                  right=('FloatPin', 5.0),
                  bottom=('FloatPin', -5.0),
                  top=('FloatPin', 5.0),
                  near=('FloatPin', 0.0),
                  far=('FloatPin', 10.0),
                  result=("Reference", ('BoolPin', False))):
     '''Creates an orthogonal projection matrix.\n\nleft (float) - The left of the near plane relative to the planes centre.\n\nright (float) - The right of the near plane relative to the planes centre.\n\ntop (float) - The top of the near plane relative to the planes centre.\n\nbottom (float) - The bottom of the near plane relative to the planes centre.\n\nnear (float) - The distance of the near plane from the cameras origin. It is recommended that the near plane is set to 1.0 or above to avoid rendering issues at close range.\n\nfar (float) - The distance of the far plane from the cameras origin.'''
     try:
         m = pyrr.Matrix44(
             pyrr.matrix44.create_orthogonal_projection(
                 left, right, bottom, top, near, far))
         result(True)
         return m
     except:
         result(False)
         return pyrr.Matrix44.identity()
Ejemplo n.º 15
0
    def render(self):
        rendertime = time.time()

        GL.glClearColor(0, 0, 0, 1)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        # active shader program
        GL.glUseProgram(self.window.shader)

        # Bind Texture
        GL.glBindTexture(GL.GL_TEXTURE_2D, self.window.texture)

        # Create transformations
        # transform = pyrr.Matrix44().identity()
        rad = numpy.radians(glfw.get_time() * 50.0)
        tr_translate = pyrr.matrix44.create_from_translation([0.5, -0.5, 0.0])
        tr_scale = pyrr.Matrix44().from_scale([1.5, 1.5, 0.5])
        tr_rotation = pyrr.matrix44.create_from_axis_rotation([0.0, 0.0, 1.0],
                                                              rad)

        # Applies right to left
        transform = tr_scale * tr_rotation * tr_translate

        loc = GL.glGetUniformLocation(self.window.shader, 'transform')
        # GL.glUniformMatrix4fv(loc, 1, GL.GL_FALSE, transform)
        GL.glUniformMatrix4fv(loc, 1, GL.GL_FALSE,
                              transform.__array__().astype(numpy.float32))

        try:
            GL.glBindVertexArray(self.VAO)

            # Draw a triangle
            # GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)

            # draw triangle, starting index of the vertex array, # of vertices (6 = indexData.size),
            # EBO indexes remain the same (accounts for stride of extra data
            GL.glDrawElements(GL.GL_TRIANGLES, self.index_size,
                              GL.GL_UNSIGNED_INT, None)
        finally:
            # Unbind when we finish
            GL.glBindVertexArray(0)
            GL.glUseProgram(0)

        self.rendertime = 1000 * (time.time() - rendertime)
Ejemplo n.º 16
0
 def m44quat(m=(DataTypes.Matrix44, pyrr.Matrix44())):
     '''Returns a Quaternion representing this matrix.'''
     return m.quaternion
Ejemplo n.º 17
0
 def v4FromM44Tr(m=('Matrix44Pin', pyrr.Matrix44())):
     '''Create vector4 from matrix44 translation.'''
     return pyrr.Vector4(pyrr.vector4.create_from_matrix44_translation(m))
Ejemplo n.º 18
0
 def quatFromMatrix44(m=(DataTypes.Matrix44, pyrr.Matrix44())):
     '''Creates a Quaternion from the specified Matrix44.'''
     return pyrr.Quaternion.from_matrix(m)
Ejemplo n.º 19
0
class QuatLib(FunctionLibraryBase):
    '''doc string for QuatLib'''
    def __init__(self):
        super(QuatLib, self).__init__()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def zeroQuat():
        '''Returns zero quaternion.'''
        return pyrr.Quaternion()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion.from_x_rotation(0.0)), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromXRotation(theta=(DataTypes.Float, 0.0)):
        '''Creates a new Quaternion with a rotation around the X-axis.'''
        return pyrr.Quaternion.from_x_rotation(theta)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion.from_y_rotation(0.0)), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromYRotation(theta=(DataTypes.Float, 0.0)):
        '''Creates a new Quaternion with a rotation around the Y-axis.'''
        return pyrr.Quaternion.from_y_rotation(theta)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion.from_z_rotation(0.0)), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromZRotation(theta=(DataTypes.Float, 0.0)):
        '''Creates a new Quaternion with a rotation around the Z-axis.'''
        return pyrr.Quaternion.from_z_rotation(theta)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion.from_matrix(pyrr.Matrix33())), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromMatrix33(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Creates a Quaternion from the specified Matrix33.'''
        return pyrr.Quaternion.from_matrix(m)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion.from_matrix(pyrr.Matrix44())), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromMatrix44(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Creates a Quaternion from the specified Matrix44.'''
        return pyrr.Quaternion.from_matrix(m)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromEulers(a=(DataTypes.Float, 0.0), b=(DataTypes.Float, 0.0), c=(DataTypes.Float, 0.0)):
        '''Creates a Quaternion from the specified Euler angles.'''
        return pyrr.Quaternion.from_eulers([a, b, c])

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromInverseOfEulers(a=(DataTypes.Float, 0.0), b=(DataTypes.Float, 0.0), c=(DataTypes.Float, 0.0)):
        '''Creates a Quaternion from the specified Euler angles.'''
        return pyrr.Quaternion.from_inverse_of_eulers([a, b, c])

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), nodeType=NodeTypes.Pure, meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatFromAxisRotation(a=(DataTypes.Float, 0.0), b=(DataTypes.Float, 0.0), c=(DataTypes.Float, 0.0), theta=(DataTypes.Float, 0.0)):
        '''Creates a new Quaternion with a rotation around the specified axis.'''
        return pyrr.Quaternion.from_axis_rotation([a, b, c], theta)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatApplyToVector(q=(DataTypes.Quaternion, pyrr.Quaternion()), v=(DataTypes.FloatVector3, pyrr.Vector3())):
        '''Rotates a vector by a quaternion.'''
        return pyrr.Vector3(pyrr.quaternion.apply_to_vector(quat=q, vec=v))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, 0.0), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatX(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the x component of the quat.'''
        return q.x

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, 0.0), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatY(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the y component of the quat.'''
        return q.y

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, 0.0), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatZ(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the z component of the quat.'''
        return q.z

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, 0.0), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatW(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the w component of the quat.'''
        return q.w

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, 0.0), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatAngle(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the angle around the axis of rotation of this Quaternion as a float.'''
        return q.angle

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatAxis(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the axis of rotation of this Quaternion as a Vector3.'''
        return q.axis

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatConjugate(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the conjugate of this Quaternion.\nThis is a Quaternion with the opposite rotation.'''
        return q.conjugate

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatCross(q=(DataTypes.Quaternion, pyrr.Quaternion()), other=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the cross of this Quaternion and another.\nThis is the equivalent of combining Quaternion rotations (like Matrix multiplication).'''
        return q.cross(other)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatInverse(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the inverse of this quaternion.'''
        return q.inverse

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Bool, False), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatIsIdentity(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns True if the Quaternion has no rotation (0.,0.,0.,1.).'''
        return q.is_identity

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, False), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatLength(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the length of this Quaternion.'''
        return q.length

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, False), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatSquaredLength(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Calculates the squared length of a quaternion.\nUseful for avoiding the performanc penalty of the square root function.'''
        return pyrr.quaternion.squared_length(q)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatLerp(q1=(DataTypes.Quaternion, pyrr.Quaternion()), q2=(DataTypes.Quaternion, pyrr.Quaternion()), t=(DataTypes.Float, 0.0)):
        '''Interpolates between q1 and q2 by t. The parameter t is clamped to the range [0, 1].'''
        return q1.lerp(q2, t)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatAsMatrix33(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns a Matrix33 representation of this Quaternion.'''
        return q.matrix33

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatAsMatrix44(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns a Matrix44 representation of this Quaternion.'''
        return q.matrix44

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatNegative(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns the negative of the Quaternion.'''
        return q.negative

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatNormalize(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Returns a normalized version of this Quaternion as a new Quaternion.'''
        return q.normalized

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatPower(q=(DataTypes.Quaternion, pyrr.Quaternion()), exp=(DataTypes.Float, 0.0), result=(DataTypes.Reference, (DataTypes.Bool, False))):
        '''Returns a new Quaternion representing this Quaternion to the power of the exponent. Checks for identify quaternion'''
        try:
            powered = q.power(exp)
            result(True)
            return powered
        except:
            result(False)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatSlerp(q1=(DataTypes.Quaternion, pyrr.Quaternion()), q2=(DataTypes.Quaternion, pyrr.Quaternion()), t=(DataTypes.Float, 0.0)):
        '''Spherically interpolates between quat1 and quat2 by t. The parameter t is clamped to the range [0, 1].'''
        return q1.slerp(q2, t)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Bool, False), meta={'Category': 'Math|Quaternion', 'Keywords': []})
    def quatIsZeroLength(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Checks if a quaternion is zero length.'''
        return pyrr.quaternion.is_zero_length(q)
Ejemplo n.º 20
0
    def __init__(self):
        """Base class of all camera types used in pysg."""

        super().__init__()
        self.__projection_matrix = pyrr.Matrix44()
        self._need_matrix_update = True
Ejemplo n.º 21
0
    def load(self, scene, pipeline, pass_name, cascades_distribution_exponent):
        #TODO: Automatic distribution exponent based on FOV
        #TODO: Configurable cascades number ???

        scene = copy.copy(scene)
        real_scene_camera = scene.camera
        scene.camera = copy.deepcopy(scene.camera)
        self.shadowmaps.load(scene)
        UBOS = {
            'COMMON_UNIFORMS' : self.common_buffer
        }
        spot_count = 0
        sun_count = 0
        point_count = 0

        for i, light in enumerate(scene.lights):
            self.data.lights[i].color = light.color
            self.data.lights[i].type = light.type
            self.data.lights[i].position = light.position
            self.data.lights[i].radius = light.radius
            self.data.lights[i].direction = light.direction
            self.data.lights[i].spot_angle = light.spot_angle
            self.data.lights[i].spot_blend = light.spot_blend

            if light.type == LIGHT_SPOT:
                self.data.lights[i].type_index = spot_count

                camera_matrix = pyrr.Matrix44(light.matrix)
                
                projection_matrix = make_projection_matrix(light.spot_angle,1,0.01,light.radius)
                spot_matrix = projection_matrix * camera_matrix
                
                self.data.spot_matrices[spot_count] = tuple([e for vector in spot_matrix for e in vector])

                scene.camera.camera_matrix = light.matrix
                scene.camera.projection_matrix = tuple([e for vector in projection_matrix for e in vector])
                
                offset = pipeline.get_samples()[pipeline.sample_count]
                self.common_buffer.load(scene, (spot_resolution, spot_resolution), offset, pipeline.sample_count)

                self.shadowmaps.spot_fbos[spot_count].clear(depth=1)
                pipeline.draw_scene_pass(self.shadowmaps.spot_fbos[spot_count], 
                    scene.objects, pass_name, pipeline.default_shader[pass_name], UBOS)

                spot_count+=1
            
            if light.type == LIGHT_SUN:
                self.data.lights[i].type_index = sun_count

                sun_matrix = pyrr.Matrix44(light.matrix)
                projection_matrix = pyrr.Matrix44(real_scene_camera.projection_matrix)
                view_matrix = projection_matrix * pyrr.Matrix44(real_scene_camera.camera_matrix)

                cascades_matrices = get_sun_cascades(sun_matrix, projection_matrix, view_matrix, sun_cascades, cascades_distribution_exponent)
                
                for i, cascade in enumerate(cascades_matrices):
                    cascade = tuple([e for vector in cascade for e in vector])
                    
                    scene.camera.camera_matrix = cascade
                    scene.camera.projection_matrix = tuple([e for vector in pyrr.Matrix44.identity() for e in vector])

                    self.data.sun_matrices[sun_count * sun_cascades + i] = cascade
                
                    offset = pipeline.get_samples()[pipeline.sample_count]
                    self.common_buffer.load(scene, (sun_resolution, sun_resolution), offset, pipeline.sample_count)

                    fbo = self.shadowmaps.sun_fbos[sun_count * sun_cascades + i]
                    fbo.clear(depth=1)
                    glEnable(GL_DEPTH_CLAMP)
                    pipeline.draw_scene_pass(fbo, scene.objects, pass_name, pipeline.default_shader[pass_name], UBOS)
                    glDisable(GL_DEPTH_CLAMP)

                sun_count+=1
            
            
        self.data.lights_count = len(scene.lights)
        
        self.UBO.load_data(self.data)
Ejemplo n.º 22
0
class Matrix44(FunctionLibraryBase):
    '''doc string for Matrix44'''
    def __init__(self):
        super(Matrix44, self).__init__()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    nodeType=NodeTypes.Pure,
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': []
                    })
    def m44Zero():
        '''zero matrix44'''
        return pyrr.Matrix44()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.String, str(pyrr.Matrix44())),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': []
                    })
    def m44ToStr(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''M44 to string.'''
        return str(m)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44.identity()),
                    nodeType=NodeTypes.Pure,
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': []
                    })
    def m44Ident():
        '''Identity matrix44.'''
        return pyrr.Matrix44.identity()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44ApplyToV3(m=(DataTypes.Matrix44, pyrr.Matrix44()),
                     v=(DataTypes.FloatVector3, pyrr.Vector3())):
        '''Apply a matrix to a vector.\nThe matrix rotation and translation are applied to the vector. '''
        return pyrr.Vector3(pyrr.matrix44.apply_to_vector(m, v))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44FromAxisAngle(axis=(DataTypes.FloatVector3, pyrr.Vector3()),
                         theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix from the specified theta rotation around an axis.\ntheta in radians.'''
        return pyrr.Matrix44(
            pyrr.matrix44.create_from_axis_rotation(axis, theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44FromX(theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix with the specified rotation about the X axis.\ntheta in radians.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_x_rotation(theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44FromY(theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix with the specified rotation about the Y axis.\ntheta in radians.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_y_rotation(theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44FromZ(theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix with the specified rotation about the Z axis.\ntheta in radians.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_z_rotation(theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44FromEulers(eulers=(DataTypes.FloatVector3, pyrr.Vector3())):
        '''Creates a matrix from the specified Euler rotations.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_eulers(eulers))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44FromInvOfQuat(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Creates a matrix with the inverse rotation of a quaternion.\nReturns a matrix with shape (4,4) that respresents the inverse of the quaternion.'''
        return pyrr.Matrix44(
            pyrr.matrix44.create_from_inverse_of_quaternion(q))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44From33(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Creates a Matrix44 from a Matrix33.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_matrix33(m))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44', 'quat']
                    })
    def m44FromQuat(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Creates matrix44 from given quaternion.'''
        return pyrr.Matrix44(q)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44FromScale(s=(DataTypes.FloatVector3, pyrr.Vector3([1, 1, 1]))):
        '''Creates an identity matrix with the scale set.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_scale(s))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44FromTransV3(t=(DataTypes.FloatVector3, pyrr.Vector3())):
        '''Creates an identity matrix with the translation set.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_translation(t))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44FromTransV4(t=(DataTypes.FloatVector4, pyrr.Vector4())):
        '''Creates an identity matrix with the translation set.'''
        return pyrr.Matrix44(pyrr.matrix44.create_from_translation(t))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44LookAtCreate(eye=(DataTypes.FloatVector3, pyrr.Vector3()),
                        target=(DataTypes.FloatVector3, pyrr.Vector3()),
                        up=(DataTypes.FloatVector3, pyrr.Vector3())):
        '''Creates a look at matrix according to OpenGL standards.\nReturns a look at matrix that can be used as a viewMatrix.'''
        return pyrr.Matrix44(pyrr.matrix44.create_look_at(eye, target, up))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m33ViewCreate(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns a view into the matrix in Matrix33 format.\nThis is different from m33From44, in that changes to the returned matrix will also alter the original matrix.'''
        return pyrr.Matrix44(pyrr.matrix44.create_matrix33_view(m))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44OrthoProj(left=(DataTypes.Float, -5.0),
                     right=(DataTypes.Float, 5.0),
                     bottom=(DataTypes.Float, -5.0),
                     top=(DataTypes.Float, 5.0),
                     near=(DataTypes.Float, 0.0),
                     far=(DataTypes.Float, 10.0),
                     result=(DataTypes.Reference, (DataTypes.Bool, False))):
        '''Creates an orthogonal projection matrix.\n\nleft (float) - The left of the near plane relative to the planes centre.\n\nright (float) - The right of the near plane relative to the planes centre.\n\ntop (float) - The top of the near plane relative to the planes centre.\n\nbottom (float) - The bottom of the near plane relative to the planes centre.\n\nnear (float) - The distance of the near plane from the cameras origin. It is recommended that the near plane is set to 1.0 or above to avoid rendering issues at close range.\n\nfar (float) - The distance of the far plane from the cameras origin.'''
        try:
            m = pyrr.Matrix44(
                pyrr.matrix44.create_orthogonal_projection(
                    left, right, bottom, top, near, far))
            result(True)
            return m
        except:
            result(False)
            return pyrr.Matrix44.identity()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44PerspProj(fovy=(DataTypes.Float, 0.0),
                     aspect=(DataTypes.Float, 0.0),
                     near=(DataTypes.Float, 0.0),
                     far=(DataTypes.Float, 0.0)):
        '''Creates perspective projection matrix.\n\nfovy (float) - field of view in y direction in degrees\n\naspect (float) - aspect ratio of the view (width / height)\n\nnear (float) - distance from the viewer to the near clipping plane (only positive)\n\nfar (float) - distance from the viewer to the far clipping plane (only positive).'''
        try:
            m = pyrr.Matrix44(
                pyrr.matrix44.create_perspective_projection(
                    fovy, aspect, near, far))
            result(True)
            return m
        except:
            result(False)
            return pyrr.Matrix44.identity()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44PerspProjBounds(left=(DataTypes.Float, -5.0),
                           right=(DataTypes.Float, 5.0),
                           bottom=(DataTypes.Float, -5.0),
                           top=(DataTypes.Float, 5.0),
                           near=(DataTypes.Float, 0.0),
                           far=(DataTypes.Float, 10.0),
                           result=(DataTypes.Reference, (DataTypes.Bool,
                                                         False))):
        '''Creates a perspective projection matrix using the specified near plane dimensions.\n\nleft (float) - The left of the near plane relative to the planes centre.\n\nright (float) - The right of the near plane relative to the planes centre.\n\ntop (float) - The top of the near plane relative to the planes centre.\n\nbottom (float) - The bottom of the near plane relative to the planes centre.\n\nnear (float) - The distance of the near plane from the cameras origin. It is recommended that the near plane is set to 1.0 or above to avoid rendering issues at close range.\n\nfar (float) - The distance of the far plane from the cameras origin.'''
        try:
            m = pyrr.Matrix44(
                pyrr.matrix44.create_perspective_projection_from_bounds(
                    left, right, bottom, top, near, far))
            result(True)
            return m
        except:
            result(False)
            return pyrr.Matrix44.identity()

    @staticmethod
    @IMPLEMENT_NODE(returns=None,
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44Decompose(m=(DataTypes.Matrix44, pyrr.Matrix44()),
                     t=(DataTypes.Reference, (DataTypes.FloatVector3,
                                              pyrr.Vector3())),
                     r=(DataTypes.Reference, (DataTypes.Quaternion,
                                              pyrr.Quaternion())),
                     s=(DataTypes.Reference, (DataTypes.FloatVector3,
                                              pyrr.Vector3()))):
        '''Decomposes an affine transformation matrix into its scale, rotation and translation components.'''
        _s, _r, _t = pyrr.matrix44.decompose(m)
        t(pyrr.Vector3(_t))
        r(pyrr.Quaternion(_r))
        s(pyrr.Vector3(_s))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['create', 'matrix44']
                    })
    def m44Inverse(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns the inverse of the matrix.\nThis is essentially a wrapper around numpy.linalg.inv.'''
        return ~m

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44c1(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns first column of matrix.'''
        return pyrr.Vector4(m.c1.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44c2(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns second column of matrix.'''
        return pyrr.Vector4(m.c2.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44c3(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns third column of matrix.'''
        return pyrr.Vector4(m.c3.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44c4(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns fourth column of matrix.'''
        return pyrr.Vector4(m.c4.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44r1(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns first row of matrix.'''
        return pyrr.Vector4(m.r1.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44r2(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns second row of matrix.'''
        return pyrr.Vector4(m.r2.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44r3(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns third row of matrix.'''
        return pyrr.Vector4(m.r3.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector4, pyrr.Vector4()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44r4(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns fourth row of matrix.'''
        return pyrr.Vector4(m.r4.tolist())

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, 0.0),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44GetComp(m=(DataTypes.Matrix44, pyrr.Matrix44()),
                   r=(DataTypes.Int, 1),
                   c=(DataTypes.Int, 1)):
        '''Returns single scalar from matrix44. r and c taken as abs and clamped in range 1-4.'''
        _r = clamp(abs(r), 1, 4)
        _c = clamp(abs(c), 1, 4)
        name = 'm{0}{1}'.format(_r, _c)
        return getattr(m, name)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()),
                    meta={
                        'Category': 'Math|Matrix44',
                        'Keywords': ['matrix44']
                    })
    def m44quat(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Returns a Quaternion representing this matrix.'''
        return m.quaternion
Ejemplo n.º 23
0
 def m44ApplyToV3(m=(DataTypes.Matrix44, pyrr.Matrix44()),
                  v=(DataTypes.FloatVector3, pyrr.Vector3())):
     '''Apply a matrix to a vector.\nThe matrix rotation and translation are applied to the vector. '''
     return pyrr.Vector3(pyrr.matrix44.apply_to_vector(m, v))
Ejemplo n.º 24
0
 def m44FromAxisAngle(axis=(DataTypes.FloatVector3, pyrr.Vector3()),
                      theta=(DataTypes.Float, 0.0)):
     '''Creates a matrix from the specified theta rotation around an axis.\ntheta in radians.'''
     return pyrr.Matrix44(
         pyrr.matrix44.create_from_axis_rotation(axis, theta))
Ejemplo n.º 25
0
    def load(self,
             scene,
             pipeline,
             pass_name,
             cascades_distribution_exponent,
             spot_resolution=2048,
             sun_resolution=2048,
             point_resolution=512):
        #TODO: Automatic distribution exponent based on FOV

        scene = copy.copy(scene)
        real_scene_camera = scene.camera
        scene.camera = copy.deepcopy(scene.camera)
        self.shadowmaps.load(scene, spot_resolution, sun_resolution,
                             point_resolution)
        UBOS = {'COMMON_UNIFORMS': self.common_buffer}
        spot_count = 0
        sun_count = 0
        point_count = 0

        for i, light in enumerate(scene.lights):
            self.data.lights[i].color = light.color
            self.data.lights[i].type = light.type
            self.data.lights[i].position = light.position
            self.data.lights[i].radius = light.radius
            self.data.lights[i].direction = light.direction
            self.data.lights[i].spot_angle = light.spot_angle
            self.data.lights[i].spot_blend = light.spot_blend

            if light.type == LIGHT_SPOT:
                self.data.lights[i].type_index = spot_count

                camera_matrix = pyrr.Matrix44(light.matrix)

                projection_matrix = make_projection_matrix(
                    light.spot_angle, 1, 0.01, light.radius)
                spot_matrix = projection_matrix * camera_matrix

                self.data.spot_matrices[spot_count] = tuple(
                    [e for vector in spot_matrix for e in vector])

                scene.camera.camera_matrix = light.matrix
                scene.camera.projection_matrix = tuple(
                    [e for vector in projection_matrix for e in vector])

                offset = pipeline.get_samples()[pipeline.sample_count]
                spot_resolution = self.shadowmaps.spot_resolution
                self.common_buffer.load(scene,
                                        (spot_resolution, spot_resolution),
                                        offset, pipeline.sample_count)

                self.shadowmaps.spot_fbos[spot_count].clear(depth=1)
                pipeline.draw_scene_pass(self.shadowmaps.spot_fbos[spot_count],
                                         scene.objects, pass_name,
                                         pipeline.default_shader[pass_name],
                                         UBOS)

                spot_count += 1

            if light.type == LIGHT_SUN:
                self.data.lights[i].type_index = sun_count

                sun_matrix = pyrr.Matrix44(light.matrix)
                projection_matrix = pyrr.Matrix44(
                    real_scene_camera.projection_matrix)
                view_matrix = projection_matrix * pyrr.Matrix44(
                    real_scene_camera.camera_matrix)

                sun_cascades = self.shadowmaps.sun_cascades
                sun_resolution = self.shadowmaps.sun_resolution
                cascades_matrices = get_sun_cascades(
                    sun_matrix, projection_matrix, view_matrix, sun_cascades,
                    cascades_distribution_exponent)

                for i, cascade in enumerate(cascades_matrices):
                    cascade = tuple([e for vector in cascade for e in vector])

                    scene.camera.camera_matrix = cascade
                    scene.camera.projection_matrix = tuple([
                        e for vector in pyrr.Matrix44.identity()
                        for e in vector
                    ])

                    self.data.sun_matrices[sun_count * sun_cascades +
                                           i] = cascade

                    offset = pipeline.get_samples()[pipeline.sample_count]
                    self.common_buffer.load(scene,
                                            (sun_resolution, sun_resolution),
                                            offset, pipeline.sample_count)

                    fbo = self.shadowmaps.sun_fbos[sun_count * sun_cascades +
                                                   i]
                    fbo.clear(depth=1)
                    glEnable(GL_DEPTH_CLAMP)
                    pipeline.draw_scene_pass(
                        fbo, scene.objects, pass_name,
                        pipeline.default_shader[pass_name], UBOS)
                    glDisable(GL_DEPTH_CLAMP)

                sun_count += 1

            if light.type == LIGHT_POINT:
                self.data.lights[i].type_index = point_count

                cube_map_axes = [((1, 0, 0), (0, -1, 0)),
                                 ((-1, 0, 0), (0, -1, 0)),
                                 ((0, 1, 0), (0, 0, 1)),
                                 ((0, -1, 0), (0, 0, -1)),
                                 ((0, 0, 1), (0, -1, 0)),
                                 ((0, 0, -1), (0, -1, 0))]
                matrices = []
                for axes in cube_map_axes:
                    position = pyrr.Vector3(light.position)
                    front = pyrr.Vector3(axes[0])
                    up = pyrr.Vector3(axes[1])
                    matrices.append(
                        pyrr.Matrix44.look_at(position, position + front, up))

                projection_matrix = make_projection_matrix(
                    math.pi / 2.0, 1.0, 0.01, light.radius)

                for i in range(6):
                    scene.camera.camera_matrix = tuple(
                        [e for vector in matrices[i] for e in vector])
                    scene.camera.projection_matrix = tuple(
                        [e for vector in projection_matrix for e in vector])

                    offset = pipeline.get_samples()[pipeline.sample_count]
                    offset = (0, 0)
                    point_resolution = self.shadowmaps.point_resolution
                    self.common_buffer.load(
                        scene, (point_resolution, point_resolution), offset,
                        pipeline.sample_count)

                    fbo = self.shadowmaps.point_fbos[point_count * 6 + i]
                    fbo.clear(depth=1)
                    pipeline.draw_scene_pass(
                        fbo, scene.objects, pass_name,
                        pipeline.default_shader[pass_name], UBOS)

                point_count += 1

        self.data.lights_count = len(scene.lights)

        self.UBO.load_data(self.data)
Ejemplo n.º 26
0
 def m44FromZ(theta=(DataTypes.Float, 0.0)):
     '''Creates a matrix with the specified rotation about the Z axis.\ntheta in radians.'''
     return pyrr.Matrix44(pyrr.matrix44.create_from_z_rotation(theta))
Ejemplo n.º 27
0
    glUniform3fv(test_camera_pos_loc, 1, GL_FALSE,
                 pyrr.Vector3(camera.position))

    glBindVertexArray(monkey_VAO)
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID[1])
    glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices))
    glBindVertexArray(0)

    # ============================================================ #
    #                       Draw a Skybox                          #
    # ============================================================ #
    glUseProgram(skybox_shader)
    glDepthFunc(GL_LEQUAL)

    # Pass the matrices to the shader
    view = pyrr.Matrix44(pyrr.Matrix33(camera.get_world_to_view_matrix(
    )))  # Remove any translation component of the view matrix
    glUniformMatrix4fv(skybox_view_loc, 1, GL_FALSE, view)
    glUniformMatrix4fv(skybox_projection_loc, 1, GL_FALSE, projection)

    # skybox cube
    glBindVertexArray(skybox_VAO)
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID[1])
    glDrawArrays(GL_TRIANGLES, 0, 36)
    glBindVertexArray(0)
    glDepthFunc(GL_LESS)

    glfw.swap_buffers(window)

glfw.terminate()
Ejemplo n.º 28
0
 def m33MultM44(m1=(DataTypes.Matrix33, pyrr.Matrix33()),
                m2=(DataTypes.Matrix44, pyrr.Matrix44())):
     '''Multiplies m33 by m44.\nm1 - m33\nm2 - m44.'''
     return m1 * m2
Ejemplo n.º 29
0
 def m33From44(m=(DataTypes.Matrix44, pyrr.Matrix44())):
     '''Creates a Matrix33 from a Matrix44.'''
     return pyrr.Matrix33(pyrr.matrix33.create_from_matrix44(m))
Ejemplo n.º 30
0
class Matrix33(FunctionLibraryBase):
    '''doc string for Matrix33'''
    def __init__(self):
        super(Matrix33, self).__init__()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33']
                    })
    ## Zero matrix33
    def m33Zero():
        '''Zero matrix33.'''
        return pyrr.Matrix33()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.String, str(pyrr.Matrix33())),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Matrix33 to string
    def m33ToStr(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Matrix33 to string.'''
        return str(m)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33.identity()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Identity matrix33
    def m33Ident():
        '''Identity matrix33.'''
        return pyrr.Matrix33.identity()

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns first column of matrix
    def m33c1(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns first column of matrix.'''
        return pyrr.Vector3(m.c1)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns second column of matrix
    def m33c2(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns second column of matrix.'''
        return pyrr.Vector3(m.c2)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns third column of matrix
    def m33c3(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns third column of matrix.'''
        return pyrr.Vector3(m.c3)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns first row of matrix
    def m33r1(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns first row of matrix.'''
        return pyrr.Vector3(m.r1)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns second row of matrix
    def m33r2(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns second row of matrix.'''
        return pyrr.Vector3(m.r2)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns third row of matrix
    def m33r3(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns third row of matrix.'''
        return pyrr.Vector3(m.r3)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Quaternion, pyrr.Quaternion()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns a Quaternion representing this matrix
    def m33quat(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns a Quaternion representing this matrix.'''
        return m.quaternion

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix44, pyrr.Matrix44()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns a Matrix44 representing this matrix
    def m33ToM44(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns a Matrix44 representing this matrix.'''
        return m.matrix44

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Float, 0.0),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    ## Returns single scalar from matrix33. r and c taken as abs and clamped in range 1-3
    #  \param r: matrix row
    #  \param c: matrix column
    def m33GetComp(m=(DataTypes.Matrix33, pyrr.Matrix33()),
                   r=(DataTypes.Int, 1),
                   c=(DataTypes.Int, 1)):
        '''Returns single scalar from matrix33. r and c taken as abs and clamped in range 1-3.'''
        _r = clamp(abs(r), 1, 3)
        _c = clamp(abs(c), 1, 3)
        name = 'm{0}{1}'.format(_r, _c)
        return getattr(m, name)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33', 'quat']
                    })
    ## Creates matrix33 from given quaternion
    def m33FromQuat(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Creates matrix33 from given quaternion.'''
        return pyrr.Matrix33(q)

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33', '*']
                    })
    ## Multiplies two m33 matrices m1 by m2
    def m33MultM33(m1=(DataTypes.Matrix33, pyrr.Matrix33()),
                   m2=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Multiplies two m33 matrices m1 by m2.'''
        return m1 * m2

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33', '*']
                    })
    def m33MultM44(m1=(DataTypes.Matrix33, pyrr.Matrix33()),
                   m2=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Multiplies m33 by m44.\nm1 - m33\nm2 - m44.'''
        return m1 * m2

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.FloatVector3, pyrr.Vector3()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    def m33ApplyToV3(m=(DataTypes.Matrix33, pyrr.Matrix33()),
                     v=(DataTypes.FloatVector3, pyrr.Vector3())):
        '''The matrix rotation are applied to the vector.\nReturns the vectors rotated by the specified matrix.'''
        return pyrr.Vector3(pyrr.matrix33.apply_to_vector(m, v))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    def m33DirectionScale(v=(DataTypes.FloatVector3, pyrr.Vector3()),
                          s=(DataTypes.Float, 0.0)):
        '''Creates a matrix which can apply a directional scaling to a set of vectors.\nAn example usage for this is to flatten a mesh against a single plane.\nReturns the scaling matrix.'''
        return pyrr.Matrix33(pyrr.matrix33.create_direction_scale(v, s))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    def m33FromAxisAngle(axis=(DataTypes.FloatVector3, pyrr.Vector3()),
                         theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix from the specified theta rotation around an axis.\ntheta in radians.'''
        return pyrr.Matrix33(
            pyrr.matrix33.create_from_axis_rotation(axis, theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    def m33FromEulers(eulers=(DataTypes.FloatVector3, pyrr.Vector3())):
        '''Creates a matrix from the specified Euler rotations.'''
        return pyrr.Matrix33(pyrr.matrix33.create_from_eulers(eulers))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['matrix33']
                    })
    def m33FromInvOfQuat(q=(DataTypes.Quaternion, pyrr.Quaternion())):
        '''Creates a matrix with the inverse rotation of a quaternion.\nReturns a matrix with shape (3,3) that respresents the inverse of the quaternion.'''
        return pyrr.Matrix33(
            pyrr.matrix33.create_from_inverse_of_quaternion(q))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33']
                    })
    def m33From44(m=(DataTypes.Matrix44, pyrr.Matrix44())):
        '''Creates a Matrix33 from a Matrix44.'''
        return pyrr.Matrix33(pyrr.matrix33.create_from_matrix44(m))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33']
                    })
    def m33FromScale(s=(DataTypes.FloatVector3, pyrr.Vector3([1, 1, 1]))):
        '''Creates an identity matrix with the scale set.'''
        return pyrr.Matrix33(pyrr.matrix33.create_from_scale(s))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33']
                    })
    def m33FromX(theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix with the specified rotation about the X axis.\ntheta in radians.'''
        return pyrr.Matrix33(pyrr.matrix33.create_from_x_rotation(theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33']
                    })
    def m33FromY(theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix with the specified rotation about the Y axis.\ntheta in radians.'''
        return pyrr.Matrix33(pyrr.matrix33.create_from_y_rotation(theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33']
                    })
    def m33FromZ(theta=(DataTypes.Float, 0.0)):
        '''Creates a matrix with the specified rotation about the Z axis.\ntheta in radians.'''
        return pyrr.Matrix33(pyrr.matrix33.create_from_z_rotation(theta))

    @staticmethod
    @IMPLEMENT_NODE(returns=(DataTypes.Matrix33, pyrr.Matrix33()),
                    meta={
                        'Category': 'Math|Matrix33',
                        'Keywords': ['create', 'matrix33']
                    })
    def m33Inverse(m=(DataTypes.Matrix33, pyrr.Matrix33())):
        '''Returns the inverse of the matrix.\nThis is essentially a wrapper around numpy.linalg.inv.'''
        return m.inverse