Ejemplo n.º 1
0
    def __init__(self,
                 window_settings={},
                 renderer_settings={},
                 context_enables=DEFAULT_CONTEXT_ENABLES):
        Renderer.__init__(self)

        window_settings = {**DEFAULT_WINDOW_SETTINGS, **window_settings}
        renderer_settings = {**DEFAULT_RENDERER_SETTINGS, **renderer_settings}

        self.size = window_settings['size']

        for key, value in renderer_settings.items():
            setattr(self, key, value)

        self.context = moderngl.create_standalone_context(require=430)
        window_cls = import_string(window_settings["class"])
        self.wnd = window_cls(**window_settings)
        self.context.enable(context_enables)
        moderngl_window.activate_context(self.wnd, self.context)
        self.context = self.wnd.ctx

        # register event methods
        self.wnd.resize_func = self.resize
        self.wnd.iconify_func = self.iconify
        self.wnd.key_event_func = self.key_event
        self.wnd.mouse_position_event_func = self.mouse_position_event
        self.wnd.mouse_drag_event_func = self.mouse_drag_event
        self.wnd.mouse_scroll_event_func = self.mouse_scroll_event
        self.wnd.mouse_press_event_func = self.mouse_press_event
        self.wnd.mouse_release_event_func = self.mouse_release_event
        self.wnd.unicode_char_entered_func = self.unicode_char_entered
        self.wnd.close_func = self.close

        self.set_advance_time_function(self.advance_time)
Ejemplo n.º 2
0
    def __init__(self):
        self.clock = pygame.time.Clock()
        self.renderer = Renderer()
        self.physics = Physics()

        self.assets = {
            'objects': [],
            'quadtree': QuadTree(Rectangle(0, 0, 1.1e9, 1.1e9), 1)
        }

        self.generate_test_objects()
Ejemplo n.º 3
0
    def __init__( self, count ):
        self.model       = Model( count )
        self.simulator   = Simulator()
        self.camera      = Camera()
        self.renderer    = Renderer()

        self.exit        = False

        self.selection   = None
Ejemplo n.º 4
0
def p3p_render():

    # intrinsic (Given. Do not change)
    K = np.array([[823.8, 0.0, 304.8], [0.0, 822.8, 236.3], [0.0, 0.0, 1.0]])
    focal = [K[0, 0], K[1, 1]]
    center = [K[0, 2], K[1, 2]]

    # extrinsic
    print('Loading data ...')
    tag_size = 0.14  # meter
    Pw = est_Pw(tag_size)
    corners = np.load('corners.npy')

    # load and process mesh
    with open('data/mesh.json', 'r') as in_file:
        mesh = json.load(in_file)
    vertices = np.array(mesh['vertices'])
    faces = np.array(mesh['faces'])
    renderer = Renderer(focal,
                        center,
                        img_w=640,
                        img_h=480,
                        faces=faces,
                        color=(0.3, 0.5, 1.0, 1.0))

    # Process each frame
    print('Processing each frame ...')
    frames = glob.glob('data/frames/*.jpg')
    frames.sort()

    final = np.zeros([len(frames), 480, 640, 3], dtype=np.uint8)
    for i, f in enumerate(frames):
        img = np.array(imageio.imread(f))
        # PnP
        Pc = corners[i]
        R, t = PnP(Pc, Pw, K)

        # Render
        t = -R.T.dot(t)
        R = R.T
        points = vertices.dot(R.T) + t.squeeze()
        output, _ = renderer(points, np.eye(3), [0, 0, 0], img)
        final[i] = output

    # Save frames as GIF
    print('Saving GIF ...')
    with imageio.get_writer('scene_rendered.gif', mode='I') as writer:
        for i in range(len(final)):
            img = final[i]
            writer.append_data(img)

    print('Complete.')

    return
