Exemple #1
0
def get_body_from_shape(object_shape, object_width, object_height, object_init):
    from simulator_kilobots.kb_lib import Quad, Triangle, Circle, LForm, TForm, CForm
    from Box2D import b2World

    fake_world = b2World()

    if object_shape.lower() in ['quad', 'rect', 'square']:
        return Quad(width=object_width, height=object_height,
                    position=object_init[:2], orientation=object_init[2],
                    world=fake_world)
    elif object_shape.lower() in ['corner_quad', 'corner-quad', 'corner_square', 'corner-square']:
        return CornerQuad(width=object_width, height=object_height,
                          position=object_init[:2], orientation=object_init[2],
                          world=fake_world)
    elif object_shape.lower() == 'triangle':
        return Triangle(width=object_width, height=object_height,
                        position=object_init[:2], orientation=object_init[2],
                        world=fake_world)
    elif object_shape.lower() == 'circle':
        return Circle(radius=object_width, position=object_init[:2],
                      orientation=object_init[2], world=fake_world)
    elif object_shape.lower() == 'l_shape':
        return LForm(width=object_width, height=object_height,
                     position=object_init[:2], orientation=object_init[2],
                     world=fake_world)
    elif object_shape.lower() == 't_shape':
        return TForm(width=object_width, height=object_height,
                     position=object_init[:2], orientation=object_init[2],
                     world=fake_world)
    elif object_shape.lower() == 'c_shape':
        return CForm(width=object_width, height=object_height,
                     position=object_init[:2], orientation=object_init[2],
                     world=fake_world)
 def __init__(self, import_file, world=None):
     # hacky way of allowing xmlStr to be passed as arg
     try:
         with open(import_file, 'r') as content_file:
             self.xmlStr = content_file.read()
             self.file = os.path.basename(import_file)
             self.file = os.path.splitext(self.file)
             # we save the filename with the epoch after the final underscore
             f = self.file[0]
             self.epoch = int(
                 f[f.rfind("_") +
                   1:])  # rfind is lastIndexOf, [i:] slice str after i
             self.cfgname = f[:f.rfind("_")]
     except FileNotFoundError:
         self.xmlStr = import_file
         # epoch cannot be determined from content
         self.epoch = None
     if world is None:
         self.world = b2World()
         self.world.userData = SimData()
     else:
         self.world = world
     # set the default options that we set to each world
     GenWorld(self.world)
     self.world.userData.step = self.epoch
     n, t, dt = xml_2_b2world(self.xmlStr)
     self.world.userData.name = n
     self.world.userData.sim_t = t
     self.world.userData.dt = dt
Exemple #3
0
    def __init__(self, bounds, controllers, debug=0):
        self.scene = self.SCENE_TITLE

        self.bounds = bounds
        self.debug = debug

        self.window_x = 0
        self.window_y = 0

        self.stage = None

        self.physicsWorld = b2World(gravity=(0, 0),
                                    contactListener=ContactListener())
        # Physical bodies should be deleted outside the simulation step.
        self.physics_to_delete = []

        self.players = []
        self.entities = []

        def batch(iterable, n=1):
            l = len(iterable)
            for ndx in range(0, l, n):
                yield iterable[ndx:min(ndx + n, l)]

        self.asteroids = []
Exemple #4
0
    def __init__(self, **kwargs):
        self.__sim_steps = 0
        self.__reset_counter = 0

        # create the Kilobots world in Box2D
        self.world = b2World(gravity=(0, 0), doSleep=True)
        self.table = self.world.CreateStaticBody(position=(.0, .0))
        self.table.CreateFixture(
            shape=b2ChainShape(vertices=[(_world_scale * self.world_x_range[0], _world_scale * self.world_y_range[1]),
                                         (_world_scale * self.world_x_range[0], _world_scale * self.world_y_range[0]),
                                         (_world_scale * self.world_x_range[1], _world_scale * self.world_y_range[0]),
                                         (_world_scale * self.world_x_range[1], _world_scale * self.world_y_range[1])]))
        self._real_time = False

        # add kilobots
        self._kilobots: [Kilobot] = []
        # add objects
        self._objects: [Body] = []
        # add light
        self._light: Light = None

        self.__seed = 0

        self._screen = None
        self.render_mode = 'human'
        self.video_path = None

        self._configure_environment()

        self._step_world()
Exemple #5
0
    def __init__(self):
        self._seed()
        self.viewer = None  # to be used later for rendering

        # Gravity set to 0; assuming that the plane is flat
        self.world = b2World(gravity=[0, 0], doSleep=True)
        self.exterior_box = None
        self.object = None
        self.first_link = None
        self.second_link = None
        self.actuator_mount = None
        self.tip = None

        # Observation Space
        # [object posx, object posy, joint1 angle, joint2 angle, joint1 angular speed, joint2 angular speed]
        # Note: potentially add 'ball in touch with end effector'
        high = np.array([np.inf] * 6)
        self.observation_space = spaces.Box(low=-high, high=high)

        # Continuous action space; one for each joint
        # action space represents angular velocity
        self.action_space = spaces.Box(-1, 1, (2, ))

        self.prev_shaping = None  # for reward calculation
        self.drawlist = []  # for rendering

        self._reset()
