コード例 #1
0
ファイル: Collider.py プロジェクト: Elgirhath/Game-engine
    def __init__(self,
                 parent,
                 center,
                 size_tuple,
                 rotation=Quaternion(1, (0, 0, 0))):
        self.parent = parent
        self.center = center
        self.size = size_tuple
        self.rotation = rotation

        self.normals = [(1, 0, 0), (0, -1, 0), (0, 0, 1), (-1, 0, 0),
                        (0, 1, 0), (0, 0, -1)]
        self.points = [(self.size[0], self.size[1], self.size[2]),
                       (self.size[0], self.size[1], -self.size[2]),
                       (self.size[0], -self.size[1], self.size[2]),
                       (self.size[0], -self.size[1], -self.size[2]),
                       (-self.size[0], self.size[1], self.size[2]),
                       (-self.size[0], self.size[1], -self.size[2]),
                       (-self.size[0], -self.size[1], self.size[2]),
                       (-self.size[0], -self.size[1], -self.size[2])]

        self.faces = [
            Mesh.Face((self.points[0], self.points[1], self.points[2],
                       self.points[3])),
            Mesh.Face((self.points[4], self.points[5], self.points[6],
                       self.points[7])),
            Mesh.Face((self.points[0], self.points[1], self.points[4],
                       self.points[5])),
            Mesh.Face((self.points[2], self.points[3], self.points[6],
                       self.points[7])),
            Mesh.Face((self.points[0], self.points[2], self.points[4],
                       self.points[6])),
            Mesh.Face((self.points[1], self.points[3], self.points[5],
                       self.points[7])),
        ]
コード例 #2
0
    def _setup_assets(self):
        scene = self.scene

        # Images
        helmet_f = KTXFile.open("damaged_helmet.ktx")
        helmet_f = helmet_f.slice_array(slice(2,
                                              3))  # Only keep the normal maps
        helmet_f = helmet_f[1:2]  # Only keep the first mipmap
        helmet_f.cast_single(
        )  # Interpret the image as a single texture (not an array)
        helmet_maps = Image.from_ktx(helmet_f, name="HelmetTextureMaps")

        # Sampler
        helmet_sampler = Sampler.from_params(
            max_lod=helmet_maps.mipmaps_levels)

        # Shaders
        shader_normals_map = {
            "POSITION": "pos",
            "NORMAL": "normal",
            "TANGENT": "tangent",
            "TEXCOORD_0": "uv"
        }
        shader2_normals_map = {
            "POSITION": "pos",
            "NORMAL": "normal",
            "TEXCOORD_0": "uv"
        }

        shader_normals = Shader.from_files(
            f"debug_normals/debug_normals.vert.spv",
            f"debug_normals/debug_normals.frag.spv",
            f"debug_normals/debug_normals.map.json",
            name="DebugNormals")

        shader2_normals = Shader.from_files(
            f"debug_normals2/debug_normals2.vert.spv",
            f"debug_normals2/debug_normals2.frag.spv",
            f"debug_normals2/debug_normals2.map.json",
            name="DebugNormalsNoTangent")

        shader_normals.uniforms.debug = {"debug1": (0, 1, 0, 0)}
        shader2_normals.uniforms.debug = {"debug1": (0, 1, 0, 0)}

        # Meshes
        helmet_m = Mesh.from_gltf(GLBFile.open("damaged_helmet.glb"),
                                  "HelmetMesh",
                                  attributes_map=shader_normals_map,
                                  name="HelmetMesh")
        helmet_m2 = Mesh.from_gltf(GLTFFile.open("DamagedHelmet.gltf"),
                                   "HelmetMesh",
                                   attributes_map=shader2_normals_map,
                                   name="HelmetMesh2")

        # Objects
        helmet = GameObject.from_components(shader=shader_normals.id,
                                            mesh=helmet_m.id,
                                            name="Helmet")
        helmet.model = Mat4.from_rotation(radians(360),
                                          (0, 1, 0)).translate(-1, 0, 0)
        helmet.uniforms.normal_maps = CombinedImageSampler(
            image_id=helmet_maps.id,
            view_name="default",
            sampler_id=helmet_sampler.id)

        helmet2 = GameObject.from_components(shader=shader2_normals.id,
                                             mesh=helmet_m2.id,
                                             name="Helmet")
        helmet2.model = Mat4().from_rotation(radians(90),
                                             (1, 0, 0)).translate(1, 0, 0)
        helmet2.uniforms.normal_maps = CombinedImageSampler(
            image_id=helmet_maps.id,
            view_name="default",
            sampler_id=helmet_sampler.id)

        scene.shaders.extend(shader_normals, shader2_normals)
        scene.meshes.extend(helmet_m, helmet_m2)
        scene.images.extend(helmet_maps)
        scene.samplers.extend(helmet_sampler)
        scene.objects.extend(helmet, helmet2)

        self.objects = (
            helmet,
            helmet2,
        )
        self.shaders = (shader_normals, shader2_normals)
