示例#1
0
    def build_flat_plane(self):
        scene = Scene(self.screen, self.camera_position, COLOUR_WHITE, self.scale)

        count = 1
        for x in range(count):
            for y in range(count):
                s = int(self.screen.width / count)
                cube_material = Material(
                    (0 + int(random.random() * 100), 150 + int(random.random() * 100), int(1 * random.random())),
                    # (0,0,255),
                    (0.5, 0.5, 0.5),
                    (0.8, 0.8, 0.8),
                    (0.5, 0.5, 0.5),
                    50
                )
                rectangle = Rectangle(
                    Point(x * s - self.screen.width/2, -self.screen.height / 2, self.screen.distance + y * s),
                    Point(x * s - self.screen.width/2, -self.screen.height / 2, self.screen.distance + (y+1) * s),
                    Point((x+1) * s - self.screen.width/2, -self.screen.height / 2, self.screen.distance + y * s),
                    cube_material
                )
                scene.add_object(rectangle)

        light_position = Point(-self.screen.width/4,-self.screen.height/2 + 50, self.screen.width * 4 + self.screen.distance)
        light = Light(light_position)
        scene.add_light(light)

        return scene
示例#2
0
	def __init__(self, player, boss):
		self.p1 = player
		self.p2 = boss

		p1_status = Scene(max(len(self.p1.name), self.max_health) + 1, 3)
		p1_status.modify_background(self.p1.name)
		p2_status = Scene(max(len(self.p2.name), self.max_health) + 1, 3)
		p2_status.modify_background(self.p2.name)

		self.p1.health = HealthBar(self.max_health)
		p1_status.add_object(self.p1.health, 0, 2)
		self.p1.status_win = p1_status
		self.p1.thruster = Thruster(self.p1)
		self.p1.thruster.switch_direction()
		self.p1.thruster.set_color(curses.COLOR_CYAN)

		self.p2.health = HealthBar(self.max_health)
		p2_status.add_object(self.p2.health, 0, 2)
		self.p2.status_win = p2_status

		width, height = Scene.max_view(0, 7)
		width *= self.screens
		self.main_win = Scene(width, height)
		self.main_win.modify_background(self.generate_starfield(width, height))
示例#3
0
def prepareScene():
    scene = Scene()

    ring = material.load_object('ring')
    scene.add_object(ring, [1.0, 1.0, 1.0], [1.05, -1.0, 0.0, 0.0],
                     [0.0, 0.0, 0.0])
    cube = material.load_object('cube')
    scene.add_object(cube, [0.5, 0.5, 0.5], [0.0, 1.0, 0.0, 0.0],
                     [0.2, 0.0, 0.6])
    magnet = material.load_object('magnet')
    scene.add_object(magnet, [0.3, 0.3, 0.3], [0.0, 1.0, 0.0, 0.0],
                     [0.0, 0.0, 0.0])

    global tree
    model = scene.to_mesh()
    tree = BspTree.tree(model)

    global camera
    camera = Camera(model)
    camera.adjust_to_model()
    camera.see()
    camera.show_all()
示例#4
0
from scene import Scene
from camera import Camera
from lights import *
from objects import *
from color import Color

width, height = 800, 600

scene = Scene(Camera((0, -80, 20), 60), (80, 60), (width, height))

scene.add_light(Ambiant(intensity=0.2))
scene.add_light(Diffuse(-20, -40, 20, intensity=0.8))
scene.add_light(Diffuse(40, 40, 5, intensity=0.4))
scene.add_light(Specular(-20, -40, 20, intensity=0.6))

scene.add_object(Sphere(10, x=50, y=30, scale_z=1.5, color=Color(r=255)))
scene.add_object(Sphere(3, z=20, scale_x=5, color=Color(g=255)))
scene.add_object(Sphere(5, color=Color(r=255, b=255)).stretch('x', angle_y=60))
scene.add_object(Plane(z=-10, color=Color(255, 255, 255)))
scene.add_object(Plane(z=80, color=Color(255, 255, 255)))
scene.add_object(Plane(x=-80, rot_y=90, color=Color(b=255)))
scene.add_object(Plane(x=80, rot_y=90, color=Color(b=255)))
scene.add_object(Plane(y=100, rot_x=90, color=Color(r=255, g=255)))
scene.add_object(Cylinder(5, x=-80, y=100, color=Color(b=255)))
scene.add_object(Cylinder(5, x=80, y=100, color=Color(b=255)))
scene.add_object(Cone(10, color=Color(r=128, g=128, b=128)))

nb_lines_chunk = 50
dispatch = Dispatcher(61385,
                      set(i for i in range(height) if i % nb_lines_chunk == 0),
                      key_fmt='i')
示例#5
0
white_light = Spotlight(np.array([3., 0., 1.5]), np.array([1., 1., 1.]))
light1 = Spotlight(np.array([-2., -0.6, 1.4]),
                   np.array([random(), random(), random()]))
light2 = Spotlight(np.array([-0.6, 2., 1.4]),
                   np.array([random(), random(), random()]))
light3 = Spotlight(np.array([0.6, -2., 1.4]),
                   np.array([random(), random(), random()]))
light4 = Spotlight(np.array([2., 0.6, 1.4]),
                   np.array([random(), random(), random()]))
#white_light2 = Spotlight(np.array([0.,1.5,0.3]),np.array([1.,1.,1.]))
#white_light3 = Spotlight(np.array([-1.,0.5,0.]),np.array([1.,1.,1.]))
#red_light = Spotlight(np.array([0.,-1.5,1.]), np.array([1.,0.,0.]))
#green_light = Spotlight(np.array([-1.74,0.75,1.]), np.array([0.,1.,0.]))
#blue_light = Spotlight(np.array([1.74,0.75,1.]), np.array([0.,0.,1.]))

this_scene.add_object(sphere1)
this_scene.add_object(sphere2)
this_scene.add_object(sphere3)
this_scene.add_object(small_sphere1)
this_scene.add_object(small_sphere2)
this_scene.add_object(small_sphere3)

this_scene.add_light(white_light)
this_scene.add_light(light1)
this_scene.add_light(light2)
this_scene.add_light(light3)
this_scene.add_light(light4)
#this_scene.add_light(white_light2)
#this_scene.add_light(white_light3)
#this_scene.add_light(red_light)
#this_scene.add_light(green_light)
示例#6
0
from scene import Scene
from sphere import Sphere
from material import Material
from light import Spotlight
from rayon import raytracer_render
from camera import Camera
import numpy as np
import matplotlib.pyplot as plt

this_scene = Scene()
some_material = Material(
    np.array([106., 102., 163.]) / 255, 0.5, 0.7, 0.1, 0.3, 0.4)
red_material = Material(
    np.array([255., 151., 112.]) / 255, 0.8, 0.4, 0.2, 0.4, 0.7)