Exemple #6
0
def copyWorld(world):
    copy = b2World(gravity=world.gravity, doSleep=world.allowSleeping)

    copy.continuousPhysics = world.continuousPhysics

    copy.velocityThreshold = world.velocityThreshold
    copy.positionThreshold = world.positionThreshold

    for body in world.bodies:
        fixtures = []
        for fixture in body.fixtures:
            fixtures.append(
                b2FixtureDef(shape=fixture.shape,
                             density=fixture.density,
                             restitution=fixture.restitution,
                             friction=fixture.friction))

        copy.CreateBody(type=body.type,
                        fixtures=fixtures,
                        userData=body.userData,
                        position=b2Vec2(body.position.x, body.position.y),
                        angle=body.angle,
                        linearVelocity=b2Vec2(body.linearVelocity.x,
                                              body.linearVelocity.y),
                        angularVelocity=body.angularVelocity)

    for body in copy.bodies:
        body.sleepingAllowed = False

    return copy
Exemple #7
0
    def __init__(self):
        self._seed()
        self.viewer = None  # to be used later for rendering

        self.count = 0

        self.world = b2World(gravity=[0, GRAVITY], doSleep=True)
        self.exterior_box = None
        # Five linear actuators
        self.actuator_list = []
        # Object to be manipulated
        self.object = None
        # Linkages
        if self.with_linkage:
            self.link_left_list = []  # four links
            self.link_right_list = []  # four links

        self.prev_state = None

        # Drawlist for rendering
        self.drawlist = []

        # Observation Space
        # [object posx, object posy, actuator1 pos.y, ... , actuator5 pos.y, actuator1 speed.y, ... , actuator5 speed.y]
        high = np.array([np.inf] * 14)
        self.observation_space = spaces.Box(low=-high, high=high)

        # Continuous action space; one for each linear actuator (5 total)
        # action space represents velocity
        self.action_space = spaces.Box(-1, 1, (5, ))
        self.prev_shaping = None  # for reward calculation

        self._reset()
def setup_world():
    world_bounds = b2AABB()
    world_bounds.lowerBound = (-200, -1000)
    world_bounds.upperBound = (200, 200)
    world = b2World(
        world_bounds,
        b2Vec2(0, -30),  # Gravity vector
        True  # Use "sleep" optimisation
    )

    wallsdef = b2BodyDef()
    walls = world.CreateBody(wallsdef)
    walls.userData = 'Blocks'

    WALLS = [
        (W, FLOOR * 0.5, (W / 2, FLOOR * 0.5), 0),  # floor
        (W / 2, 1, (W / 2, H + 1), 0),  # ceiling
        (1, 600, (-1, -500), 0),  # left wall
        (1, 600, (W + 1, -500), 0),  # right wall
    ]

    for wall in WALLS:
        shape = b2PolygonDef()
        shape.SetAsBox(*wall)
        walls.CreateShape(shape)

    return world
Exemple #9
0
 def __init__(self,new_display):
     self.b2_game_world = b2World()  # default gravity is (0,-10) and doSleep is True
     self.groundBody = self.b2_game_world.CreateStaticBody(position=(0, -48),
                                 shapes=b2PolygonShape(box=(80, 10)),
                                 )
     # Create a dynamic body at (0, 4)
  
     self.game_display = new_display
Exemple #10
0
 def __init__(self, width, height):
     self.render_list = []
     aabb = b2AABB()
     aabb.lowerBound = (-width, -height)
     aabb.upperBound = (width, height)
     gravity = (0, -10)
     do_sleep = True
     self.world = b2World(aabb, gravity, do_sleep)
Exemple #11
0
    def __init__(self, bounds, controllers, stage, debug=0):
        self.scene = self.SCENE_TITLE
        self.game_over_timer = 0
        self.stage = stage

        self.game_over_quad = QuadDrawable(
            SCREEN_WIDTH / 2 - 496 / 2,
            SCREEN_HEIGHT / 2 - 321 / 2,
            496,
            321,
        )
        self.game_over_quad.texture = Texture.load_from_file(
            'resources/images/game_over.png')

        self.bounds = bounds
        self.debug = debug

        self.window_x = 0
        self.window_y = 0

        self.physicsWorld = b2World(gravity=(0, 0),
                                    contactListener=ContactListener())
        # Physical bodies should be deleted outside the simulation step.
        self.physics_to_delete = []
        self._shapes = Shapes()

        self.controllers = controllers

        self.bullet_mgr = bullet_mgr = BulletManager(self)

        self.players = []
        self.entities = [bullet_mgr]

        def batch(iterable, n=1):
            l = len(iterable)
            for ndx in range(0, l, n):
                yield iterable[ndx:min(ndx + n, l)]

        quadrant = 0
        for cs in batch(controllers, 3):
            x = 300 + (SCREEN_WIDTH -
                       600) * (quadrant & 1) + 100 * random.uniform(-1, 1)
            y = 200 + (SCREEN_HEIGHT -
                       400) * (quadrant >> 1 & 1) + 50 * random.uniform(-1, 1)
            ship = Ship(
                self,
                bullet_mgr,
                controllers=cs,
                x=x,
                y=y,
                # angle=math.degrees(math.atan2(y, x)) - 180
                color=SHIP_TEXTURES[list(SHIP_TEXTURES.keys())[quadrant]],
            )
            self.players.append(ship)
            self.entities.append(ship)
            quadrant += 1

        self.asteroids = []
Exemple #12
0
def make_world():
    """
	Creates a new physical world.

	Returns:
		The newly created world.
	"""
    world = b2World(gravity=(0, 0), doSleep=False)
    return world