コード例 #3
0
    def _setup_assets(self):
        scene = self.scene

        # Images
        helmet_f = KTXFile.open("damaged_helmet.ktx")
        if __debug__:
            helmet_f = helmet_f[
                2:
                3]  # Speed up load time by only keeping a low res mipmap in debug mode

        specular_env_f = KTXFile.open("storm/specular_cubemap.ktx")
        irradiance_env_f = KTXFile.open("storm/irr_cubemap.ktx")

        with (IMAGE_PATH / "brdf.bin").open("rb") as f:
            brdf_args = {
                "format": vk.FORMAT_R16G16_UNORM,
                "extent": (128, 128, 1),
                "default_view_type": vk.IMAGE_VIEW_TYPE_2D
            }
            brdf_f = f.read()

        helmet_i = Image.from_ktx(helmet_f, name="HelmetTextureMaps")
        brdf_i = Image.from_uncompressed(brdf_f, name="BRDF", **brdf_args)
        env_i = Image.from_ktx(specular_env_f, name="CubemapTexture")
        env_irr_i = Image.from_ktx(irradiance_env_f,
                                   name="CubemapIrradianceTexture")

        # Sampler
        brdf_s = Sampler.new()
        env_s = Sampler.from_params(max_lod=env_i.mipmaps_levels)
        helmet_s = Sampler.from_params(max_lod=helmet_i.mipmaps_levels)

        # Shaders
        n = "pbr2/pbr2"
        shader_map = {
            "POSITION": "pos",
            "NORMAL": "normal",
            "TEXCOORD_0": "uv"
        }
        shader = Shader.from_files(f"{n}.vert.spv",
                                   f"{n}.frag.spv",
                                   f"{n}.map.json",
                                   name="PBRShader")

        color_factor = 1.0
        emissive_factor = 1.0
        exposure = 1.5
        gamma = 2.2

        shader.uniforms.render = {
            "light_color": (1.0, 1.0, 1.0),
            "env_lod": (0, env_i.mipmaps_levels),
            "factors": (color_factor, emissive_factor, exposure, gamma)
        }

        shader.uniforms.brdf = CombinedImageSampler(image_id=brdf_i.id,
                                                    view_name="default",
                                                    sampler_id=brdf_s.id)
        shader.uniforms.env_specular = CombinedImageSampler(
            image_id=env_i.id, view_name="default", sampler_id=env_s.id)
        shader.uniforms.env_irradiance = CombinedImageSampler(
            image_id=env_irr_i.id, view_name="default", sampler_id=brdf_s.id)

        # Meshes
        helmet_m = Mesh.from_gltf(GLTFFile.open("DamagedHelmet.gltf"),
                                  "HelmetMesh",
                                  attributes_map=shader_map,
                                  name="HelmetMesh")

        # Objects
        helmet = GameObject.from_components(shader=shader.id,
                                            mesh=helmet_m.id,
                                            name="Helmet")
        helmet.model = Mat4().from_rotation(radians(90), (1, 0, 0))
        helmet.uniforms.texture_maps = CombinedImageSampler(
            image_id=helmet_i.id, view_name="default", sampler_id=helmet_s.id)

        # Packing
        scene.images.extend(helmet_i, brdf_i, env_i, env_irr_i)
        scene.samplers.extend(helmet_s, brdf_s, env_s)
        scene.shaders.extend(shader)
        scene.meshes.extend(helmet_m)
        scene.objects.extend(helmet)

        self.objects = (helmet, )
        self.shaders = (shader, )