light1 = Spotlight(np.array([1., 1., 0.]), np.array([252., 236., 201.]) / 255)
#red_light = Spotlight(np.array([-1,2,1]),np.array([1,1,0]))
#other_light = Spotlight(np.array([0,-1,1.5]),np.array([1,0,1]))
blue_sphere = Sphere(np.array([0., 0., 3.]), 0.8, some_material)
red_sphere = Sphere(np.array([0.4, 0.4, 1.8]), 0.1, red_material)

this_scene.add_object(blue_sphere)
this_scene.add_object(red_sphere)
this_scene.add_light(light1)
#this_scene.add_light(red_light)
#this_scene.add_light(other_light)

this_camera = Camera(1500, 1500, 2.2)

plt.imsave('shadow exemple.png', raytracer_render(this_camera, this_scene))
示例#7
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 4)
    scene.camera.rotation = Quaternion.AngleAxis(Vector3(1, 0, 0),
                                                 math.radians(-15))

    # Creates the terrain meshes and materials
    terrain_meshes, terrain_materials = create_terrain()

    # Create container object for all the terrain sub-objects
    master_object = Object3d("TerrainObject")
    master_object.position = Vector3(0, -1, 0)
    scene.add_object(master_object)

    # Create the terrain objects and place it in a scene, at position (0,0,0)
    for _, (mesh, material) in enumerate(zip(terrain_meshes,
                                             terrain_materials)):
        obj = Object3d("TerrainObject")
        obj.scale = Vector3(1, 1, 1)
        obj.position = Vector3(0, 0, 0)
        obj.mesh = mesh
        obj.material = material
        master_object.add_child(obj)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 15
    axis = Vector3(0, 1, 0)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(True)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Rotates the object, considering the time passed (not linked to frame rate)
        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)
        master_object.rotation = q * master_object.rotation

        #Commented code serves to make benchmarks
        Mesh.stat_vertex_count = 0
        Mesh.stat_transform_time = 0
        Mesh.stat_render_time = 0

        scene.render(screen)

        #Writes the benchmarks results
        print("Frame stats:")
        print(f"Vertex count = {Mesh.stat_vertex_count}")
        print(f"Transform time = {Mesh.stat_transform_time}s")
        print(f"Render time = {Mesh.stat_render_time}s")

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()

        print(f"Frame time = {delta_time}s")
示例#8
0

