示例#1
0
 def __init__(self, font, position, **kwargs):
     """Initialize the game object."""
     GameObject.__init__(self, GameObject.Priority.BACKGROUND.value - 10)
     self.__position = position
     self.__digits = [Label(font, str(i), (0, 0)) for i in range(10)]
     self.__show_highscore = kwargs.get('highscore', False)
     self.restart()
示例#2
0
 def __init__(self, font, text, **kwargs):
     """Initialize the game object."""
     GameObject.__init__(self, GameObject.Priority.BACKGROUND.value - 10)
     self.__blink_state = True
     self.visible = True
     self.__surface, self.__rect = font.render(font, text, **kwargs)
     self.__stamps = []
示例#3
0
 def __init__(self, canvas_size, count=300):
     """Create the starfield stars."""
     GameObject.__init__(self, GameObject.Priority.BACKGROUND)
     self.__width, self.__height = canvas_size
     self.__stars = [
         self.__create_star(randrange(0, self.__width - 1))
         for star in range(count)
     ]
示例#4
0
 def __init__(self, pos, scale=1, **kw):
     """Initialize the game object."""
     Collider.__init__(self, kw.get('shape', Collider.ELLIPSE))
     Controllable.__init__(self, ConstantController(-1, 0))
     Movable.__init__(self, pos)
     GameObject.__init__(self, GameObject.Priority.BOSS)
     self.__sprite = Sprite('media/images/asteroid.png',
                            scale=scale, rotate=0)
示例#5
0
    def test_find_first_of_type(self):
        scene = Scene(None)
        first = GameObject(components.Camera())
        second = GameObject(components.Camera())
        scene.add_object(first)
        scene.add_object(second)
        scene.setup_frame(1.0)

        tested_component = first.get_component(components.Camera)
        self.assertIs(scene.get_object_of_type(components.Camera), tested_component)
示例#6
0
 def __init__(self, creator, color, origin, target, size=8):
     """Initialize the object."""
     Collider.__init__(self, Collider.LINE)
     Controllable.__init__(self, self.__controller(origin, target, size))
     Movable.__init__(self, origin)
     Hideable.__init__(self)
     GameObject.__init__(self, GameObject.Priority.PROJECTILE)
     self.__creator = type(creator)
     self.__color = color
     self.__next = None