コード例 #4
0
    def _setup_assets(self):
        scene = self.scene
        engine = self.engine

        # Images
        w, h = self.heightmap_size
        heightmap_i = Image.empty(
            name = "HeightmapImage",
            extent=(w, h, 1),
            format=vk.FORMAT_R8G8B8A8_SNORM,
            usage=DEFAULT_IMAGE_USAGE | vk.IMAGE_USAGE_STORAGE_BIT,
            default_view_type=vk.IMAGE_VIEW_TYPE_2D,
            layout=ImageLayout.ShaderWrite
        )

        placeholder_i = Image.empty(
            name = "PlaceholderImage",
            extent=(1,1,1),
            format=vk.FORMAT_R8G8B8A8_SNORM,
            default_view_type=vk.IMAGE_VIEW_TYPE_2D
        )

        # Samplers
        heightmap_sm = Sampler.from_params(
            address_mode_V=vk.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
            address_mode_U=vk.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
            mag_filter=vk.FILTER_NEAREST,
            min_filter=vk.FILTER_NEAREST
        )

        # Shaders
        dt = "debug_texture/debug_texture"
        debug_texture_attributes_map = {"POSITION": "pos", "TEXCOORD_0": "uv"}
        debug_texture_s = Shader.from_files(f"{dt}.vert.spv",  f"{dt}.frag.spv", f"{dt}.map.json", name="DebugTexture")

        # Compute shaders
        compute_queue = "render"
        if "compute" in engine.queues:
            compute_queue = "compute"

        ch = "compute_heightmap/compute_heightmap"
        local_x, local_y = self.compute_local_size
        compute_heightmap_c = Compute.from_file(f"{ch}.comp.spv", f"{ch}.map.json", name="ComputeHeightmap", queue=compute_queue)
        compute_heightmap_c.set_constant("local_size_x", local_x)
        compute_heightmap_c.set_constant("local_size_y", local_y)
        compute_heightmap_c.uniforms.heightmap = CombinedImageSampler(image_id=heightmap_i.id, view_name="default", sampler_id=heightmap_sm.id)

        # Meshes
        plane_m = Mesh.from_prefab(MeshPrefab.Plane, attributes_map=debug_texture_attributes_map, name="PlaneMesh")
        
        # Game objects
        preview_heightmap_o = GameObject.from_components(shader = debug_texture_s.id, mesh = plane_m.id, name = "ObjTexture")
        preview_heightmap_o.model = Mat4()
        preview_heightmap_o.uniforms.color_texture = CombinedImageSampler(image_id=placeholder_i.id, view_name="default", sampler_id=heightmap_sm.id)

        scene.images.extend(heightmap_i, placeholder_i)
        scene.samplers.extend(heightmap_sm)
        scene.shaders.extend(debug_texture_s)
        scene.computes.extend(compute_heightmap_c)
        scene.meshes.extend(plane_m)
        scene.objects.extend(preview_heightmap_o)

        self.objects = (preview_heightmap_o,)
        self.shaders = ()
        self.compute_heightmap = compute_heightmap_c
        self.heightmap_texture = heightmap_i
        self.heightmap_sampler = heightmap_sm
        self.heightmap_preview = preview_heightmap_o