if __name__ == '__main__':
    # Select model to use
    model = Models.wolf02
    model_details = MODEL_DETAILS[model]
    file_path = model_details[FileDetails.FILE_PATH]
    camera_pos = model_details[FileDetails.CAMERA_POS]
    light_source_pos = model_details[FileDetails.LIGHT_SOURCE_POS]
    camera_direction = [0, 0, -1]

    # Create model object
    obj = Object(*read_off_file(file_path).values())
    scene = Scene(camera_pos, camera_direction, light_source_pos,
                  (WIDTH, HEIGHT))
    scene.add_object(obj)
    scene.simulate_model()
    DISPLAY_MATRIX = scene.display_coords

    # Render openGL function
    # main(render)

    # # Display some values
    # print(f"World Coords: {obj.vertices[Coords.WORLD][:3]}")
    # print(f"Camera Coords: {obj.vertices[Coords.CAMERA][:3]}")
    # print("---Face 1---")
    # for i, vertex_index in enumerate(obj.faces[Face.INDICES][0]):
    #     print(
    #         f"Vertex {i+1} World Coords: {obj.vertices[Coords.WORLD][vertex_index]}")
    #     print(
    #         f"Vertex {i+1} Camera Coords: {obj.vertices[Coords.CAMERA][vertex_index]}")
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 640
    res_y = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 4)

    # Create a sphere and place it in a scene, at position (0,0,0)
    '''
    obj1 = Object3d("TestObject")
    obj1.scale = Vector3(1, 1, 1)
    obj1.position = Vector3(0, 0, 0)
    obj1.mesh = Mesh.create_sphere((1, 1, 1), 12, 12)
    obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
    scene.add_object(obj1)
    '''
    # puts name of file that you wanna load
    # if you dont want to load a file leave it as ""
    fileloaded = "teste2.obj"

    #if theres so file to be loaded
    if fileloaded == "":
        # Create a pyramid and place it in a scene, at position (0,0,0)
        obj1 = Object3d("TestObject")
        obj1.scale = Vector3(1, 1, 1)
        obj1.position = Vector3(0, 0, 0)
        obj1.mesh = Mesh.create_pyramid()
        obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
        scene.add_object(obj1)

    else:
        # Create a object chosen by the user and place it in a scene, at position (0,0,0)
        obj1 = Object3d("TestObject")
        obj1.scale = Vector3(1, 1, 1)
        obj1.position = Vector3(0, 0, 0)

        #function to enable objects to be loaded from terminal
        if len(sys.argv) == 2:
            print(True)
            obj1.mesh = Mesh.create_mesh(sys.argv[1])
        #if nothing at the terminal just run normaly with the name of the file in code
        else:
            obj1.mesh = Mesh.create_mesh(fileloaded)
        # add object to viewer
        obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
        scene.add_object(obj1)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 50
    axis = Vector3(1, 0.7, 0.2)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(True)
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            #if your pressing a key
            elif event.type == pygame.KEYDOWN:
                #exit the game
                if event.key == pygame.K_ESCAPE:
                    return
                # rotate object in y axis
                if event.key == pygame.K_LEFT:
                    axis = Vector3(0, 1, 0)
                if event.key == pygame.K_RIGHT:
                    axis = Vector3(0, -1, 0)
                # rotate object in x axis
                if event.key == pygame.K_UP:
                    axis = Vector3(1, 0, 0)
                if event.key == pygame.K_DOWN:
                    axis = Vector3(-1, 0, 0)
                # rotate object in z axis
                if event.key == pygame.K_PAGEUP:
                    axis = Vector3(0, 0, 1)
                if event.key == pygame.K_PAGEDOWN:
                    axis = Vector3(0, 0, -1)
                #normalize axis
                axis.normalize()

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Rotates the object, considering the time passed (not linked to frame rate)
        ax = (axis * math.radians(angle) * delta_time)

        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)

        #Object movement
        keys = pygame.key.get_pressed()
        # movementing object up down right and left
        if keys[pygame.K_LEFT]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_RIGHT]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_UP]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_DOWN]:
            obj1.rotation = q * obj1.rotation

        #functions to make the rotations work
        if keys[pygame.K_PAGEUP]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_PAGEDOWN]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_w]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y + 0.006,
                                    obj1.position.z)
        if keys[pygame.K_s]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y - 0.006,
                                    obj1.position.z)
        if keys[pygame.K_a]:
            obj1.position = Vector3(obj1.position.x - 0.006, obj1.position.y,
                                    obj1.position.z)
        if keys[pygame.K_d]:
            obj1.position = Vector3(obj1.position.x + 0.006, obj1.position.y,
                                    obj1.position.z)
        if keys[pygame.K_q]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y,
                                    obj1.position.z - 0.006)
        if keys[pygame.K_e]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y,
                                    obj1.position.z + 0.006)

        #rendering objects on to screen
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
示例#10
0
def main():
    """Main function, it implements the application loop"""

    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 0)

    # Creates the terrain meshes and materials
    terrain_object = create_terrain()
    scene.add_object(terrain_object)

    # Game variables
    # A missile spawns every 2 seconds (this time gets smaller every missile, to
    # make the game harder with time)
    missile_spawn_time = 2
    # Time until the next missile is shot
    missile_timer = missile_spawn_time
    # Storage for all missiles active in the game
    missiles = []

    # Flashing effect Color
    flash_color = Color(0, 0, 0, 0)
    # Total time of the current flash
    total_flash_time = 0
    # Time elapsed for the current flash
    flash_timer = 0

    # Minimum time between player shots
    shot_cooldown = 0.2
    # Timer for the shot cooldown
    shot_timer = 0
    # Storage for all the shots active in the game
    shots = []

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(True)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                # If ESC is pressed exit the application
                if event.key == pygame.K_ESCAPE:
                    return
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # If the user has the mouse button down
                if shot_timer <= 0:
                    # We're not on cooldown, so we can shoot

                    # Get the mouse position and convert it to NDC (normalized
                    # device coordinates)
                    mouse_pos = pygame.mouse.get_pos()
                    mouse_pos = ((mouse_pos[0] / res_x) * 2 - 1,
                                 (mouse_pos[1] / res_y) * 2 - 1)

                    # Create a shot
                    shot = Shot()
                    # Initialize the position and direction of the shot, based on the
                    # mouse position on the screen. For this, we request the scene camera the
                    # ray corresponding to the mouse position
                    shot.position, shot.direction = scene.camera.ray_from_ndc(
                        mouse_pos)

                    # Add the shot to the scene (for rendering) and on the shot storage, for
                    # all other operations
                    scene.add_object(shot)
                    shots.append(shot)

                    # Reset the cooldown
                    shot_timer = shot_cooldown

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Spawn new missiles
        missile_timer -= delta_time
        if missile_timer < 0:
            # It's time to spawn a new missile
            # Reduce time until the next missile, but clamp it so we don't have more than
            # one missile every half a second
            missile_spawn_time -= 0.025
            if missile_spawn_time < 0.5:
                missile_spawn_time = 0.5
            # Reset the timer
            missile_timer = missile_spawn_time

            # Create a new missile
            new_missile = Missile()
            # Add the missile to the scene (for rendering) and on the missile storage,
            # for all other operations
            scene.add_object(new_missile)
            missiles.append(new_missile)

        # Animate missiles
        # We need the following to keep track of all missiles we'll have to destroy,
        # since we can't change the storage while we're iterating it
        missiles_to_destroy = []
        for missile in missiles:
            # Update the missile
            missile.update(delta_time)

            # Check if the missile is close to the player plane (z < 0.1)
            if missile.position.z < 0.1:
                # Check if the missile is close enough to the player to hit him
                if missile.position.magnitude() < 0.25:
                    # It has hit the player, flash the screen red for one second
                    flash_color = Color(1, 0, 1, 1)
                    total_flash_time = flash_timer = 1
                # Destroy missile (remove it from the scene and add it to the destruction
                # list so we can remove it in a bit)
                missiles_to_destroy.append(missile)
                scene.remove_object(missile)

        # Animate shots
        # We need the following to keep track of all shots we'll have to destroy,
        # since we can't change the storage while we're iterating it
        shots_to_destroy = []
        for shot in shots:
            # Update the shot
            shot.update(delta_time)

            # Check if the shot is too far away, and add it to the destruction list,
            # besides removing it from the scene
            if shot.position.z > 12:
                # Destroy shot
                shots_to_destroy.append(shot)
                scene.remove_object(shot)

        # Update shot cooldown
        shot_timer -= delta_time

        # Check collisions
        for shot in shots:
            # Check each shot with each missile
            for missile in missiles:
                # Check the distance between the shot and the missile, it it is below
                # a threshould (in this case 0.5), destroy the missile and the shot
                distance = Vector3.distance(shot.position, missile.position)
                if distance < 0.5:
                    # Add it to the missile destruction list, and remove it from the scene
                    missiles_to_destroy.append(missile)
                    scene.remove_object(missile)
                    # Add it to the shot destruction list, and remove it from the scene
                    shots_to_destroy.append(shot)
                    scene.remove_object(shot)
                    # Flash the screen cyan for 0.5 seconds
                    flash_color = Color(0, 1, 1, 1)
                    total_flash_time = flash_timer = 0.5

        # Actually delete objects
        missiles = [x for x in missiles if x not in missiles_to_destroy]
        shots = [x for x in shots if x not in shots_to_destroy]

        # Render scene
        scene.render(screen)

        # Render screen flash
        if flash_timer > 0:
            flash_timer -= delta_time
            if flash_timer > 0:
                flash_color.a = flash_timer / total_flash_time
                # Render the full screen rectangle, using additive blend
                screen.fill(flash_color.premult_alpha().tuple3(), None,
                            pygame.BLEND_RGB_ADD)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