Exemple #13
0
def make_world():
	"""
	Creates a new physical world.

	Returns:
		The newly created world.
	"""
	world = b2World(gravity=(0,0), doSleep=False)
	return world
Exemple #14
0
    def setup_physics(self):
        from threading import Timer
        from Box2D import b2World

        self.physics_update_time = 1 / 10.0
        self.vel_iters = 6
        self.pos_iters = 2
        self.world = b2World(gravity=(0, 0), doSleep=True)
        
        Timer(self.physics_update_time, self.update_physics)
Exemple #15
0
    def __init__(self):
        pygame_sdl2.init()
        pygame_sdl2.key.set_repeat(1, 10)
        self.windowSurface = pygame_sdl2.display.set_mode((500, 400), 0, 32)

        pygame_sdl2.display.set_caption('Swing Proto')
        clock = pygame_sdl2.time.Clock()
        clock.tick(self.FRAMES_PER_SECOND)
        self.running = False
        self.world = b2World(gravity=(0, -10), doSleep=True)
        self.player = Player(self.world)
Exemple #16
0
    def init_physics(self):
        self.world = b2World(gravity=(0, 0))
        self.ball.register_in_world(self.world, self.friction)

        for player in self.home_team.players:
            player.register_in_world(self.world, self.friction)

        for player in self.away_team.players:
            player.register_in_world(self.world, self.friction)

        self.field.register_in_world(self.world)
Exemple #17
0
    def __init__(self):
        super(FrameworkBase, self).__init__()
        self.__reset()

        # Box2D Initialization
        self.world = b2World(gravity=(0, -10), doSleep=True)

        self.destructionListener = fwDestructionListener(test=self)
        self.world.destructionListener = self.destructionListener
        self.world.contactListener = self
        self.t_steps, self.t_draws = [], []
Exemple #18
0
 def __init__(self):
     pygame_sdl2.init()
     pygame_sdl2.key.set_repeat(1, 10)
     self.windowSurface = pygame_sdl2.display.set_mode((500, 400), 0, 32)
     
     pygame_sdl2.display.set_caption('Swing Proto')
     clock = pygame_sdl2.time.Clock()
     clock.tick(self.FRAMES_PER_SECOND)
     self.running = False
     self.world = b2World(gravity=(0, -10), doSleep=True)
     self.player = Player(self.world)
Exemple #19
0
def init_helper(env_obj):
    env_obj.world = b2World(gravity=[0, GRAVITY], doSleep=True)

    env_obj.exterior_box = None
    # Five linear actuators
    env_obj.actuator_list = []
    # Linkages
    env_obj.link_left_list = []  # four links
    env_obj.link_right_list = []  # four links
    # Drawlist for rendering
    env_obj.drawlist = []
Exemple #20
0
    def __init__(self):
        super(FrameworkBase, self).__init__()

        self.__reset()

        # Box2D Initialization
        self.world = b2World(gravity=(0, -10), doSleep=True)

        self.destructionListener = fwDestructionListener(test=self)
        self.world.destructionListener = self.destructionListener
        self.world.contactListener = self
        self.t_steps, self.t_draws = [], []
    def __init__(self, do_gui=False):
        self.world = b2World(gravity=(0.0, 0.0), doSleep=True)
        self.do_gui = do_gui
        self.TARGET_FPS = 100
        self.TIME_STEP = 1.0 / self.TARGET_FPS
        self.VEL_ITERS, self.POS_ITERS = 10, 10
        self.bodies = []

        if do_gui:
            self.gui_world = GuiWorld(self.TARGET_FPS)
            # raw_input()
        else:
            self.gui_world = None
Exemple #22
0
 def __init__(self, camera, luObserver, fxObserver, lvl):
     self.mSwitch = True
     self.mTimer = 0.0
     self.mLevelDone = False
     self.mCamera = camera
     self.mLuObs = luObserver
     self.mFxObs = fxObserver
     self.contactListener = ContactListener()
     self.gravity = Gravity()
     self.physWorld = b2World(gravity=(0,0),doSleep=True, contactListener=self.contactListener)
     self.level = Level(self.physWorld, self.gravity, lvl)
     self.player = Player(self.level.mStartPos, self.physWorld, self.gravity)
     self.mEntityToFollow = self.player
Exemple #23
0
    def __init__(self, title):
        pygame.init()
        pygame.display.set_caption(title)

        self.running = False
        self.clock = pygame.time.Clock()
        self.renderer = Renderer()
        self.world = b2World(gravity=(0, -10), doSleep=True)
        self.renderer.setupDebugDraw(self.world)
        self.gameObjects = []

        body = self.world.CreateDynamicBody(position=(10, -10))
        box = body.CreatePolygonFixture(box=(1, 1), density=1, friction=0.3)
        self.player = self.createObject(physics=box)
Exemple #24
0
    def __init__(self, title):
        pygame.init()
        pygame.display.set_caption(title)
        
        self.running = False
        self.clock = pygame.time.Clock()
        self.renderer = Renderer()
        self.world = b2World(gravity=(0,-10), doSleep=True)
        self.renderer.setupDebugDraw(self.world)
        self.gameObjects = []

        body = self.world.CreateDynamicBody(position=(10,-10))
        box = body.CreatePolygonFixture(box=(1,1), density=1, friction=0.3)
        self.player = self.createObject(physics=box)