Ejemplo n.º 5
0
def test(param, test_ply_fn, start_id, end_id, out_ply_folder,
         out_render_gt_folder, out_render_out_folder):

    print("**********Initiate Netowrk**********")
    model = graphAE.Model(param)

    model.cuda()

    if (param.read_weight_path != ""):
        print("load " + param.read_weight_path)
        checkpoint = torch.load(param.read_weight_path)
        model.load_state_dict(checkpoint['model_state_dict'])

    model.eval()

    template_plydata = PlyData.read(param.template_ply_fn)
    faces = get_faces_from_ply(template_plydata)

    from renderer.render.gl.glcontext import create_opengl_context
    from renderer.render.gl.glcontext import destroy_opengl_context
    RESOLUTION = 1024

    glutWindow = create_opengl_context(width=RESOLUTION, height=RESOLUTION)

    render = Renderer(width=RESOLUTION, height=RESOLUTION)
    MSE_sum = 0
    MSE_num = 0
    for i in range(start_id, end_id):
        ply_fn = test_ply_fn + "%06d" % i + ".ply"
        if (os.path.exists(ply_fn) == False):
            continue
        pc, mean = get_pc_from_ply_fn(ply_fn)

        MSE = evaluate(param, model, render, "%06d" % i, pc, mean,
                       template_plydata, faces, out_ply_folder,
                       out_render_gt_folder, out_render_out_folder)
        MSE_sum = MSE_sum + MSE
        MSE_num = MSE_num + 1
    print("mean MSE:", MSE_sum / MSE_num)
    destroy_opengl_context(glutWindow)
Ejemplo n.º 6
0
def play(file, Q, size):
	grid = Grid(filename=file)
	print("Playing ", file)

	epsilon = 0.001
	action_size = 4 * (size-1) # number of colors is (size-1), number of directions is 4.

	state = grid.start_state
	won = False

	turns = 0

	while turns < 100000:
		if random.uniform(0, 1) < epsilon or not state in Q:
			action = random.randint(0,action_size-1)
		else:
			action = np.argmax(Q[state])

		color = int(action / 4 + 1)
		direction = int(action % 4)
		action_tu = (color, direction)

		turns += 1

		if not state.is_viable_action(action_tu):
			continue

		# Advance to the next state.
		state = state.next_state(action_tu)

		# Break if we're in the winning state.
		if state.is_winning():
			won = True
			break
	renderer = Renderer("Play")
	renderer.render(state)
	renderer.tear_down()

	print ("Took " + str(turns) + " turns!")
	return won
Ejemplo n.º 7
0
#!/bin/python

import sys
from ai.ai import AI
from renderer.ui import ui as ui
from ai.log import log as log
from threading import Thread
import time
import errno
from socket import error as socket_error
from renderer.renderer import Renderer

renderer = Renderer()


def main():
    amount_of_ais = int(sys.argv[1])
    host = sys.argv[2]
    port = int(sys.argv[3])
    while True:
        ais = []
        try:
            for i in range(amount_of_ais):
                ais.append(
                    AI("The Machine Thread", i + 1, renderer, host, port))

            for ai in ais:
                ai.join()
        except socket_error as serr:
            for ai in ais:
                ai.stop()