示例#11
0
class Game:
	max_health = 10
	ship_space = 15
	screens = 3

	def __init__(self, player, boss):
		self.p1 = player
		self.p2 = boss

		p1_status = Scene(max(len(self.p1.name), self.max_health) + 1, 3)
		p1_status.modify_background(self.p1.name)
		p2_status = Scene(max(len(self.p2.name), self.max_health) + 1, 3)
		p2_status.modify_background(self.p2.name)

		self.p1.health = HealthBar(self.max_health)
		p1_status.add_object(self.p1.health, 0, 2)
		self.p1.status_win = p1_status
		self.p1.thruster = Thruster(self.p1)
		self.p1.thruster.switch_direction()
		self.p1.thruster.set_color(curses.COLOR_CYAN)

		self.p2.health = HealthBar(self.max_health)
		p2_status.add_object(self.p2.health, 0, 2)
		self.p2.status_win = p2_status

		width, height = Scene.max_view(0, 7)
		width *= self.screens
		self.main_win = Scene(width, height)
		self.main_win.modify_background(self.generate_starfield(width, height))

	def intro(self):
		self.midpoint_x = round(
			self.main_win.width * (self.screens - 0.5)/self.screens
		)
		midpoint_y = self.main_win.height // 2
		outline = Outline(self.p2)
		self.main_win.add_object(
			outline,
			self.midpoint_x + self.ship_space - 1,
			midpoint_y - self.p2.height // 2 - 1
		)
		outline = Outline(self.p1)
		self.main_win.add_object(
			outline,
			self.midpoint_x - self.ship_space - self.p1.width,
			midpoint_y - self.p1.height // 2 - 1
		)
		self.main_win.add_object(
			self.p2,
			self.midpoint_x + self.ship_space,
			midpoint_y - self.p2.height // 2
		)
		self.main_win.add_object(
			self.p1,
			4,
			midpoint_y - self.p1.height // 2
		)
		self.main_win.add_object(
			self.p1.thruster,
			2,
			midpoint_y + 1
		)
		self.main_win.display(0, 7)

		self.main_win.auto_refresh = False
		position = self.p1.scene.objects[self.p1.stacking_order]
		distance = self.midpoint_x - self.ship_space - position.x2
		speed = 0.04
		while distance > 0:
			self.main_win.move_relative(self.p1, x=1)
			self.main_win.move_relative(self.p1.thruster, x=1)
			self.p1.thruster.update()
			self.main_win.pan(x=1)
			self.main_win.refresh()
			time.sleep(speed)
			if distance == 40:
				self.main_win.hide(self.p1.thruster)
			if distance < 40:
				speed += 0.005
			distance -= 1

		msg = Alert('!!! WARNING !!!\nENEMY WEAPONS LOCKED')
		msg.show(self.main_win)
		self.main_win.refresh()
		time.sleep(3)
		msg.hide()
		self.main_win.refresh()


	def play(self):
		self.p1.status_win.display(
			curses.COLS // 2 - self.ship_space - self.max_health,
			2
		)
		self.p2.status_win.display(
			curses.COLS // 2 + self.ship_space,
			2
		)

		if self.p1.scene.objects[self.p1.stacking_order].x2 != self.midpoint_x - self.ship_space:
			self.main_win.move_to(self.p1, x=self.midpoint_x - self.ship_space - self.p1.width)
			self.main_win.pan(x=self.main_win.width - self.main_win.win_width)

		laser = Laser(self.p1, self.p2, self.main_win.height // 2)
		self.main_win.add_object(laser, laser.x1, laser.y)

		shield1 = Drawable(')')
		shield1.set_color(curses.COLOR_CYAN)
		shield1.set_attrs(curses.A_BOLD)
		self.main_win.add_object(shield1, laser.x1, laser.y)
		self.main_win.hide(shield1)
		shield2 = Drawable('(')
		shield2.set_color(curses.COLOR_CYAN)
		shield2.set_attrs(curses.A_BOLD)
		self.main_win.add_object(shield2, laser.x2, laser.y)
		self.main_win.hide(shield2)

		self.main_win.refresh()
		self.main_win.auto_refresh = True
		step = 0
		while not self.p1.health.is_empty() and not self.p2.health.is_empty():
			time.sleep(0.5)
			target1 = self.p1.get_target()
			target2 = self.p2.get_target()

			target = None
			successful = True
			if step < 5:
				target = self.p1
				if not self.is_valid_target(target1):
					target1 = 0
				elif not self.is_valid_target(target2) or target1 == target2:
					successful = False
			else:
				target = self.p2
				if not self.is_valid_target(target2):
					target2 = 0
				elif not self.is_valid_target(target1) or target1 == target2:
					successful = False

			self.p1.show_target(target2)
			self.p2.show_target(target1)

			direction = 1

			if target is self.p1:
				direction = -1
			self.main_win.show(laser)
			laser.start(direction)
			time.sleep(0.01)
			while laser.advance():
				time.sleep(0.02)

			if not successful:
				if direction > 0:
					self.main_win.show(shield2)
					time.sleep(0.5)
					self.main_win.hide(shield2)
				else:
					self.main_win.show(shield1)
					time.sleep(0.5)
					self.main_win.hide(shield1)

			self.main_win.hide(laser)

			if successful:
				target.health.decrease()
				target.set_color(curses.COLOR_RED)
				if target.health.is_empty():
					continue
				time.sleep(0.2)
				target.set_color(curses.COLOR_WHITE)

			step = (step + 1) % 10

		explosion = Explosion(target)
		explosion.set_color(curses.COLOR_YELLOW)
		explosion.set_attrs(curses.A_BOLD)
		self.main_win.add_object(explosion, explosion.x, explosion.y)
		explosion.explode()

		self.winner = self.p2
		if target is self.p2:
			self.winner = self.p1


	def outro(self):
		if self.winner is self.p1:
			self.win_animation()
		else:
			self.lose_animation()


	def win_animation(self):
		ship_position = self.main_win.objects[self.p1.stacking_order].x1
		distance = self.main_win.max_x - ship_position + 2

		self.main_win.auto_refresh = False
		self.main_win.show(self.p1.thruster)
		self.p1.thruster.step = 1
		speed = 0.25
		while distance >= 0:
			self.main_win.move_relative(self.p1, x=1)
			self.p1.thruster.update()
			self.main_win.move_relative(self.p1.thruster, x=1)
			self.main_win.refresh()
			time.sleep(speed)
			speed -= 0.005
			if speed < 0.04:
				speed = 0.04

			distance -= 1

		self.main_win.auto_refresh = True
		msg = Alert('!!! CONGRATULATIONS !!!\nTHE GUMMIES HAVE BEEN SAVED')
		msg.show(self.main_win)
		time.sleep(3)
		msg.hide()


	def lose_animation(self):
		msg = Alert('YOUR SHIP HAS BEEN DESTROYED')
		msg.show(self.main_win)
		time.sleep(5)
		msg.hide()


	def generate_starfield(self, width, height):
		starfield = ''
		stars = ['.', '*', '`', '.']
		for y in range(0, height):
			for x in range(0, width):
				if random.randint(0, 30) == 0:
					starfield += random.choice(stars)
				else:
					starfield += ' '

			starfield += '\n'

		return starfield.rstrip()


	@staticmethod
	def is_valid_target(target):
		return target in (1, 2, 3, 4, 5)
示例#12
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 640
    res_y = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position = Vector3(0, 0, -2)

    # Create a cube and place it in a scene, at position (0,0,0)
    obj1 = Object3d("TestObject")
    obj1.scale = Vector3(1, 1, 1)
    obj1.position = Vector3(0, 0, 2)
    obj1.mesh = Mesh.create_cube((1, 1, 1))
    obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
    scene.add_object(obj1)

    # Create a second object, and add it as a child of the first object
    # When the first object rotates, this one will also mimic the transform
    obj2 = Object3d("ChildObject")
    obj2.position += Vector3(0, 0.75, 0)
    obj2.mesh = Mesh.create_cube((0.5, 0.5, 0.5))
    obj2.material = Material(Color(0, 1, 0, 1), "TestMaterial2")
    obj1.add_child(obj2)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 15
    axis = Vector3(1, 0.7, 0.2)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(False)
    pygame.event.set_grab(True)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # If ESC is pressed exit the application
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 20))

        # Rotates the object, considering the time passed (not linked to frame rate)
        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)
        obj1.rotation = q * obj1.rotation

        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