コード例 #5
0
    def _setup_assets(self):
        scene = self.scene

        # Textures
        texture = Image.from_ktx(KTXFile.open("vulkan_logo.ktx"), name="Texture")
        array_texture = Image.from_ktx(KTXFile.open("array_test.ktx"), name="ArrayTexture")
        cubemap_texture = Image.from_ktx(KTXFile.open("storm/specular_cubemap.ktx"), name="CubemapTexture")
        
        with (IMAGE_PATH/"brdf.bin").open("rb") as f:
            texture_raw_data = f.read()
            texture_args = {"format": vk.FORMAT_R16G16_UNORM, "extent": (128, 128, 1), "default_view_type": vk.IMAGE_VIEW_TYPE_2D}
            raw_texture = Image.from_uncompressed(texture_raw_data, name="TextureRaw", **texture_args)

        # Samplers
        sampler = Sampler.from_params(
            address_mode_V=vk.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
            address_mode_U=vk.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE
        )

        sampler_lod = Sampler.from_params(
            address_mode_V=vk.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
            address_mode_U=vk.SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
            max_lod=cubemap_texture.mipmaps_levels
        )


        # Shaders
        simple_name = "debug_texture/debug_texture"
        array_name = "debug_texture_array/debug_texture_array"
        cube_name = "debug_texture_cube/debug_texture_cube"
        
        shader_attributes_map = {"POSITION": "pos", "TEXCOORD_0": "uv"}

        shader_simple = Shader.from_files(f"{simple_name}.vert.spv",  f"{simple_name}.frag.spv", f"{simple_name}.map.json", name="DebugTexture")
        shader_array = Shader.from_files(f"{array_name}.vert.spv",  f"{array_name}.frag.spv", f"{array_name}.map.json", name="DebugArrayTexture")
        shader_cube = Shader.from_files(f"{cube_name}.vert.spv",  f"{cube_name}.frag.spv", f"{cube_name}.map.json", name="DebugCubeTexture")

        # Meshes
        plane_m = Mesh.from_prefab(MeshPrefab.Plane, attributes_map=shader_attributes_map, invert_y=True, name="PlaneMesh")
        plane_m2 = Mesh.from_prefab(MeshPrefab.Plane, attributes_map=shader_attributes_map, name="PlaneMesh")
        sphere_m = Mesh.from_gltf(GLBFile.open("test_sphere.glb"), "Sphere.001", attributes_map=shader_attributes_map, name="SphereMesh")

        # Objects
        plane1 = GameObject.from_components(shader = shader_simple.id, mesh = plane_m.id, name = "ObjTexture")
        plane1.model = Mat4()
        plane1.uniforms.color_texture = CombinedImageSampler(image_id=texture.id, view_name="default", sampler_id=sampler.id)

        plane2 = GameObject.from_components(shader = shader_simple.id, mesh = plane_m2.id, name = "ObjRawTexture", hidden=True)
        plane2.model = Mat4()
        plane2.uniforms.color_texture = CombinedImageSampler(image_id=raw_texture.id, view_name="default", sampler_id=sampler.id)

        plane3 = GameObject.from_components(shader = shader_array.id, mesh = plane_m.id, name = "ObjArrayTexture", hidden=True)
        plane3.model = Mat4()
        plane3.uniforms.color_texture = CombinedImageSampler(image_id=array_texture.id, view_name="default", sampler_id=sampler.id)

        sphere = GameObject.from_components(shader = shader_cube.id, mesh = sphere_m.id, name = "ObjCubeTexture", hidden=True)
        sphere.model = Mat4.from_rotation(radians(180), (1, 0, 0))
        sphere.uniforms.cube_texture = CombinedImageSampler(image_id=cubemap_texture.id, view_name="default", sampler_id=sampler_lod.id)
        
        # Add objects to scene
        scene.shaders.extend(shader_simple, shader_array, shader_cube)
        scene.samplers.extend(sampler, sampler_lod)
        scene.images.extend(texture, array_texture, raw_texture, cubemap_texture)
        scene.meshes.extend(plane_m, plane_m2, sphere_m)
        scene.objects.extend(plane1, plane2, plane3, sphere)

        self.cubemap_max_mipmap = cubemap_texture.mipmaps_levels
        self.visible_index = 0
        self.objects.extend((plane1, plane2, plane3, sphere))