示例#7
0
 def __init__(self, position, type=SMALL, **kwargs):
     """Initialize the object."""
     Hideable.__init__(self)
     GameObject.__init__(self, GameObject.Priority.DEFAULT)
     ts = kwargs.get('time_scale', 1.0)
     self.__sprite = Sprite(type, animate=True, time_scale=ts, loop=True)
     self.__ttl = self.__sprite.duration + pygame.time.get_ticks()
     _, _, w, h, *_ = list(map(lambda i: i // 2, self.__sprite.bounds))
     x, y = position
     self.__position = (x - w, y - h)
     self.should_collide = False
示例#8
0
 def __init__(self, creator, color, origin, direction, **kwargs):
     """Initialize the object."""
     Collider.__init__(self, Collider.LINE)
     Controllable.__init__(self, direction)
     Movable.__init__(self, origin)
     Hideable.__init__(self)
     GameObject.__init__(self, GameObject.Priority.PROJECTILE)
     self.__size = kwargs.get("size", 8)
     self.__creator = type(creator)
     self.__color = color
     self.__next = None
     self.__ignore_colision = tuple(kwargs.get('ignore_colision', ()))
示例#9
0
 def __init__(self, canvas, image, **kw):
     """Initialize Enemy object."""
     Controllable.__init__(self,
                           kw.get('controller', ConstantController(-1, 0)))
     Collider.__init__(self, kw.get('bounding_shape', Collider.RECT))
     Movable.__init__(
         self,
         kw.get('position', (canvas[0] + 10, randint(50, canvas[1] - 50))))
     GameObject.__init__(self, kw.get('priority', GameObject.Priority.NPC))
     self.__sprite = Sprite(image, **kw)
     x, y, *_ = self.__sprite.bounds
     self.move(x, y)
示例#10
0
 def __init__(self, position, speed=5, controller=ConstantController(0, 0)):
     """Initialize the object."""
     Collider.__init__(self, Collider.RECT)
     Controllable.__init__(self, controller)
     Movable.__init__(self, position)
     Killable.__init__(self, Explosion.BIG)
     GameObject.__init__(self, GameObject.Priority.PLAYER)
     self.__original_position = position
     self.__sprite = Sprite('media/images/f18.png')
     self.__lives = 3
     self.__points = 0
     self.__speed = speed
     self.__move = (0, 0)
示例#11
0
 def __init__(self, canvas, image, **kw):
     """Initialize Enemy object."""
     Controllable.__init__(self,
                           kw.get('controller',
                                  ConstantController(-1, 0)))
     Collider.__init__(self, kw.get('shape', Collider.RECT))
     Movable.__init__(self, kw.get('position', (canvas[0] + 10,
                                   randint(50, canvas[1] - 50))))
     Killable.__init__(self, Explosion.SMALL, time_scale=0.5)
     GameObject.__init__(self, GameObject.Priority.NPC)
     self. __sprite = Sprite(image,
                             animate=kw.get('animate', False),
                             cast_shadow=kw.get('cast_shadow', True))
示例#12
0
    def init(self, width, height):
        super(self.__class__, self).init(width, height)
        self.scene = Scene(self)

        map_obj = GameObject()
        self.scene.add_object(map_obj)
        map_obj.add_components(engine.components.Transform(),
                               engine.components.TiledMap(map_path="assets/levels/level01.tmx"))

        self.scene.camera = GameObject()
        self.scene.add_object(self.scene.camera)
        self.scene.camera.add_components(engine.components.Transform(), engine.components.Camera())

        self._create_interface()

        Input.bindings["left"] = pygame.K_a
        Input.bindings["right"] = pygame.K_d
        Input.bindings["jump"] = pygame.K_SPACE
示例#13
0
    def fill_scene_with_objects(self):
        """
        Fills this object's scene with objects as described by tiled_map
        """
        from engine import GameObject

        tiled_map = self.map
        scene = self.game_object.scene
        for group in tiled_map.visible_object_groups:
            for obj in tiled_map.layers[group]:
                game_object = GameObject()
                translation = Vector2(0, 0)
                if obj.image is not None:
                    translation.x = obj.image.get_width()/2
                    translation.y = obj.image.get_height()/2

                obj_position = Vector2(obj.x, obj.y) + translation
                game_object.add_components(Transform(position=obj_position))
                game_object.name = obj.name
                if obj.image is not None:
                    animation_data = obj.properties.get("animation_data", None)
                    game_object.add_components(SpriteRenderer(image=obj.image, animation_data=animation_data))

                if "components" in obj.properties:
                    self._resolve_components(obj.properties["components"].split(";"), game_object)

                scene.add_object(game_object)
示例#14
0
    def update(self, delta_time):
        #get movement input direction
        mov_dir = vector3()
        if (Input.get_key(pygame.K_d)):
            mov_dir.x += 1
        if (Input.get_key(pygame.K_a)):
            mov_dir.x -= 1
        if (Input.get_key(pygame.K_w)):
            mov_dir.z += 1
        if (Input.get_key(pygame.K_s)):
            mov_dir.z -= 1

        #apply object rotation to direction vector, normalize, scale and apply movement
        mov_dir = vector3.from_np3(
            rotate_vectors(self.transform.rotation, mov_dir.to_np3()))
        mov_dir.normalize()
        self.transform.position += mov_dir * delta_time * 1.5

        #get rotation input
        rot_dir = vector3()
        if (Input.get_key(pygame.K_RIGHT)):
            rot_dir.z -= 1
        if (Input.get_key(pygame.K_LEFT)):
            rot_dir.z += 1
        if (Input.get_key(pygame.K_UP)):
            rot_dir.x += 1
        if (Input.get_key(pygame.K_DOWN)):
            rot_dir.x -= 1

        # scale rotation, get a quaternion of it and apply it
        rot_dir *= delta_time * 1.5
        rot_dir = from_rotation_vector(rot_dir.to_np3())
        self.transform.rotation *= rot_dir

        #shoot a bullet
        if (Input.get_key_down(pygame.K_p)):
            bullet = GameObject("bullet")
            bullet.transform.position = self.transform.position
            bullet.transform.rotation = self.transform.rotation
            bullet.add_component(Bullet)
示例#15
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
示例#16
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)
示例#17
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))
示例#18
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, )