示例#13
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 640
    res_y = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 2)

    # Create the cube mesh we're going to use for every single object
    cube_mesh = Mesh.create_cube((1, 1, 1))
    # Spawn rate is one cube every 25 ms
    spawn_rate = 0.025
    # Keep a timer for the cube spawn
    cube_spawn_time = spawn_rate
    # Storage for all the objects created this way
    falling_objects = []

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(True)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # If ESC is pressed exit the application
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Update the cube spawn timer
        cube_spawn_time = cube_spawn_time - delta_time
        if cube_spawn_time < 0:
            # It's time to spawn a new cube
            cube_spawn_time = spawn_rate

            # Create a new cube, and add it to the scene
            new_cube = FallingCube(cube_mesh)
            scene.add_object(new_cube)

            # Add the new cube to the storage, so it can be updated
            falling_objects.append(new_cube)

        # Update the cubes
        for falling_object in falling_objects:
            falling_object.update(delta_time)

            # Is the cube fallen too far?
            if falling_object.position.y < -8:
                # Remove cube from scene
                scene.remove_object(falling_object)

        # Update the storage, so that all cubes that have fallen too far disappear
        falling_objects = [x for x in falling_objects if x.position.y > -8]

        # Render the scene
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
示例#14
0
    rects = []
    #rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
    #rects = non_max_suppression(rects, probs=None, overlapThresh=0.65)

    objects = []

    for contour in contours:
        obj = ImageObject(0, contour, frame)
        if obj.get_area() < 1000:
            continue
        if obj.get_area() > 30000:
            continue
        if obj.detect_human():
            #print(f"HUMAN {i}")
            i += 1
        objects.append(obj)

    for o in objects:
        scene.add_object(o)

    for i, o in scene.objects.items():
        o.draw(frame)

    cv2.imshow('f', mask)
    cv2.imshow('fr', frame)
    k = cv2.waitKey(1) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()
