def test_scene_assigns_unique_ids(self): rng = list(range(0, 1000)) scene = Scene(None) for obj in [GameObject() for x in rng]: scene.add_object(obj) scene.setup_frame(1.0) self.assertEqual(set(scene.objects.keys()), set(rng))
class Platformer(Application): def __init__(self): super(Platformer, self).__init__() 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 def _create_interface(self): self.scene.interface = Canvas(self.scene) group = SpriteGroup("life_indicator", [("assets/interface/heart.png", 32, 32)] * 3, spacing=4) self.scene.interface.add_child(group) def damaged(group, event): group.visible_count = event["lives"] group.rebuild_sprite() group.listen_for_event("player_damaged", damaged)
def test_find_no_objects_of_type(self): scene = Scene(None) obj = GameObject(components.Camera()) scene.add_object(obj) self.assertIsNone(scene.get_object_of_type(components.Renderable)) self.assertItemsEqual(scene.get_objects_of_type(components.Renderable), [])
def render(self, window): Scene.render(self, window) window.fill((255, 255, 0)) self.player.draw(window) self.player_ia.draw(window) self.ball.draw(window) self.btnGoHome.draw(window)
def test_scene_adds_objects(self): scene = Scene(None) objects = [GameObject() for x in range(0, 1000)] for obj in objects: scene.add_object(obj) scene.setup_frame(1.0) self.assertEqual(len(scene.objects), len(objects)) self.assertEqual(set(scene.objects.values()), set(objects))
def test_scene_throws_exception_after_setup_if_object_queued_in_two_scenes(self): first_scene = Scene(None) second_scene = Scene(None) obj = GameObject() first_scene.add_object(obj) second_scene.add_object(obj) first_scene.setup_frame(1.0) with self.assertRaises(ObjectInScene): second_scene.setup_frame(1.0)
def test_removes_problematic_object_from_queue(self): first_scene = Scene(None) obj = GameObject() first_scene.add_object(obj) second_scene = Scene(None) second_scene.add_object(obj) first_scene.setup_frame(1.0) try: second_scene.setup_frame(1.0) except ObjectInScene: pass self.assertNotIn(obj, second_scene.objects_spawn_queue)
def __init__(self, app, engine): self.app = app self.engine = engine self.scene = s = Scene.empty() # Global state stuff self.visible_index = None self.objects = [] self.mouse_state = { btn: evt.MouseClickState.Up for btn in evt.MouseClickButton } self.mouse_state["pos"] = (0,0) # Camera width, height = engine.window.dimensions() self.camera = cam = Camera(60, width, height) self.camera_view = LookAtView(cam, position = [0,0,-2.5], bounds_zoom=(-7.0, -0.2)) # Assets self._setup_assets() # Callbacks s.on_initialized = self.init_scene s.on_window_resized = self.update_perspective s.on_key_pressed = self.handle_keypress s.on_mouse_move = s.on_mouse_click = s.on_mouse_scroll = self.handle_mouse
def __init__(self, app, engine): self.app = app self.engine = engine self.scene = s = Scene.empty() # Global state stuff self.shaders = () self.objects = () self.heightmap_seed = (1, 1) self.heightmap_size = (256, 256) self.compute_local_size = self._compute_local_size() self.compute_heightmap = None self.heightmap_texture = None self.heightmap_sampler = None self.heightmap_preview = None # Camera width, height = engine.window.dimensions() self.camera = cam = Camera(45, width, height) self.camera_view = LookAtView(cam, position = [0,0,-1.9], bounds_zoom=(-3.0, -0.2)) # Assets self._setup_assets() # Callbacks s.on_initialized = self.init_scene s.on_window_resized = self.update_perspective s.on_key_pressed = self.handle_keypress s.on_mouse_move = s.on_mouse_click = s.on_mouse_scroll = self.handle_mouse
def __init__(self, app, engine): self.app = app self.engine = engine self.scene = s = Scene.empty() # Global state stuff self.shaders = () self.objects = () self.debug = 0 self.light = {"rot": -95, "pitch": 40} # Camera width, height = engine.window.dimensions() self.camera = cam = Camera(45, width, height) self.camera_view = LookAtView(cam, position=[0, 0, -3.5], bounds_zoom=(-7.0, -0.2)) # Assets self._setup_assets() # Callbacks s.on_initialized = self.init_scene s.on_window_resized = self.update_perspective s.on_key_pressed = self.handle_keypress s.on_mouse_move = s.on_mouse_click = s.on_mouse_scroll = self.handle_mouse
def __init__(self, app, engine): self.app = app self.engine = engine self.scene = s = Scene.empty() self.shader = None self.objects = [] # Global state stuff self.mouse_state = { btn: evt.MouseClickState.Up for btn in evt.MouseClickButton } self.mouse_state["pos"] = (0, 0) width, height = engine.window.dimensions() cam_pos = [0, 0, -5.5] self.camera = { "pos_vec": cam_pos, "pos": Mat4.from_translation(*cam_pos), "proj": Mat4.perspective(radians(60), width / height, 0.001, 1000.0) } # Callbacks s.on_initialized = self.init_scene s.on_window_resized = self.update_perspective s.on_mouse_move = self.move_camera s.on_mouse_click = self.move_camera s.on_key_pressed = self.handle_keypress
def test_scene_does_not_allow_objects_from_another_scene(self): first_scene = Scene(None) second_scene = Scene(None) obj = GameObject() first_scene.add_object(obj) first_scene.setup_frame(1.0) with self.assertRaises(ObjectInScene): second_scene.add_object(obj)
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)
def test_scene_remove_queued_object(self): scene = Scene(None) obj = GameObject() scene.add_object(obj) scene.remove_object(obj) scene.setup_frame(1.0) self.assertEqual(0, len(scene.objects))
def simulation(filename): scenes_folder = os.walk(app.node.scenes_root) scenes = [] for addr, dirs, files in scenes_folder: for file in files: if filename in file: with open(addr+'/'+file,'r') as f: app.node.scene = Scene.fromDict(json.load(f)) for worker in app.node.workers: response = requests.post(('http://%s:%s/api/internal/worker/scene/init/' + filename) % (worker.ip, worker.port)) return render_template("simulation.html")
def scene_init(filename): scenes_folder = os.walk(app.node.scenes_root) scenes = [] for addr, dirs, files in scenes_folder: for file in files: if filename in file: with open(addr+'/'+file,'r') as f: app.node.scene = Scene.fromDict(json.load(f)) app.node.scene.addObject(Fluid(32)) app.image = Image(app.node.scene.frameWidth, app.node.scene.frameHeight) return ok()
def test_find_ordered_objects_of_type(self): scene = Scene(None) objects = [GameObject(components.Camera()) for x in range(0, 5)] for obj in objects: scene.add_object(obj) scene.setup_frame(1.0) component_list = [x.get_component(components.Camera) for x in objects] self.assertEqual(component_list, scene.get_objects_of_type(components.Camera)) self.assertNotEqual(component_list[::-1], scene.get_objects_of_type(components.Camera))
def test_remove_object(self): scene = Scene(None) objects = [GameObject() for x in range(0, 1000)] for obj in objects: scene.add_object(obj) scene.setup_frame(1.0) cut = len(objects)//2 for obj in objects[:cut]: scene.remove_object(obj) self.assertEqual(len(objects) - cut, len(scene.objects)) self.assertSetEqual(set(objects[cut:]), set(scene.objects.values()))
def test_return_named_objects(self): scene = Scene(None) game_objects = [GameObject() for x in range(0, 10)] for index,obj in enumerate(game_objects): obj.name = str(index % 2) scene.add_object(obj) scene.setup_frame(1.0) self.assertEqual([x for x in game_objects if int(x.name) % 2 == 0], scene.get_objects_by_name("0"))
def test_return_named_object(self): scene = Scene(None) game_objects = [GameObject() for x in range(0, 10)] for index,obj in enumerate(game_objects): obj.name = str(index) scene.add_object(obj) scene.setup_frame(1.0) self.assertIs(game_objects[2], scene.get_object_by_name("2"))
def test_return_nameless(self): scene = Scene(None) game_objects = [GameObject() for x in range(0, 10)] for index,obj in enumerate(game_objects): obj.name = None if index % 2 == 0 else "name" scene.add_object(obj) scene.setup_frame(1.0) self.assertEqual([x for x in game_objects if x.name is None], scene.get_objects_by_name(None))
def test_simple_1000_spheres(self): scene = Scene("example") ruby_material = ColorMaterial(Color(255, 0, 0), Vector3d(0.1745, 0.01175, 0.01175), Vector3d(0.61424, 0.04136, 0.04136), Vector3d(0.727811, 0.626959, 0.626959), 76.8) x0 = -15 y0 = -15 for i in range(1000): x = x0 + i % 30 y = y0 + i // 30 z = 0 r = 0.5 scene.addObject( RenderableObject(Sphere(Vector3d(x, y, z), r), ruby_material)) scene.addLight(SpotLight(Vector3d(10, 10, -10))) scene.addCamera( Camera(Vector3d(0, 0, -25), Vector3d(0, 0, 0), Vector3d(0, 1, 0), 60, 4 / 3, 1)) image = Image(scene.frameWidth, scene.frameHeight) frames_cnt = 30 start = time.time() for i in range(frames_cnt): scene.getFrame(image) elapsed = time.time() - start print( "\n1000 spheres frames per second : Time = {}s, Frames = {}, FPS = {}" .format(round(elapsed, 4), frames_cnt, round(frames_cnt / elapsed, 4)), end="")
def test_deserialization(self): print("\nScene deserialization", end="") obj_cnt = 10 light_cnt = 2 camera_cnt = 1 scene = create_scene_sample(camera_cnt, obj_cnt, light_cnt) dict = json.loads(repr(scene)) s = Scene.fromDict(dict) self.assertEqual(s.name, "example") self.assertEqual(s.frameWidth, 800) self.assertEqual(s.frameHeight, 600) self.assertEqual(s.objCnt, obj_cnt) self.assertEqual(s.lightCnt, light_cnt) self.assertEqual(s.camCnt, camera_cnt)
def clearUserEnv(self): '''Clears user environment to a clean slate''' UE = self.userenv for asset in list(UE.assets): self.delAsset(asset) UE.focus = None UE.camera = Camera() UE.scene = Scene() UE.assets.clear() try: shutil.rmtree(datapath("save/assets/meshes")) shutil.rmtree(datapath("save/assets/textures")) os.mkdir(datapath("save/assets/meshes")) os.mkdir(datapath("save/assets/textures")) except: pass
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
def create_scene_sample(camera_cnt=1, obj_cnt=1, light_cnt=1): scene = Scene("example") for i in range(camera_cnt): scene.addCamera( Camera(Vector3d(2 * i + 1, 3 * i + 1, 4 * i + 1), Vector3d(0, 0, 0), Vector3d(0, 1, 0), 60, 4 / 3, 1), True) ruby_material = ColorMaterial(Color(255, 0, 0), Vector3d(0.1745, 0.01175, 0.01175), Vector3d(0.61424, 0.04136, 0.04136), Vector3d(0.727811, 0.626959, 0.626959), 76.8) for i in range(obj_cnt): scene.addObject( RenderableObject(Sphere(Vector3d(i * 10), i * 5), ruby_material)) for i in range(light_cnt): scene.addLight(SpotLight(Vector3d(-i * 2, i * 4, i * 5))) return scene
def test(name="example"): width = 640 height = 480 scene = Scene(name, width, height) ruby_material = ColorMaterial(Color(255, 0, 0), Vector3d(0.1745, 0.01175, 0.01175), Vector3d(0.61424, 0.04136, 0.04136), Vector3d(0.727811, 0.626959, 0.626959), 76.8) scene.addObject(RenderableObject(Sphere(Vector3d(0), 2), ruby_material)) #scene.addObject(RenderableObject(Sphere(Vector3d(4,4,-4), 1), ruby_material)) #scene.addLight(SpotLight(Vector3d(10,10,10))) scene.addLight(SpotLight(Vector3d(5, 6, -6))) scene.addCamera( Camera(Vector3d(0, 7, 7), Vector3d(0, 0, 0), Vector3d(0, -1, 1).normalized(), 75, width * 1.0 / height, 2), True) scene.addCamera( Camera(Vector3d(0, 10, 0), Vector3d(0, 0, 0), Vector3d(0, 0, 1), 75, width * 1.0 / height, 2), False) scene.addCamera( Camera(Vector3d(10, 0, 0), Vector3d(0, 0, 0), Vector3d(0, -1, 0), 75, width * 1.0 / height, 2), False) scene.addCamera( Camera(Vector3d(0, 0, 10), Vector3d(0, 0, 0), Vector3d(0, -1, 0), 75, width * 1.0 / height, 2), False) with open(name + '.json', 'w') as f: json.dump(json.loads(repr(scene)), f) dump_scene_image(scene)
def __init__(self, assets=set(), scene=Scene(), camera=Camera()): self.assets = assets self.scene = scene self.camera = camera
def render(self, window): Scene.render(self, window) window.fill((255, 255, 255)) self.btnGoPong.draw(window) self.btnGoCamp.draw(window)
def render(self, window): Scene.render(self, window) window.fill((255, 0, 255)) self.btnGoHome.draw(window)
def test_simple_scene(self): scene = Scene("example") ruby_material = ColorMaterial(Color(255, 0, 0), Vector3d(0.1745, 0.01175, 0.01175), Vector3d(0.61424, 0.04136, 0.04136), Vector3d(0.727811, 0.626959, 0.626959), 76.8) scene.addObject( RenderableObject(Sphere(Vector3d(0, 0, 0), 3), ruby_material)) scene.addObject( RenderableObject(Sphere(Vector3d(4, 4, -4), 1), ruby_material)) scene.addLight(SpotLight(Vector3d(10, 10, -10))) scene.addLight(SpotLight(Vector3d(0, 10, -5))) scene.addCamera( Camera(Vector3d(0, 0, -15), Vector3d(0, 0, 0), Vector3d(0, 1, 0), 60, 4 / 3, 1)) image = Image(scene.frameWidth, scene.frameHeight) frames_cnt = 30 start = time.time() for i in range(frames_cnt): scene.getFrame(image) elapsed = time.time() - start print( "\nSimple case frames per second : Time = {}s, Frames = {}, FPS = {}" .format(round(elapsed, 4), frames_cnt, round(frames_cnt / elapsed, 4)), end="")
if tank.target and tank.target.armor > 0: self.target = tank.target break self.follow_target() def _get_nearest_obj(self, objects): if objects: nearest_obj = objects[0] for obj in objects[1:]: if self.distance_to(obj) < self.distance_to(nearest_obj): nearest_obj = obj return nearest_obj return None scene = Scene('Tanks world') deploy1 = Point(constants.field_width - 100, 100) army_1 = [SimpleTank(pos=deploy1) for i in range(5)] deploy2 = Point(100, constants.field_height - 100) army_2 = [CooperativeTank(pos=deploy2) for i in range(5)] deploy3 = Point(100, 100) targets = [Target(pos=deploy3) for i in range(4)] targets += [Target(pos=deploy3, auto_fire=True) for i in range(4)] second_pos = (constants.field_width - 20, constants.field_height - 20) targets += [ StaticTarget(pos=(20, 20), angle=90), StaticTarget(pos=second_pos, angle=-90, auto_fire=True)
def test_constructor(self): print("\nConstructor without parameters", end="") scene = Scene() self.assertEqual(scene.name, "unnamed")
def test_custom_constructor(self): print("\nConstructor with parameters", end="") scene = Scene("test") self.assertEqual(scene.name, "test")
def test_simple_example(self): print("\nSimple example", end="") scene = Scene("example") self.assertEqual(scene.name, "example") ruby_material = ColorMaterial(Color(255, 0, 0), Vector3d(0.1745, 0.01175, 0.01175), Vector3d(0.61424, 0.04136, 0.04136), Vector3d(0.727811, 0.626959, 0.626959), 76.8) sphere = Sphere(Vector3d(0, 0, 0), 10) object = RenderableObject(sphere, ruby_material) light = SpotLight(Vector3d(10, 10, 10)) camera = Camera(Vector3d(0, 0, -10), Vector3d(0, 0, 0), Vector3d(0, 1, 0), 60, 4 / 3, 1) scene.addObject(object) self.assertEqual(scene.objCnt, 1) scene.clearObjects() self.assertEqual(scene.objCnt, 0) scene.addLight(light) self.assertEqual(scene.lightCnt, 1) self.assertTrue(light.state) scene.setOnOffLight(0, False) self.assertFalse(light.state) scene.clearLights() self.assertEqual(scene.lightCnt, 0) scene.addCamera(camera) self.assertEqual(scene.camCnt, 1) scene.clearCameras() self.assertEqual(scene.camCnt, 0)
def test_remove_on_empty_exception(self): scene = Scene(None) with self.assertRaises(ValueError): scene.remove_object(GameObject())
def test_scene_sets_game_objects_scene_attribute(self): scene = Scene(None) obj = GameObject() scene.add_object(obj) scene.setup_frame(1.0) self.assertTrue(obj.scene, scene)
def test_removed_objects_are_cleared_on_frame_end(self): scene = Scene(None) objects = [GameObject() for x in range(0, 100)] for obj in objects: scene.add_object(obj) scene.setup_frame(1.0) scene.simulate_preframe() scene.simulate_postframe() scene.remove_object(objects[0]) scene.setup_frame(1.0) scene.simulate_preframe() scene.simulate_postframe() self.assertIsNone(objects[0].scene) self.assertIsNone(objects[0].id)
def test_scene_does_not_allow_duplicated_additions(self): scene = Scene(None) obj = GameObject() scene.add_object(obj) with self.assertRaises(ObjectInScene): scene.add_object(obj)
def __init__(self): Scene.__init__(self)
def main(): c = Context("pygame", (800, 400), "Renderer") init_engine() clock = Clock() obj0 = Obj(r"./assets/objects/tetrahedron.obj") obj1 = Obj(r"./assets/objects/halfcube.obj") obj2 = Obj(r"./assets/objects/octahedron.obj") obj3 = Obj(r"./assets/objects/dodecahedron.obj") obj4 = Obj(r"./assets/objects/teapot.obj") obj5 = Obj(r"./assets/objects/pointer.obj") tex0 = Tex(r"./assets/textures/_default.png") tex1 = Tex(r"./assets/textures/metal.jpg") tex2 = Tex(r"./assets/textures/abstract.jpg") tex3 = Tex(r"./assets/textures/white.png") model0 = Model(obj0, tex0, pos=Point(0.0, 0.0, 0.0), scale=0.8) model1 = Model(obj1, tex2, pos=Point(-1.5, 0.0, 0.0), scale=0.8) model2 = Model(obj2, tex0, pos=Point(0.0, 0.0, 0.0), scale=0.8) model3 = Model(obj3, tex0, pos=Point(0.0, 0.0, 0.0), scale=0.8) model4 = Model(obj4, tex3, pos=Point(10, 10, 10), scale=0.8) model5 = Model(obj5, tex1, pos=Point(0.0, 0.0, 0.0), scale=2.0) camera = Camera(pos=Point(0.0, 0.0, 3.0), rot=Rot(0.0, 0.0, 0.0), fovy=90) scene = Scene({model1, model4, model5}) camera_rotdeltas = { pygame.K_LEFT: Rot(0.0, -0.04, 0.0), pygame.K_RIGHT: Rot(0.0, 0.04, 0.0), pygame.K_DOWN: Rot(-0.04, 0.0, 0.0), pygame.K_UP: Rot(0.04, 0.0, 0.0), pygame.K_COMMA: Rot(0.0, 0.0, -0.04), pygame.K_PERIOD: Rot(0.0, 0.0, 0.04) } camera_posdeltas = { pygame.K_a: Point(-0.1, 0.0, 0.0), pygame.K_d: Point(0.1, 0.0, 0.0), pygame.K_s: Point(0.0, 0.0, 0.1), pygame.K_w: Point(0.0, 0.0, -0.1), pygame.K_f: Point(0.0, -0.1, 0.0), pygame.K_r: Point(0.0, 0.1, 0.0) } while True: clock.tick(60) c.idle() model0.rot += Rot(0.01, 0.02, 0.03) model1.rot += Rot(0.02, 0.03, 0.01) model2.rot += Rot(0.03, 0.01, 0.02) model3.rot += Rot(0.03, 0.02, 0.01) ## model4.rot += Rot(0.01, 0.03, 0.02) model5.rot += Rot(0.02, 0.01, 0.03) # rotate camera from keyboard inputs pygame.event.pump() pressed_keys = pygame.key.get_pressed() for k in camera_rotdeltas: if pressed_keys[k]: camera.rot += camera_rotdeltas[k] rx, ry, rz = camera.rot defacto_rot = Rot(rx, -ry, -rz) for k in camera_posdeltas: if pressed_keys[k]: camera.pos += defacto_rot.get_transmat() * camera_posdeltas[k] X, Y = c.getres() glViewport(0, 0, X, Y) scene.render(camera, aspect=X / Y, mode="full") c.dispbuffer()
# -*- coding: utf-8 -*- """запуск простейшей игры""" from engine import Scene from my_bee import MyBee # импортируем код класса пчелы scene = Scene( # создаем нужную сцену name="My little garden", flowers_count=10, resolution=(1000, 500), ) bee = MyBee() # вот оно - рождение пчелы! scene.go() # и запускаем наш виртуальный мир крутиться... # для запуска соревнования # # scene = Scene( # name="My little garden", # beehives_count=2, # flowers_count=80, # speed=40, # resolution=(1000, 500) # ) # # # from my_bee import MyBee # from my_bee import MyBee as OtherBee # # bees = [MyBee() for i in range(10)] # В классе MyBee должна быть указана команда team = 1 # bees_2 = [OtherBee() for i in range(10)] # В классе OtherBee должна быть указана команда team = 2
def __init__(self): Scene.__init__(self) self.all_sprites_list = pygame.sprite.Group()