Ejemplo n.º 8
0
class StarSystem:
    def __init__(self):
        self.clock = pygame.time.Clock()
        self.renderer = Renderer()
        self.physics = Physics()

        self.assets = {
            'objects': [],
            'quadtree': QuadTree(Rectangle(0, 0, 1.1e9, 1.1e9), 1)
        }

        self.generate_test_objects()

    def run(self):
        self.running = True
        while self.running:
            self.clock.tick(26)

            # self.counter += 1
            # if self.counter % 20 == 0:
            #     self.assets['objects'].append(
            #         Star(3000, 8e6, (random.randint(-500e6, 500e6), random.randint(-500e6, 500e6))))

            self.print_debug()

            self.check_for_keys_pressed()

            self.refresh_quadtree()

            self.physics.gravity(self.assets['objects'])
            self.physics.update_positions(self.assets['objects'],
                                          self.clock.get_time())

            self.renderer.clear_screen()
            self.renderer.draw_all_objects(self.assets)

            self.check_window_exit()
        pygame.quit()

    def generate_test_objects(self):
        self.assets['objects'].append(Star(3000, 35e6, (0, 0)))
        self.assets['objects'].append(Planet(300, 5e6, (120e6, 0), (0, -39e6)))
        self.assets['objects'].append(Planet(5, 1.2e6, (135e6, 0), (0, -3e6)))
        self.assets['objects'].append(Planet(200, 6e6, (500e6, 0), (0, -20e6)))
        self.assets['objects'].append(Planet(150, 4e6, (300e6, 0), (0, -25e6)))
        for i in range(30):
            self.assets['objects'].append(
                Planet(random.randint(150, 500),
                       random.randint(1.2e6, 6e6), (random.randint(
                           -500e6, 500e6), random.randint(-500e6, 500e6)),
                       (random.randint(-39e6, 39e6), random.randint(
                           -39e6, 39e6))))

    # def add_new_object(self):
    #     self.assets['objects'].append(Star(3000, 35e6, (0, 0)))
    #     for i in range(5):
    #         self.assets['objects'].append(Star(3000, 15e6, (random.randint(-500e6, 500e6), random.randint(-500e6, 500e6))))

    def check_for_keys_pressed(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.renderer.focus[0] -= 10
        if keys[pygame.K_RIGHT]:
            self.renderer.focus[0] += 10
        if keys[pygame.K_UP]:
            self.renderer.focus[1] -= 10
        if keys[pygame.K_DOWN]:
            self.renderer.focus[1] += 10
        if keys[pygame.K_KP_MINUS]:
            self.renderer.kmPerPixel += 10000
        if keys[pygame.K_KP_PLUS] and self.renderer.kmPerPixel > 10000:
            self.renderer.kmPerPixel -= 10000
        if keys[pygame.K_ESCAPE]:
            self.running = False

    def check_window_exit(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

    def refresh_quadtree(self):
        self.assets['quadtree'] = QuadTree(Rectangle(0, 0, 1.1e9, 1.1e9), 1)
        for object in self.assets['objects']:
            self.assets['quadtree'].insert(object)

    def print_debug(self):
        print('______')
        # print(self.clock.get_time())
        # print(self.clock.get_rawtime())
        load = int(self.clock.get_rawtime() / 38 * 100)
        print(f"Load: {load}%")
        print(f'Focus: {self.renderer.focus}')
        print(f'kmPerPixel: {self.renderer.kmPerPixel}')
Ejemplo n.º 9
0
#!/usr/bin/python
import pygame, sys, os
from pygame.locals import *
from drawing.camera import Camera
from data.world import World
from renderer.renderer import Renderer
from material.materials import Materials

pygame.init()
camera = Camera(1280, 720, pygame.display.set_mode((1280, 720)))
pygame.display.set_caption('Pixel Planet')
world = World(1290,730)
world.generate()

renderer = Renderer(camera);

#print world.to_string()

def input(events):
	for event in events:
		if event.type == QUIT:
			sys.exit(0)
		if event.type == KEYDOWN and event.key == 27:
			sys.exit(0)
		else:
			print(event)

while True:
    input(pygame.event.get())
    renderer.draw(world)
Ejemplo n.º 10
0
import pygame

from simulator.model import Model
from simulator.simulator import Simulator
from renderer.camera import Camera
from renderer.renderer import Renderer

pygame.init()
pygameFlags = pygame.RESIZABLE | pygame.OPENGL | pygame.DOUBLEBUF
screen = pygame.display.set_mode( ( 800, 600 ), pygameFlags, 24 )

Renderer.setupGL()

class GameState:
    def __init__( self, count ):
        self.model       = Model( count )
        self.simulator   = Simulator()
        self.camera      = Camera()
        self.renderer    = Renderer()

        self.exit        = False

        self.selection   = None

state = GameState( 1000 )

while not state.exit:

    for e in pygame.event.get():
        mod = 1 if 'mod' in e.dict and int( e.mod ) & ( 64 + 128 ) else 0 # left or right CTRL
        mod2 = 1 if 'mod' in e.dict and int( e.mod ) & ( 1 + 2 ) else 0 # left or right SHIFT