示例#15
0
class MainWindowHandler:
    def __init__(self, builder):
        self.builder = builder
        self.window = builder.get_object('main_window')
        self.object_store = builder.get_object('object_store')
        self.scene = Scene()
        self.output_buffer = builder.get_object('outputbuffer')
        self.press_start = None
        self.old_size = None
        self.rotation_ref = RotationRef.CENTER
        self.current_file = None
        self.clipping_method = LineClippingMethod.COHEN_SUTHERLAND
        self.pressed_keys = set()

        # 3D Tests
        obj = GraphicObject3D(
            vertices=[
                Vec3(
                    0,
                    0,
                    0,
                ),
                Vec3(
                    0,
                    0,
                    1,
                ),
                Vec3(
                    1,
                    0,
                    1,
                ),
                Vec3(
                    1,
                    0,
                    0,
                ),
                Vec3(
                    0,
                    0,
                    0,
                ),
                Vec3(
                    0,
                    1,
                    0,
                ),
                Vec3(
                    1,
                    1,
                    0,
                ),
                Vec3(
                    1,
                    0,
                    0,
                ),
                Vec3(
                    0,
                    0,
                    0,
                ),
                Vec3(
                    0,
                    0,
                    1,
                ),
                Vec3(
                    0,
                    1,
                    1,
                ),
                Vec3(
                    0,
                    1,
                    0,
                ),
                Vec3(
                    0,
                    0,
                    0,
                ),
                Vec3(
                    0,
                    0,
                    1,
                ),
                Vec3(
                    0,
                    0,
                    1,
                ),
                Vec3(
                    0,
                    1,
                    1,
                ),
                Vec3(
                    1,
                    1,
                    1,
                ),
                Vec3(
                    1,
                    0,
                    1,
                ),
                Vec3(
                    0,
                    0,
                    1,
                ),
                Vec3(
                    0,
                    1,
                    1,
                ),
                Vec3(
                    0,
                    1,
                    1,
                ),
                Vec3(
                    1,
                    1,
                    1,
                ),
                Vec3(
                    1,
                    1,
                    0,
                ),
                Vec3(
                    0,
                    1,
                    0,
                ),
            ],
            name='hmmm',
        )

        obj.rotate(30, 30, 30, reference=obj.centroid)

        self.add_object(obj)

    def log(self, msg: str):
        self.output_buffer.insert_at_cursor(f'{msg}\n')
        scrollwindow = self.builder.get_object('output_scrollwindow')
        adjustment = scrollwindow.get_vadjustment()
        adjustment.set_value(adjustment.get_upper())

    def on_destroy(self, *args):
        self.window.get_application().quit()

    def on_resize(self, widget: Gtk.Widget, allocation: Gdk.Rectangle):
        if self.scene.window is None:
            w, h = allocation.width, allocation.height
            self.old_size = allocation
            self.scene.window = Window(Vec2(-w / 2, -h / 2),
                                       Vec2(w / 2, h / 2))

        w_proportion = allocation.width / self.old_size.width
        h_proportion = allocation.height / self.old_size.height

        self.scene.window.max = Vec2(self.scene.window.max.x * w_proportion,
                                     self.scene.window.max.y * h_proportion)
        self.scene.window.min = Vec2(self.scene.window.min.x * w_proportion,
                                     self.scene.window.min.y * h_proportion)
        self.old_size = allocation

        self.scene.update_ndc()

    def viewport(self) -> Rect:
        widget = self.builder.get_object('drawing_area')
        return Rect(min=Vec2(0, 0),
                    max=Vec2(
                        widget.get_allocated_width(),
                        widget.get_allocated_height(),
                    )).with_margin(10)

    def on_draw(self, widget, cr):
        viewport = self.viewport()
        vp_matrix = viewport_matrix(viewport)

        cr.set_line_width(2.0)
        cr.paint()
        cr.set_source_rgb(0.8, 0.0, 0.0)

        for obj in self.scene.objs:
            clipped = obj.clipped(method=self.clipping_method)
            if clipped:
                clipped.draw(cr, vp_matrix)

        cr.set_source_rgb(0.4, 0.4, 0.4)
        viewport.draw(cr, vp_matrix)

    def on_new_object(self, widget):
        dialog = NewObjectDialog()
        response = dialog.dialog_window.run()

        if response == Gtk.ResponseType.OK:
            if dialog.new_object is not None:
                self.add_object(dialog.new_object)
                self.builder.get_object('drawing_area').queue_draw()
            else:
                self.log('ERROR: invalid object')

    def on_quit(self, widget):
        self.window.close()

    def on_about(self, widget):
        about_dialog = Gtk.AboutDialog(
            None,
            authors=['Arthur Bridi Guazzelli', 'João Paulo T. I. Z.'],
            version='1.5.0',
            program_name='Rudolph')
        about_dialog.run()
        about_dialog.close()

    def on_key_press(self, widget, event):
        '''
        Returns: False if event can propagate, True otherwise.
        '''
        DIRECTIONS = {
            Gdk.KEY_Up: Vec2(0, -10),
            Gdk.KEY_Down: Vec2(0, 10),
            Gdk.KEY_Left: Vec2(10, 0),
            Gdk.KEY_Right: Vec2(-10, 0),
        }

        self.pressed_keys |= {event.keyval}

        for key in self.pressed_keys:
            if key in DIRECTIONS:
                self.world_window.offset(DIRECTIONS[key])

        self.window.queue_draw()

        return True

    def on_key_release(self, widget, event):
        '''
        Returns: False if event can propagate, True otherwise.
        '''

        self.pressed_keys -= {event.keyval}

        return False

    def on_button_press(self, widget, event):
        if BUTTON_EVENTS[event.button] == 'left':
            # register x, y
            self.press_start = Vec2(-event.x, event.y)
            self.dragging = True

    def on_motion(self, widget, event):
        def viewport_to_window(v: Vec2):
            viewport = self.viewport()

            return Vec2((v.x / viewport.width) * self.scene.window.width,
                        (v.y / viewport.height) * self.scene.window.height)

        # register x, y
        # translate window
        if self.dragging:
            current = Vec2(-event.x, event.y)
            delta = viewport_to_window(current - self.press_start)

            window = self.scene.window

            m = rotation_matrix(window.angle)

            delta = delta @ m

            self.scene.translate_window(delta)
            self.press_start = current
            widget.queue_draw()

    def on_button_release(self, widget, event):
        if BUTTON_EVENTS[event.button] == 'left':
            self.dragging = False

    def on_scroll(self, widget, event):
        if event.direction == Gdk.ScrollDirection.UP:
            self.scene.zoom_window(0.5)
        elif event.direction == Gdk.ScrollDirection.DOWN:
            self.scene.zoom_window(2.0)

        widget.queue_draw()

    def on_press_navigation_button(self, widget):
        TRANSFORMATIONS = {
            'nav-move-up': ('translate', Vec2(0, 10)),
            'nav-move-down': ('translate', Vec2(0, -10)),
            'nav-move-left': ('translate', Vec2(-10, 0)),
            'nav-move-right': ('translate', Vec2(10, 0)),
            'nav-rotate-left': ('rotate', -5),
            'nav-rotate-right': ('rotate', 5),
            'nav-zoom-in': ('scale', Vec2(1.1, 1.1)),
            'nav-zoom-out': ('scale', Vec2(0.9, 0.9)),
        }

        op, *args = TRANSFORMATIONS[widget.get_name()]
        if op == 'translate':
            args[0] = (args[0] @ rotation_matrix(self.scene.window.angle))

        for obj in self.selected_objs():
            if op == 'translate':
                obj.translate(*args)
            elif op == 'scale':
                obj.scale(*args)
            elif op == 'rotate':
                try:
                    abs_x = int(entry_text(self, 'rotation-ref-x'))
                    abs_y = int(entry_text(self, 'rotation-ref-y'))
                except ValueError:
                    abs_x = 0
                    abs_y = 0

                ref = {
                    RotationRef.CENTER: obj.centroid,
                    RotationRef.ORIGIN: Vec2(0, 0),
                    RotationRef.ABSOLUTE: Vec2(float(abs_x), float(abs_y)),
                }[self.rotation_ref]

                if isinstance(obj, GraphicObject3D):
                    obj.rotate(args[0], 0, 0, ref)
                else:
                    obj.rotate(*args, ref)
            obj.update_ndc(self.scene.window)

        self.window.queue_draw()

    def selected_objs(self):
        tree = self.builder.get_object('tree-displayfiles')
        store, rows = tree.get_selection().get_selected_rows()

        return (self.scene.objs[int(str(index))] for index in rows)

    def add_object(self, obj: GraphicObject):
        self.log(f'Object added: <{type(obj).__name__}>')
        self.scene.add_object(obj)
        self.add_to_treeview(obj)

    def add_to_treeview(self, obj: GraphicObject):
        self.object_store.append([obj.name, str(f'<{type(obj).__name__}>')])

    def remove_selected_objects(self, widget):
        tree = self.builder.get_object('tree-displayfiles')
        store, paths = tree.get_selection().get_selected_rows()

        for path in reversed(paths):
            iter = store.get_iter(path)
            store.remove(iter)
            self.scene.remove_objects([int(str(path))])
        self.window.queue_draw()

    def on_change_rotation_ref(self, widget: Gtk.RadioButton):
        for w in widget.get_group():
            if w.get_active():
                self.rotation_ref = {
                    'rotate-ref-obj-center': RotationRef.CENTER,
                    'rotate-ref-origin': RotationRef.ORIGIN,
                    'rotate-ref-abs': RotationRef.ABSOLUTE,
                }[w.get_name()]
                if w.get_name() == 'rotate-ref-abs':
                    for _id in 'rotation-ref-x', 'rotation-ref-y':
                        self.builder.get_object(_id).set_editable(True)

    def on_new_file(self, item):
        self.log('NEW FILE')
        old_window = self.scene.window
        self.scene = Scene(window=old_window)
        self.object_store.clear()
        self.current_file = None
        self.builder.get_object('drawing_area').queue_draw()

    def on_open_file(self, item):
        file_chooser = self.new_file_chooser(Gtk.FileChooserAction.OPEN)

        response = file_chooser.run()
        if response == Gtk.ResponseType.OK:
            path = file_chooser.get_filename()
            self.log(f'OPEN FILE: {path}')

            old_window = self.scene.window
            self.scene = load_scene(path)
            self.scene.window = old_window
            self.scene.update_ndc()

            self.object_store.clear()
            for obj in self.scene.objs:
                self.add_to_treeview(obj)

            self.current_file = path
            self.builder.get_object('drawing_area').queue_draw()
        file_chooser.destroy()

    def on_save_file(self, item):
        label = item.get_label()
        if label == 'gtk-save' and self.current_file is not None:
            self.save_scene()

        elif label == 'gtk-save-as' or self.current_file is None:
            file_chooser = self.new_file_chooser(Gtk.FileChooserAction.SAVE)

            response = file_chooser.run()
            if response == Gtk.ResponseType.OK:
                path = file_chooser.get_filename()
                self.log(path)
                self.save_scene()
                self.current_file = path
            file_chooser.destroy()

    def save_scene(self):
        save_scene(self.scene, self.current_file)
        self.log(f'SAVE FILE: {self.current_file}')

    def new_file_chooser(self, action):
        file_chooser = Gtk.FileChooserDialog(
            parent=self.window,
            action=action,
            buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK,
                     Gtk.ResponseType.OK))

        if action == Gtk.FileChooserAction.OPEN:
            file_chooser.title = 'Open file'

        elif action == Gtk.FileChooserAction.SAVE:
            file_chooser.title = 'Save file'
            file_chooser.set_current_name('untitled.obj')

        filter = Gtk.FileFilter()
        filter.set_name('CG OBJ')
        filter.add_pattern('*.obj')
        file_chooser.add_filter(filter)

        return file_chooser

    def on_clicked_rotate_window(self, widget: Gtk.Button):
        rotation_angle = int(entry_text(self, 'window-rot-entry'))
        self.scene.window.angle += rotation_angle
        for obj in self.scene.objs:
            obj.update_ndc(self.scene.window)
        self.log(f'Window rotated {rotation_angle} degrees')
        self.window.queue_draw()

    def on_change_clipping_method(self, widget: Gtk.ComboBoxText):
        METHODS = {
            'Cohen Sutherland': LineClippingMethod.COHEN_SUTHERLAND,
            'Liang Barsky': LineClippingMethod.LIANG_BARSKY,
        }
        self.clipping_method = METHODS[widget.get_active_text()]
        self.window.queue_draw()