Exemple #25
0
 def buildWorld(self):
     SCALE = ControlSystem.MODEL_SCALE
     world = b2World(gravity=b2Vec2(0.0, -9.81) * SCALE,
                     doSleep=True,
                     contactListener=self)
     bodies = []
     ''' STATICS '''
     self.ground_body = world.CreateStaticBody(position=b2Vec2(1, .050) *
                                               SCALE)
     self.ground_body.CreatePolygonFixture(box=b2Vec2(1, 0.025) * SCALE,
                                           friction=5.)
     bodies.append(self.ground_body)
     self.platform = world.CreateStaticBody(position=b2Vec2(1.25, .2) *
                                            SCALE)
     self.platform.CreatePolygonFixture(
         box=b2Vec2(ControlSystem.objDim.x, 0.025) * SCALE, friction=5.)
     bodies.append(self.platform)
     self.obstacle = world.CreateStaticBody(position=b2Vec2(.8, .2) * SCALE)
     self.obstacle.CreatePolygonFixture(box=b2Vec2(.025, 0.025) * SCALE,
                                        friction=5.)
     bodies.append(self.obstacle)
     ''' FINGERS '''
     self.fLeft = world.CreateDynamicBody(position=self.refL,
                                          angle=0,
                                          linearVelocity=b2Vec2(0, 0))
     self.fLeft.fixedRotation = True
     self.fLeft.CreatePolygonFixture(box=b2Vec2(.02, .05) * SCALE,
                                     **ControlSystem.fingerDyn)
     bodies.append(self.fLeft)
     self.fRight = world.CreateDynamicBody(position=self.refR,
                                           angle=0,
                                           linearVelocity=b2Vec2(0, 0))
     self.fRight.fixedRotation = True
     self.fRight.CreatePolygonFixture(box=b2Vec2(.02, .05) * SCALE,
                                      **ControlSystem.fingerDyn)
     bodies.append(self.fRight)
     ''' OBJECT '''
     self.object = world.CreateDynamicBody(position=b2Vec2(.5, .1) * SCALE,
                                           angle=0,
                                           linearVelocity=b2Vec2(0, 0))
     self.object.CreatePolygonFixture(box=ControlSystem.objDim * SCALE,
                                      **self.objDynProps)
     self.object.linearDamping = 0.0
     self.object.angularDamping = 0.01
     bodies.append(self.object)
     print "mass %f" % self.object.mass
     self.bodies = bodies
     return world
    def __init__(self,
                 boxes,
                 boxes_density,
                 boxes_restitution,
                 boxes_friction,
                 boxes_pos,
                 boxes_angle,
                 grip_strength,
                 gravity = (0, -9.81),
                 timestep = 1.0/10,
                 vel_iters = 10,
                 pos_iters = 8):

        # init box2d world
        self.world = b2World(gravity = gravity, doSleep = True)

        # gripper max force
        self.grip_strength = grip_strength

        # set simulation parameters
        self.timestep = timestep
        self.vel_iters = vel_iters
        self.pos_iters = pos_iters

        # initialize all the boxes
        self.box_bodies = []
        self.box_fixtures = []
        for b, d, r, f, p, a in zip(boxes,
                               boxes_density,
                               boxes_restitution,
                               boxes_friction,
                               boxes_pos,
                               boxes_angle):
            self.box_bodies.append(self.world.CreateDynamicBody(position = p,
                                                                angle = a))
            fixture = self.box_bodies[-1].CreatePolygonFixture(box=b,
                                                             density = d,
                                                             friction = f,
                                                             restitution = r)
            self.box_fixtures.append(fixture)

        # initialize the floor
        self.floor_body = self.world.CreateStaticBody(
                                    position = (0,0),
                                    shape = b2PolygonShape(box = (50,2))
                                    )
Exemple #27
0
 def __init__(self, root_layer, camera_config, gravity=(0, 0, 0)):
     self._camera = Camera(
         target=camera_config['target'],
         width=camera_config['width'],
         rect=camera_config['rect'],
         limits=camera_config['limits'],
     )
     self._root_layer = root_layer
     self._chunks = []
     worldAABB = b2AABB()
     worldAABB.lowerBound = (-1000, -1000)
     worldAABB.upperBound = (1000, 1000)
     gravity_x, gravity_y = gravity
     gravity = b2Vec2(gravity_x, gravity_y)
     self._box2d_world = b2World(worldAABB, gravity, True)
     self._contact_listener = ContactListener()
     self._box2d_world.SetContactListener(self._contact_listener)
     self._remove_list = []
Exemple #28
0
def createPlanarWorld(gravity):
    """
    world, bodies = create_planar_world(gravity = 9.81)
    """
    world = b2World(gravity=(0, -gravity), doSleep=False)
    world.warmStarting = True
    world.continuousPhysics = True
    world.subStepping = False

    # And a static body to hold the ground shape
    ground_body = world.CreateStaticBody(
        position=(0, 0),
        shapes=b2PolygonShape(box=(50, 1)),
    )
    ground_body.userData = 'ground'

    goal_upper = world.CreateStaticBody(
        position=(0, 0),
        shapes=b2PolygonShape(box=(5, .001)),
    )
    goal_upper.userData = 'boundsU'

    goal_lower = world.CreateStaticBody(
        position=(0, 0),
        shapes=b2PolygonShape(box=(5, .001)),
    )
    goal_lower.userData = 'boundsL'

    # Create a ball to bounce
    ball = world.CreateDynamicBody(position=(0, 0), angle=0)
    ball.CreateCircleFixture(radius=.5, density=.1, friction=0.)
    ball.userData = 'ball'

    # Construct the robot paddle
    robot = world.CreateDynamicBody(position=(0, 0), angle=0)
    robot.CreatePolygonFixture(box=(5, .1), density=1., friction=0.)
    robot.userData = 'robot'

    bodies = {}
    for body in world.bodies:
        bodies[body.userData] = body

    return world, bodies