コード例 #6
0
def Import_obj(obj_file,
               position,
               rotation=Quaternion(1, (0, 0, 0)),
               scale=(1, 1, 1)):
    path = "models/" + obj_file
    obj_lines = open(path, "r").readlines()
    vertices = []
    edges = []
    normals = []
    faces = []
    for line in obj_lines:
        if line[0] == "v" and line[1] == " ":
            vertex_coords = []
            value = ""
            for sign in line:
                if ord(sign) == 45 or (ord(sign) >= 48
                                       and ord(sign) <= 57) or ord(sign) == 46:
                    value += sign
                if ord(sign) == 32 and len(value) > 0:
                    vertex_coords.append(float(value))
                    value = ""
            vertex_coords.append(float(value))
            vertex = tuple(vertex_coords)
            vertices.append(vertex)

        if line[0] == "v" and line[1] == "n" and line[2] == " ":
            normal_coords = []
            value = ""
            for sign in line:
                if ord(sign) == 45 or (ord(sign) >= 48
                                       and ord(sign) <= 57) or ord(sign) == 46:
                    value += sign
                if ord(sign) == 32 and len(value) > 0:
                    normal_coords.append(float(value))
                    value = ""
            normal_coords.append(float(value))
            normal = tuple(normal_coords)
            normals.append(normal)

        if line[0] == "f" and line[1] == " ":
            vertex_list = []
            value = ""
            slash_passed = False
            for sign in line:
                if ord(sign) == 45 or (ord(sign) >= 48
                                       and ord(sign) <= 57) or ord(sign) == 46:
                    value += sign
                if ord(sign) == 47 and len(value) > 0:
                    if not slash_passed:
                        vertex_list.append(vertices[int(value) - 1])
                    slash_passed = True
                    value = ""
                if ord(sign) == 32 and len(value) > 0:
                    slash_passed = False
                    normal = normals[int(value) - 1]
                    value = ""

            faces.append(Mesh.Face(vertex_list, normal))
            face_edges = []

            if len(vertex_list) == 4:
                face_edges.append(Mesh.Edge(vertex_list[0], vertex_list[1]))
                face_edges.append(Mesh.Edge(vertex_list[1], vertex_list[2]))
                face_edges.append(Mesh.Edge(vertex_list[2], vertex_list[3]))
                face_edges.append(Mesh.Edge(vertex_list[3], vertex_list[0]))
#                print("Only triangles accepted")
            else:
                face_edges.append(Mesh.Edge(vertex_list[0], vertex_list[1]))
                face_edges.append(Mesh.Edge(vertex_list[1], vertex_list[2]))
                face_edges.append(Mesh.Edge(vertex_list[2], vertex_list[0]))

            for face_edge in face_edges:
                already_exists = False
                for edge in edges:
                    if edge.A == face_edge.A and edge.B == face_edge.B:
                        already_exists = True
                        break
                    if edge.A == face_edge.B and edge.B == face_edge.A:
                        already_exists = True
                        break

                if not already_exists:
                    edges.append(face_edge)

    mesh = Mesh.Mesh(None, vertices, edges, faces)
    obj = Mesh.Object(position, rotation, scale, mesh)
    name = ""
    for i in range(0, len(obj_file) - 4):
        name += obj_file[i]
    obj.name = name
    return obj
コード例 #7
0
 def awake(self):
     renderer = self.game_object.add_component(MeshRenderer)
     renderer.mesh = Mesh.create_cube((0.1, 0.1, 0.1))
     renderer.material = Material(color(0, 0, 1, 1), "TestMaterial1")
コード例 #8
0
import random
import sys

import pygame

from engine import (Collider, Color, Importer, Input, Mesh, Other, Rigidbody,
                    pyinit)
from engine.Quaternion import Quaternion
from engine.Ray import Ray
from engine.render import text_renderer
from engine.math import vector3, vector2
from engine.render import Screen
from engine.render.camera import camera

player = Mesh.Object((0, 0, 0.9))
cam = camera.Camera((0, 0, 0.9), resolution=(1366, 768))
player.add_camera(cam)
player.collider = Collider.Box_collider(player, (0, 0, 0), (0.1, 0.1, 0.85))