示例#16
0
def main():
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    screenX = 640
    screenY = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((screenX, screenY))

    # Create a scene
    scene = Scene("TesteCena")
    scene.camera = Camera(False, screenX, screenY)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 2)

    # Create a sphere and place it in a scene, at position (0,0,0)
    obj = Object3d("Object")
    obj.scale = Vector3(1, 1, 1)
    obj.position = Vector3(0, 0, 0)

    #Number of sides of the cilinder
    sides = 12

    #Create a cilinder
    obj.mesh = Mesh.create_cylinder(sides, 1, 1, None)

    #Create a sphere
    #obj.mesh = Mesh.create_sphere((1, 1, 1), 12, 12)
    
    #Create a cube
    #obj.mesh = Mesh.create_cube((5, 5, 5))
    
    obj.material = Material(Color(1, 0, 0, 1), "Material1")
    scene.add_object(obj)

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(True)
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
         #Busca o evento
        events = pygame.event.get()
        key = pygame.key.get_pressed()
        ang = 20

        #Quando é carregada a tecla W
        if key[pygame.K_w]:
            movement = Vector3(0, 1, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla S
        if key[pygame.K_s]:
            movement = Vector3(0, -1, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla A
        if key[pygame.K_a]:
            movement = Vector3(-1, 0, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla D
        if key[pygame.K_d]:
            movement = Vector3(1, 0, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla Q
        if key[pygame.K_q]:
            movement = Vector3(0, 0, 1)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla E
        if key[pygame.K_e]:
            movement = Vector3(0, 0, -1)
            movement.normalize()
            obj.position = obj.position + movement * delta_time
        
        #Quando é carregada a seta para a direita
        if key[pygame.K_RIGHT]:
            rot = Vector3(0, -1, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a seta para a esquerda
        if key[pygame.K_LEFT]:
            rot = Vector3(0, 1, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation
            
        #Quando é carregada a seta para baixo
        if key[pygame.K_DOWN]:
            rot = Vector3(-1, 0, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a seta para cima
        if key[pygame.K_UP]:
            rot = Vector3(1, 0, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a tecla PgUp
        if key[pygame.K_PAGEUP]:
            rot = Vector3(0, 0, 1)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a tecla PgDn
        if key[pygame.K_PAGEDOWN]:
            rot = Vector3(0, 0, -1)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        for event in events:
            #Quando é carregada a tecla ESC
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    exit()
                    
            #Quando é carregado o botão para sair do programa
            if event.type == pygame.QUIT:
                exit()

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
示例#17
0
def main():
    """Main function, it implements the application loop"""

    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 0)

    # Creates the terrain meshes and materials
    terrain_object = create_terrain()
    scene.add_object(terrain_object)

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            key_state = pygame.key.get_pressed()
            if key_state[pygame.K_ESCAPE]:
                return
            if key_state[pygame.K_d]:
                scene.camera.position = Vector3(scene.camera.position.x + 0.1,
                                                scene.camera.position.y,
                                                scene.camera.position.z)
            if key_state[pygame.K_a]:
                scene.camera.position = Vector3(scene.camera.position.x - 0.1,
                                                scene.camera.position.y,
                                                scene.camera.position.z)
            if key_state[pygame.K_w]:
                scene.camera.position = Vector3(scene.camera.position.x,
                                                scene.camera.position.y,
                                                scene.camera.position.z + 0.1)
            if key_state[pygame.K_s]:
                scene.camera.position = Vector3(scene.camera.position.x,
                                                scene.camera.position.y,
                                                scene.camera.position.z - 0.1)

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 20))

        # Render scene
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
示例#18
0
def main():
    """Main function, it implements the application loop"""

    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 0)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given, every second
    axis = scene.camera.up()
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(False)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(True)
    
    #Clean count to make a max nuber of cubes
    count = 0
    #Number of cubes in scene
    while count < 72:
        #function to add 72 cubes in scene at random
        new_cube = RandomCube()
        scene.add_object(new_cube)
        count += 1


    # Game loop, runs forever
    while True:

        # Process OS events
        for event in pygame.event.get():
            
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
                axis.normalize() 
        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 20))

        keys=pygame.key.get_pressed()
        # Confine the mouse to the center of the screen         
        pygame.mouse.set_pos(res_x/2, res_y/2)        

        # Get the mouse movement from the last frmae
        rel = pygame.mouse.get_rel()

        # Gets the rotation angle
        rotAngle = rel[0] * 4

        if rel[0] != 0:
            # Rotates the object, considering the time passed (not linked to frame rate)
            q = Quaternion.AngleAxis(axis, math.radians(rotAngle) * delta_time)
            
            #camera rotation
            scene.camera.rotation = q * scene.camera.rotation
    
        ''' Movement Stuff'''
        
        #going forwards
        if keys[pygame.K_w]:
            scene.camera.position += scene.camera.forward() * delta_time * 4
        #going backwards
        if keys[pygame.K_s]:
            scene.camera.position -= scene.camera.forward() * delta_time * 4
        #going left
        if keys[pygame.K_a]:
            scene.camera.position -= scene.camera.right() * delta_time * 4
        #going right
        if keys[pygame.K_d]:
            scene.camera.position += scene.camera.right() * delta_time * 4
            
        # Render scene
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        #Limit fps to 144
        while time.time() - prev_time < 0.00694:
            continue

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
示例#19
0
from scene import Scene
from camera import Camera
from lights import *
from objects import *
from color import Color

width, height = 800, 600

scene = Scene(Camera((0, -80, 20), 60), (80, 60), (width, height))

scene.add_light(Ambiant(intensity=0.2))
scene.add_light(Diffuse(-20, -40, 20, intensity=0.8))
scene.add_light(Diffuse(40, 40, 5, intensity=0.4))
scene.add_light(Specular(-20, -40, 20, intensity=0.6))

scene.add_object(Sphere(10, x=50, y=30, scale_z=1.5, color=Color(r=255)))
scene.add_object(Sphere(3, z=20, scale_x=5, color=Color(g=255)))
scene.add_object(Sphere(5, color=Color(r=255, b=255)).stretch('x', angle_y=60))
scene.add_object(Plane(z=-10, color=Color(255, 255, 255)))
scene.add_object(Plane(z=80, color=Color(255, 255, 255)))
scene.add_object(Plane(x=-80, rot_y=90, color=Color(b=255)))
scene.add_object(Plane(x=80, rot_y=90, color=Color(b=255)))
scene.add_object(Plane(y=100, rot_x=90, color=Color(r=255, g=255)))
scene.add_object(Cylinder(5, x=-80, y=100, color=Color(b=255)))
scene.add_object(Cylinder(5, x=80, y=100, color=Color(b=255)))
scene.add_object(Cone(10, color=Color(r=128, g=128, b=128)))

nb_lines_chunk = 50
dispatch = Dispatcher(61385, set(i for i in range(height) if i % nb_lines_chunk == 0), key_fmt='i')

dispatch.welcome = bytes(scene)
示例#20
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 640
    res_y = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 2)

    # Create a sphere and place it in a scene, at position (0,0,0)
    obj1 = Object3d("TestObject")
    obj1.scale = Vector3(1, 1, 1)
    obj1.position = Vector3(0, 0, 0)
    obj1.mesh = Mesh.create_sphere((1, 1, 1), 12, 12)
    obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
    scene.add_object(obj1)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 0
    axis = Vector3(0, 1, 0)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(True)
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Rotates the object, considering the time passed (not linked to frame rate)
        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)
        obj1.rotation = q * obj1.rotation

        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()

        #Variavel que vai guardar a tecla pressionada
        k = pygame.key.get_pressed()

        #Cada tecla tem a sua própria ação
        if (k[pygame.K_UP]):
            angle = 15
            axis = Vector3(1, 0, 0)
        elif (k[pygame.K_DOWN]):
            angle = -15
            axis = Vector3(1, 0, 0)
        elif (k[pygame.K_LEFT]):
            angle = 15
            axis = Vector3(0, 1, 0)
        elif (k[pygame.K_RIGHT]):
            angle = -15
            axis = Vector3(0, 1, 0)
        elif (k[pygame.K_PAGEUP]):
            angle = 15
            axis = Vector3(0, 0, 1)
        elif (k[pygame.K_PAGEDOWN]):
            angle = -15
            axis = Vector3(0, 0, 1)
        elif (k[pygame.K_w]):
            obj1.position.y = obj1.position.y + 0.001
        elif (k[pygame.K_s]):
            obj1.position.y = obj1.position.y - 0.001
        elif (k[pygame.K_a]):
            obj1.position.x = obj1.position.x - 0.001
        elif (k[pygame.K_d]):
            obj1.position.x = obj1.position.x + 0.001
        elif (k[pygame.K_q]):
            obj1.position.z = obj1.position.z + 0.001
        elif (k[pygame.K_e]):
            obj1.position.z = obj1.position.z - 0.001
        else:
            angle = 0