Exemple #29
0
 def setupPlayground(self):
     # libavg setup        
     self.display = avg.DivNode(parent=self._parentNode, size=self._parentNode.size)
     self.renderer = Renderer()     
     background = avg.ImageNode(parent=self.display)
     background.setBitmap(self.backgroundpic) 
     self.display.player = None
     (displayWidth, displayHeight) = self.display.size
     widthThird = (int)(displayWidth / 3)
     fieldSize = (widthThird, displayHeight)
     self.field1 = avg.DivNode(parent=self.display, size=fieldSize)
     self.field2 = avg.DivNode(parent=self.display, size=fieldSize, pos=(displayWidth - widthThird, 0))
     avg.LineNode(parent=self.display, pos1=(0, 1), pos2=(displayWidth, 1))
     avg.LineNode(parent=self.display, pos1=(0, displayHeight), pos2=(displayWidth, displayHeight))   
     self.lines.createImageNode('layer1', dict(parent=self.display, pos=(widthThird, 0)), (2, displayHeight))
     self.lines.createImageNode('layer1', dict(parent=self.display, pos=(displayWidth - widthThird, 0)), (2, displayHeight))  
     # pybox2d setup
     self.world = b2World(gravity=(0, 0), doSleep=True)
     self.hitset = set()
     self.listener = ContactListener(self.hitset)
     self.world.contactListener = self.listener
     self.running = True
     pointsToWin = 999 if self.tutorialMode else config.pointsToWin
     self.leftPlayer, self.rightPlayer = Player(self, self.field1, pointsToWin), Player(self, self.field2, pointsToWin)
     self.leftPlayer.other, self.rightPlayer.other = self.rightPlayer, self.leftPlayer    
     # horizontal lines
     BorderLine(self.world, a2w((0, 1)), a2w((displayWidth, 1)), 1, False, 'redball')
     BorderLine(self.world, a2w((0, displayHeight)), a2w((displayWidth, displayHeight)), 1, False, 'redball')
     # vertical ghost lines
     maxWallHeight = brickSize * brickLines * PPM
     BorderLine(self.world, a2w((maxWallHeight, 0)), a2w((maxWallHeight, displayHeight)), 1, False, 'redball', 'ball') 
     BorderLine(self.world, a2w((displayWidth - maxWallHeight - 1, 0)), a2w((displayWidth - maxWallHeight - 1, displayHeight)), 1, False, 'redball', 'ball')
     self.middleX, self.middleY = self.display.size / 2
     self.middle = a2w((self.middleX, self.middleY))
     BatManager(self.field1, self.world, self.renderer)
     BatManager(self.field2, self.world, self.renderer)
     self.bonus = None
     self.balls = []
     self.redballs = []
     self.towers = []
     self.ghosts = []
     self.mainLoop = g_player.setOnFrameHandler(self.step)
    def __init__(self):
        # Called once per game, when game starts

        self.world = b2World(
        )  # default gravity is (0,-10) and doSleep is True

        # terrain_locations = [(1, 0),
        #                      (2, 0),
        #                      (5, 0,),
        #                      (10, 0)]
        #
        # self.terrain = shapes.create_terrain('water', terrain_locations, self.world)

        # Create an object that moves in the box2d world and can be rendered to the screen
        #self.many_shapes = [ shapes.LLeftShape(self.world, (random()*100 - 50, random()*30)) for x in range(1,100) ]
        self.demo_shape = shapes.LLeftShape(self.world, (5, 5))

        # A box2d object that doesn't move and isn't rendered to screen
        body_bottom_wall = self.world.CreateStaticBody(
            position=(0, -10),
            shapes=b2PolygonShape(box=(SCREEN_WIDTH / 2, 5)))
Exemple #31
0
def eval_genome(genome, config):
    net = neat.nn.FeedForwardNetwork.create(genome, config)

    controller = NeuralNetworkController(net)

    fitnesses = []

    eps = 0.00000001

    for runs in range(runs_per_net):
        system = cart_pendulum_demo.CartPendulumSystem(b2World(),
                                                       controller,
                                                       initial_rotation=0)
        system.print_state = False

        steps = 0

        f2_fitnesses = []

        while steps < simulation_steps:
            system.step(True)

            if not system.in_legal_state():
                break

            f2_fitnesses.append(
                1.0 / (abs(system.x) + abs(system.theta) + abs(system.dx) +
                       abs(system.dtheta) + eps))
            steps += 1

        # two tier fitness scheme to make sure we at least get to having long-term balancers
        if steps >= simulation_steps:
            fitness = steps + sum(f2_fitnesses)
        else:
            fitness = steps

        fitnesses.append(fitness)

    # The genome's fitness is its worst performance across all runs.
    return min(fitnesses)