pygame.mixer.pre_init(44100, -16, 1, 512)
pyinit.init(camera.main_camera.resolution, "The game", "window")
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
game_exit = False
"""**********************************************************************************
**********************************************************************************
***********************************MAIN*******************************************
**********************************************************************************
**********************************************************************************"""

walk_speed = 1.5
コード例 #9
0
ファイル: 3Dsoft.py プロジェクト: wsantos/pyvoxel
def main():
    window = pyglet.window.Window()

    device = Device()

    mesh = Mesh("Cube", 8)
    mesh.vertices[0] = Vector3(-1, 1, 1)
    mesh.vertices[1] = Vector3(1, 1, 1)
    mesh.vertices[2] = Vector3(-1, -1, 1)
    mesh.vertices[3] = Vector3(-1, -1, -1)
    mesh.vertices[4] = Vector3(-1, 1, -1)
    mesh.vertices[5] = Vector3(1, 1, -1)
    mesh.vertices[6] = Vector3(1, -1, 1)
    mesh.vertices[7] = Vector3(1, -1, -1)

    mesh2 = Mesh("Quad", 4)
    mesh2.vertices[0] = Vector3(-1, 1, 1)
    mesh2.vertices[1] = Vector3(1, 1, 1)
    mesh2.vertices[2] = Vector3(-1, -1, 1)
    mesh2.vertices[3] = Vector3(1, -1, 1)

    cp = Vector3(0.0,0.0,10.0)
    ct = Vector3(0,0,0)

    #GUI
    variable = partial(glydget.Variable, namespace=locals())
    device_gui = glydget.Group('Camera Position', 
        [variable('cp.x', label=u'x',
                  vmin=-10, vmax=10, vstep=0.1),
         variable('cp.y', label=u'y',
                  vmin=-10,  vmax=10, vstep=0.1),
         variable('cp.z', label=u'z',
                  vmin=-10, vmax=10, vstep=0.1)])

    dialog = glydget.Window ("Controls",
                             [device_gui,
                              glydget.Button(u'Quit', quit)])

    dialog.show()
    dialog.move(5, window.height-5)
    window.push_handlers(dialog)
    fps_display = pyglet.clock.ClockDisplay()

    #render loop
    @window.event
    def on_draw():

        
        #device.z_cam += 0.01
        #mesh.rotation.x += 0.01
        #mesh.rotation.y += 0.01
        #mesh.rotation.z += 0.01
        view_matrix = Matrix.look_at(cp, ct, Vector3.unit_y())
        projection_matrix = Matrix.projection()
        #world_matrix = Matrix.identity()#chamar funcao yaw aqui que recebe o vetor rotation
        world_matrix = Matrix.pyr(mesh.rotation)
        #tm = world_matrix * view_matrix * projection_matrix
        tm = projection_matrix * view_matrix * world_matrix


        start = timeit.default_timer()
        window.clear()
        device.clear()
        #device.rot += 10.1
        #world_matrix.data[2][2] = device.rot
        #print "rot",device.rot
        print "Begin mesh draw -----------------------------------------------"
        for index, vertice in enumerate(mesh.vertices):
            vertice_tmp = vertice.transform_coordinate(tm)
            print vertice_tmp
            x = vertice_tmp.x * 640 + 640/2.0
            y = -vertice_tmp.y * 480 + 480 /2.0
            print "Vertex %s: %s,%s,%s" % (index, x, y, vertice_tmp.z)

            color = None
            if vertice_tmp.z > 0:
                color = (255,0,0,0)
            else:
                color = (0,255,0,0)

            device.put_pixel(int(x),int(y), *color)
        print "End mesh draw -----------------------------------------------"

        #device.put_pixel(5,5,5,255,0,0)
        device.present()
        dialog.batch.draw()
        fps_display.draw()

        #pxbuf.blit(0, 0)

        stop = timeit.default_timer()
        time = stop - start
        if time > 0.016:
            print "Drop"


    def update(dt):
        pass

    pyglet.clock.schedule_interval(update, 0.0001)


    pyglet.app.run()