示例#21
0
def main():

    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 0)

    # Creates the terrain meshes and materials
    terrain_object = create_terrain()
    scene.add_object(terrain_object)

    # Minimum time between player shots
    shot_cooldown = 0.2
    # Timer for the shot cooldown
    shot_timer = 0
    # Storage for all the shots active in the game
    shots = []

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Don't show mouse cursor
    pygame.mouse.set_visible(False)
    # Lock the mouse cursor to the game window
    pygame.event.set_grab(True)

    # Game loop, runs forever
    while True:
        #Busca o evento
        events = pygame.event.get()
        key = pygame.key.get_pressed()
        speed = 0.05
        ang = 20

        #Manter o rato no centro do ecrã
        displayCenter = [screen.get_size()[i] // 2 for i in range(2)]
        mouseMove = (0, 0)
        pygame.mouse.set_pos(displayCenter)

        #Buscar o movimento do rato e devolve (x, y)
        mouseMove = pygame.mouse.get_rel()

        #Código para movimentação da câmara a partir do movimento do rato
        rot = Vector3(mouseMove[1], mouseMove[0], 0)
        scene.camera.rotation *= Quaternion.AngleAxis(
            rot,
            math.radians(ang) * delta_time)

        #Para impedir que a câmara rode no eixo do Z
        scene.camera.rotation.z = 0

        #Quando é carregada a tecla W
        if key[pygame.K_w]:
            movement = Vector3(0, 0, 1)
            movement.normalize()
            scene.camera.position += movement * delta_time + scene.camera.forward(
            ) * speed

        #Quando é carregada a tecla S
        if key[pygame.K_s]:
            movement = Vector3(0, 0, -1)
            movement.normalize()
            scene.camera.position += movement * delta_time - scene.camera.forward(
            ) * speed

        #Quando é carregada a tecla A
        if key[pygame.K_a]:
            movement = Vector3(-1, 0, 0)
            movement.normalize()
            scene.camera.position += movement * delta_time - scene.camera.right(
            ) * speed

        #Quando é carregada a tecla D
        if key[pygame.K_d]:
            movement = Vector3(1, 0, 0)
            movement.normalize()
            scene.camera.position += movement * delta_time + scene.camera.right(
            ) * speed

        # Process OS events
        for event in events:
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                # If ESC is pressed exit the application
                if event.key == pygame.K_ESCAPE:
                    return
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # If the user has the mouse button down
                if shot_timer <= 0:
                    # We're not on cooldown, so we can shoot

                    # Get the mouse position and convert it to NDC (normalized
                    # device coordinates)
                    mouse_pos = pygame.mouse.get_pos()
                    mouse_pos = ((mouse_pos[0] / res_x) * 2 - 1,
                                 (mouse_pos[1] / res_y) * 2 - 1)

                    # Create a shot
                    shot = Shot()
                    # Initialize the position and direction of the shot, based on the
                    # mouse position on the screen. For this, we request the scene camera the
                    # ray corresponding to the mouse position
                    shot.position, shot.direction = scene.camera.ray_from_ndc(
                        mouse_pos)

                    # Add the shot to the scene (for rendering) and on the shot storage, for
                    # all other operations
                    scene.add_object(shot)
                    shots.append(shot)

                    # Reset the cooldown
                    shot_timer = shot_cooldown

        # Clears the screen with a black (0, 0, 0)
        screen.fill((0, 0, 0))

        # Animate shots
        # We need the following to keep track of all shots we'll have to destroy,
        # since we can't change the storage while we're iterating it
        shots_to_destroy = []
        for shot in shots:
            # Update the shot
            shot.update(delta_time)

            # Check if the shot is too far away, and add it to the destruction list,
            # besides removing it from the scene
            if shot.position.z > 12:
                # Destroy shot
                shots_to_destroy.append(shot)
                scene.remove_object(shot)

        # Update shot cooldown
        shot_timer -= delta_time

        # Actually delete objects
        shots = [x for x in shots if x not in shots_to_destroy]

        # Render scene
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()