def setup_world():
    global buoyancy
    world_bounds = b2AABB()
    world_bounds.lowerBound = (-200, -100)
    world_bounds.upperBound = (1000, 1000)
    world = b2World(
        world_bounds,
        b2Vec2(0, -30),  # Gravity vector
        True  # Use "sleep" optimisation
    )

    wallsdef = b2BodyDef()
    walls = world.CreateBody(wallsdef)
    walls.userData = 'Blocks'

    WALLS = [
        #(W, FLOOR * 0.5, (W / 2, FLOOR * 0.5), 0),  # floor
        #(W / 2, 1, (W / 2, H + 1), 0),  # ceiling
        (1, 600, (-1, -500), 0),  # left wall
        #(1, 600, (W + 1, -500), 0),  # right wall
    ]

    for wall in WALLS:
        shape = b2PolygonDef()
        shape.SetAsBox(*wall)
        walls.CreateShape(shape)

    for shape in read_shapes_from_svg('shapes/ground.svg'):
        walls.CreateShape(shape)

    buoyancydef = b2BuoyancyControllerDef()
    buoyancydef.normal = b2Vec2(0, 1)
    buoyancydef.offset = WATER_LEVEL
    buoyancydef.density = 2.5
    buoyancydef.angularDrag = 0.5
    buoyancydef.linearDrag = 3
    buoyancy = world.CreateController(buoyancydef)

    return world
    def __init__(self, verbose=False):
        EzPickle.__init__(self)

        # General and utils variables
        self.verbose = verbose
        self.np_random = None
        self.seed()

        # Box2D variables
        self.time = -1.0  # Set time to -1.0 to indicate that models is not ready yet
        self.car = None
        self.contact_listener = ContactListener(self)
        self.world = b2World((0, 0), contactListener=self.contact_listener)
        self.ground = None
        self.track_tiles_coordinates = None  # For easy access in StateTransformer
        self.track_tiles = []
        self.cones = []
        self.tile_visited_count = 0

        # PyGLet variables
        self.viewer = None
        self.invisible_state_window = None
        self.invisible_video_window = None
        self.score_label = None
        self.transform = None

        # RL-related variables
        # action_space has the following structure (steer, gas, brake). -1, +1 is for left and right steering
        self.state = None
        self.done = False
        self.action_space = spaces.Box(np.array([-1, 0, 0]),
                                       np.array([+1, +1, +1]),
                                       dtype=np.float32)
        self.observation_space = spaces.Box(low=0,
                                            high=255,
                                            shape=(STATE_H, STATE_W, 3),
                                            dtype=np.uint8)
        self.reward = 0.0
        self.prev_reward = 0.0
	def __init__(self, net=False, physics=False):
		self.entities = {}
		self.groups = {}
		self.updates = []
		self.renders = []
		self.time = 0

		self.camera = Camera()

		self.window = None
		self.keys = None

		self.net = net
		if self.net:
			from client import Client
			self.client = Client()
		self.net_data = []

		self.physics = physics
		if self.physics:
			from Box2D import b2World
			self.world = b2World(gravity=(0, 0), doSleep=True)

		self.running = False
TIME_STEP=1.0/FPS
SCREEN_WIDTH, SCREEN_HEIGHT=640 ,480

# Box2D Iterations
VELOCITY_ITERATION = 10
POSITION_ITERATION = 10

# --- pygame setup ---
pygame.init()
screen=pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT),0, 32)
pygame.display.set_caption('Dinosaurs In Space!')

# --- pybox2d world setup ---
# Create the world
GRAVITY = -10
world=b2World(gravity=(0,GRAVITY),doSleep=False)

# --- pygame.mixer setup ---
pygame.mixer.init()
#TODO: Tweak for latency vs channels and verify this works - CP
pygame.mixer.set_num_channels(10)

# TODO: These function have, by far, the shittiest, most f*****g confusing names - CP
def pixelsToWorld(pixels):
    worldPosition = (pixels[0] / PPM, (SCREEN_HEIGHT - pixels[1]) / PPM)
    return worldPosition

def pixelsToVelocity(pixels):
    worldPosition = (pixels[0] / PPM, pixels[1] / PPM)
    return worldPosition
Exemple #36
0
import math
from random import randint
import sys

from Box2D import b2Shape, b2World
from pygame import init, display, draw, event, locals, Color
from pygame.time import Clock

w_width, w_height = 800, 600
black = Color(0, 0, 0)
world = b2World(gravity=(0, 9.8))
actors, colors = [], []
PPM = 64.0  # Pixels per Meter


def add_rect_body(kind, x, y, width, height, angle=0.0, mass=1.0, rest=0.0,
                  frict=0.75):
    body_factory = {
        'static': world.CreateStaticBody,
        'dynamic': world.CreateDynamicBody,
    }[kind]

    body = body_factory(position=(x/PPM, y/PPM), angle=angle, mass=mass)
    body.CreatePolygonFixture(box=(width/PPM, height/PPM), density=1,
                              friction=frict, restitution=rest)
    return body


def ground_arc(radius, segments, centerX, centerY):
    angle_incr = math.pi/(2.0*segments)
    for i in range(segments):
Exemple #37
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This is a simple example of building and running a simulation using Box2D. Here
we create a large ground box and a small dynamic box.

** NOTE **
There is no graphical output for this simple example, only text.
"""

from Box2D import b2PolygonShape, b2World

world = b2World()  # default gravity is (0,-10) and doSleep is True
groundBody = world.CreateStaticBody(position=(0, -10), shapes=b2PolygonShape(box=(50, 10)))

# Create a dynamic body at (0, 4)
body = world.CreateDynamicBody(position=(0, 4))

# And add a box fixture onto it (with a nonzero density, so it will move)
box = body.CreatePolygonFixture(box=(1, 1), density=1, friction=0.3)

# Prepare for simulation. Typically we use a time step of 1/60 of a second
# (60Hz) and 6 velocity/2 position iterations. This provides a high quality
# simulation in most game scenarios.
timeStep = 1.0 / 60
vel_iters, pos_iters = 6, 2

# This is our little game loop.
for i in range(60):
    # Instruct the world to perform a single step of simulation. It is
Exemple #38
0
r = (1, 1)

# Timestep
timeStep = 1.0 / 100
# Iteration limits
velocityIterations = 5000
positionIterations = 2500
# Iteration thresholds
velocityThreshold = 6*10**-5
positionThreshold = 2*10**-5
# Number of steps
steps = 600


# Create world in case model needs it
world = b2World()
# Fill world with static box and circles
new_confined_clustered_circles_world(world, nBodies, b2Vec2(xlow, ylow), b2Vec2(xhi, yhi), r, sigma_coef, seed)

# Choose a model
model = None
#model = BuiltinWarmStartModel()
#model = BadModel()
#model = RandomModel(0)
#model = ParallelWorldModel(world)
#model = CopyWorldModel()
#model = IdentityGridModel((xlow, ylow), (xhi, yhi), 0.25, 0.25, 1)
#model = NNModel(CNN({}))


# Iteration counter plots
from .dataframes import dataframes_from_b2World

# Number of worlds to generate
nWorlds = 25
# Number of bodies in world
nBodies = 50
# Something about spread of bodies?
sigma_coef = 1.2
# Dimension of static box
p_ll = (0, 0)
p_ur = (10, 10)
# Radius of bodies
r = (0.5, 0.5)

# Create worlds
worlds = [b2World() for _ in range(nWorlds)]
# Fill worlds with static box and circles
for i in range(nWorlds):
    new_confined_clustered_circles_world(worlds[i], nBodies, b2Vec2(p_ll),
                                         b2Vec2(p_ur), r, sigma_coef, i)
# Simulate 200 steps for worlds
for w in worlds:
    for j in range(200):
        w.Step(0.01, 10, 10)

# Determine original totals - change attribute here if wanted
originals = []
for w in worlds:
    original = 0
    for b in w.bodies:
        original += b.mass
Exemple #40
0
    def __init__(self, obstacles, **kargs):
        # --------------------------------------------------- #
        # set parameters
        # --------------------------------------------------- #
        robot_pos = kargs.get('robot_pos', (0, 0))
        robot_angle = kargs.get('robot_angle', 0)
        robot = kargs.get('robot', DefaultRobot())
        robot_linear_damping = kargs.get('robot_linear_damping', 0.9)
        robot_angluar_damping = kargs.get('robot_angluar_damping', 0.99)
        robot_restitution = kargs.get('robot_restitution', 0.1)

        # world limit should be a list with two tuple. The coordinates
        # of the bottom left limit and of the top right limit
        world_limits = kargs.get('world_limit', None)

        # Parameters for the Simulation, avoid changing these while the
        # simulation is running.

        # Simulated elapsed time per step, increasing this sacrifices accuracy
        # for more performance
        self.timestep = kargs.get('timestep', 1 / 10)
        # number of iterations of the solvers, lowering this sacrifices accuracy
        # for more performance
        self.vel_iters = kargs.get('vel_iters', 10)
        self.pos_iters = kargs.get('pos_iters', 8)
        # --------------------------------------------------- #

        # initialize an empty world
        if isinstance(robot, b2ContactListener):
            self.world = b2World(contactListener=robot,
                                 gravity=(0, 0),
                                 doSleep=True)
        else:
            self.world = b2World(gravity=(0, 0), doSleep=True)

        # create obstacle shapes from list of vertex list
        self.__obstacle_vertices = obstacles
        shapes = [b2ChainShape(vertices_loop=v) for v in obstacles]

        # if limits were specified, create obstacle boundary
        if world_limits != None:
            v = [
                world_limits[0], (world_limits[1][0], world_limits[0][1]),
                world_limits[1], (world_limits[0][0], world_limits[1][1])
            ]
            shapes.append(b2ChainShape(vertices_loop=v))

        # create an unmovable entity. This will represent all obstacles
        self.obstaclebody = self.world.CreateStaticBody(shapes=shapes)

        # package the robot physical properties (for collisions)
        # The robot constructor can choose to ignore them
        param = {
            'position': robot_pos,
            'angle': robot_angle,
            'linearDamping': robot_linear_damping,
            'angularDamping': robot_angluar_damping,
            'restitution': robot_restitution
        }

        # create the robot entity
        self.robotbody = robot.attachRobotBody(self.world, **param)
        self.robot = robot
        self.inputs = robot.getDefaultInput()
Exemple #41
0

def draw_line(surface, x1, y1, x2, y2):
    color = sdl2.ext.Color(255, 255, 255)
    sdl2.ext.line(surface, color, (x1, y1, x2, y2))


def draw_rect(surface, x, y, width, height):
    color = sdl2.ext.Color(255, 0, 0)
    sdl2.ext.fill(surface, color,
                  ((x - width / 2) * 10,
                   (y - height / 2) * 10, width * 10, height * 10))


contact_listener = ContactListener()
physicsWorld = b2World(gravity=(0, 0), contactListener=contact_listener)

pShip = PhysicsShip(object(), physicsWorld, 50, 50)
pShip2 = PhysicsShip(object(), physicsWorld, 80, 80)
pShield = PhysicsShield(object(), physicsWorld, Vector2(60, 60), 20)
# pBullet = PhysicsBullet(object(), physicsWorld, 10, 20, 8, 13)
pAsteroid = PhysicsAsteroid(object(), physicsWorld, 100, 100)

sdl2.ext.init()
window = sdl2.ext.Window("2D drawing primitives", size=(1920, 1080))
window.show()

windowsurface = window.get_surface()


def draw_polygon(screen, body, polygon):
def init_physics():
    defines.world = b2World(gravity=(0,0), doSleep=True)  # default gravity is (0,-10) and doSleep is True
    defines.world.using_contacts = True
Exemple #43
0
 def __init__(self, terrain=None, car=None):
     self.world = world = b2World()
     world.CreateStaticBody(shapes=terrain)
     self.car, wheels, springs = create_vehicle(world, *car)
Exemple #44
0
    def __init__(self, obstacles, **kargs):
        # --------------------------------------------------- #
        # set parameters
        # --------------------------------------------------- #
        robot_pos = kargs.get('robot_pos', (0,0))
        robot_angle = kargs.get('robot_angle', 0)
        robot = kargs.get('robot', DefaultRobot())
        robot_linear_damping = kargs.get('robot_linear_damping', 0.9)
        robot_angluar_damping = kargs.get('robot_angluar_damping', 0.99)
        robot_restitution = kargs.get('robot_restitution', 0.1)

        # world limit should be a list with two tuple. The coordinates
        # of the bottom left limit and of the top right limit
        world_limits = kargs.get('world_limit', None)


        # Parameters for the Simulation, avoid changing these while the
        # simulation is running.

        # Simulated elapsed time per step, increasing this sacrifices accuracy
        # for more performance
        self.timestep = kargs.get('timestep', 1/10)
        # number of iterations of the solvers, lowering this sacrifices accuracy
        # for more performance
        self.vel_iters = kargs.get('vel_iters', 10)
        self.pos_iters = kargs.get('pos_iters', 8)
        # --------------------------------------------------- #



        # initialize an empty world
        if isinstance(robot, b2ContactListener):
            self.world = b2World(contactListener = robot,
                                  gravity = (0,0),
                                  doSleep = True)
        else:
            self.world = b2World(gravity = (0,0), doSleep = True)

        # create obstacle shapes from list of vertex list
        self.__obstacle_vertices = obstacles
        shapes = [ b2ChainShape(vertices_loop = v) for v in obstacles]

        # if limits were specified, create obstacle boundary
        if world_limits != None:
            v= [world_limits[0], (world_limits[1][0], world_limits[0][1]),
                   world_limits[1],  (world_limits[0][0], world_limits[1][1])]
            shapes.append(b2ChainShape(vertices_loop = v))

        # create an unmovable entity. This will represent all obstacles
        self.obstaclebody = self.world.CreateStaticBody(shapes = shapes)

        # package the robot physical properties (for collisions)
        # The robot constructor can choose to ignore them
        param = {'position': robot_pos,
                    'angle': robot_angle,
                    'linearDamping': robot_linear_damping,
                    'angularDamping': robot_angluar_damping,
                    'restitution': robot_restitution}

        # create the robot entity
        self.robotbody = robot.attachRobotBody(self.world, **param)
        self.robot = robot
        self.inputs = robot.getDefaultInput()
Exemple #45
0
def init_world(g=(0, -10), sleep=True):
    global world
    world = b2World(gravity=g, doSleep=sleep)
    return world
import math

from Box2D import b2World

from cart_pendulum_demo import load_winner_net_controller, CartPendulumSystem
from plot_winner_output import plot_net_output
from settings import fwSettings

if __name__ == "__main__":
    controller = load_winner_net_controller()
    initial_position = 2.3
    initial_rotation = 0.0
    sim = CartPendulumSystem(b2World(), controller, initial_position,
                             initial_rotation)

    print()
    print("Initial conditions:")
    print("        x = {0:.4f}".format(sim.x))
    print("    x_dot = {0:.4f}".format(sim.dx))
    print("    theta = {0:.4f}".format(sim.theta))
    print("theta_dot = {0:.4f}".format(sim.dtheta))
    print()

    # Run the given simulation for up to 120 seconds.
    balance_time = 0.0
    times = []
    positions = []
    rotations = []

    steps = 3000
    step = 0
Exemple #47
0
import game
from Box2D import b2World

game.init(world=b2World(gravity=(0, 0), doSleep=True))

#import rule_connect
#rule_connect.add()
from camera import Camera

Camera().add()

import camera_control

camera_control.add()

import b2draw

b2draw.init()
'''from firefly import Firefly
import random
for _ in range(100):
	Firefly(random.randint(-40, 40), random.randint(-30, 30)).add()'''

from tilemap import TileMap, SolidBlock

tilemap = TileMap((0, 0), (10, 10))
tilemap.add()

game.start()
Exemple #48
0
def setup_box2D():
    '''Create Box2D world.'''    
    world = b2World(gravity=(0, 0), doSleep=True, contactListener=ContactListener())
    b2PolygonShape.draw = draw_polygon
    b2CircleShape.draw = draw_circle
    return world