def __init__(self, vis=True, gravity=True): ''' Initializes an Empty Simulation Environment containing only the ground. ''' self.objectDict = dict() #map from id to pyBox2d object # for every PO in this environment #TODO: make a property self.connectionDict = dict() #map from a frozen set of of PhysicsObject ids to a Pybox2d joint self.creatures = dict() #store a reference to every creature being simulated shouldSleep = True if gravity == None: self.world = b2.world(gravity=(0,0), doSleep=shouldSleep) elif isinstance(gravity, tuple): self.world = b2.world(gravity=gravity, doSleep=shouldSleep) elif gravity == True: self.world = b2.world(gravity=(0,-9.8), doSleep=shouldSleep) else: self.world = b2.world(gravity=(0,gravity), doSleep=shouldSleep) self.ground = None #self.world.CreateStaticBody(position=(0,1), # shapes=b2.polygonShape(box=(50,2)) # ) #TODO: This will be defined later on, by other code self._powerController = PowerController() self.vis = vis if self.vis: self.r = Renderer(self.world) self.r.setup(showCoords=True) self.physicsStep = 50.0/200.0
def __init__(self, ppm=20, fps=60, width=640, height=480, gravity=(0, 0), \ caption="Window", joint_limit=False, lower_angle=-.5*b2_pi, upper_angle=.5*b2_pi, max_torque=10000, \ linear_damping=0.0, angular_damping=0.0, enable_mouse_joint=True): self.window = Window(width=width, height=height, caption=caption) self.ppm = ppm # pixels per meter self.width = width self.height = height self.colors = [(255, 255, 255, 255), (255, 0, 0, 255)] self.fps = fps self.timestep = 1.0 / self.fps pyglet.clock.set_fps_limit(self.fps) self.world = world(gravity=gravity, doSleep=False) self.linear_damping = linear_damping self.angular_damping = angular_damping self.joint_limit = joint_limit self.lower_angle = lower_angle self.upper_angle = upper_angle self.max_torque = max_torque self.enable_mouse_joint = enable_mouse_joint self.selected = None self.mouse_joint = None self.joints = [] self.bodies = [] # create ground self.ground = self.add_static_body(p=(self.width/2, 10), \ size=(self.width, 30))
def example_geometry(): """Generate example geometry for testing""" get_triangles = metis.geometry.box2d_triangles_from_shapely world = b2.world() agent = world.CreateDynamicBody() agent_geometry = shapely.geometry.Polygon([ (2./3., 0.), (-1./3., .4), (-1./3., -.4)]) for triangle in get_triangles(agent_geometry): _ = agent.CreateFixture(shape=triangle) heptagon = shapely.geometry.Point(0, 0).buffer(1.5, resolution=3) offset_hexagon = shapely.geometry.Point(1, 0).buffer(1.5, resolution=2) shapes = { 'box': shapely.geometry.box(0, 0, 1, 1), 'convex': heptagon, 'nonconvex': heptagon.difference(offset_hexagon) } boxes = {} for name in shapes: boxes[name] = world.CreateDynamicBody() for triangle in get_triangles(shapes[name]): _ = boxes[name].CreateFixture(shape=triangle) return world, agent, boxes
def example_world(): """Create an example Box2D world for testing Returns: tuple(world, robot): - world is a Box2D world with a dynamic body - robot is a Box2D body describing a robot in the world """ get_triangles = metis.geometry.box2d_triangles_from_shapely obstacle_geometry = shapely.geometry.box(0, 0, 10, 10) obstacle_geometry = obstacle_geometry.difference( obstacle_geometry.buffer(-.2)) obstacle_geometry = obstacle_geometry.union( shapely.geometry.LineString([(5, 0), (5, 10)]).buffer(.1, cap_style=2)) obstacle_geometry = obstacle_geometry.difference( shapely.geometry.Point(5, 2.5).buffer(1, cap_style=1)) obstacle_geometry = obstacle_geometry.difference( shapely.geometry.Point(5, 7.5).buffer(1, cap_style=1)) world = b2.world() obstacles = world.CreateStaticBody() for triangle in get_triangles(obstacle_geometry): _ = obstacles.CreateFixture(shape=triangle) return world
def init_track(self, centerline, left, right, checkpoints): # --- pybox2d world setup --- self.world = world(gravity=(0, 0), doSleep=True) self.bodies = [] self.tracks = [] # --- track setup outer_track = self.world.CreateBody(shapes=chainShape( vertices=self.rtfm(left))) inner_track = self.world.CreateBody(shapes=chainShape( vertices=self.rtfm(right))) self.centerline = centerline self.spawn = (round(centerline[0][0] / self.PPM), round(centerline[0][1] / self.PPM)) self.cpts = list( self.rtfm(x) for x in checkpoints ) #unlike left and right tracks, center is stored as meters instead of pix. #this is because it is accessed as meters by physics engine every loop. #this next bit decides whether to flip left and right to make sure we can handle clockwise AND #counterclockwise tracks in the next bit. Theres probably a faster way to do it but this block #only runs once so who cares. The idea is to shoot a ray across the screen until it hits a track, #and whichever track it contacts first is the outer track (left track) outer_track.fixtures[0].userData = 'outer' callback = RayCastClosestCallback() i = 0 while callback.hit == False: self.world.RayCast(callback, (i - 10, -10), (i - 10, self.SCREEN_HEIGHT / self.PPM)) i += 3 if callback.fixture.userData != 'outer': print('clockwise track detected. Initiating corrections') temp = outer_track outer_track = inner_track inner_track = temp self.tracks.append([outer_track, 'white']) self.tracks.append([inner_track, 'lightblue']) self.direction = np.arctan2(centerline[1][1] - centerline[0][1], centerline[1][0] - centerline[0][0]) # --- Create car self.car = self.world.CreateDynamicBody(position=self.spawn, angle=self.direction, linearDamping=.3, angularDamping=6) self.car_color = 'blue' self.box = self.car.CreatePolygonFixture(box=(1, .5), density=1, friction=0.002) # --- trial spawn locations self.trial = 0 self.trials = [ random.randint(0, len(self.centerline) - 2) for _ in range(self.num_trials) ] #starting point for each trial
def __init__(self, render=False, fixed_ur_timestep=False): self.render = render self.fixed_ur_timestep = fixed_ur_timestep # -------------------- Pygame Setup ---------------------- pygame.init() self.delta_time = 1.0 / TARGET_FPS # 0.016666 self.fps = TARGET_FPS self.accumulator = 0 self.screen = None if self.render: self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Testbed Homing Simple') self.clock = pygame.time.Clock() self.myfont = pygame.font.SysFont("monospace", 15) # -------------------- Environment and PyBox2d World Setup ---------------------- # Create the world self.world = world(gravity=(0, 0), doSleep=True) self.race = RaceS(screen=self.screen, world=self.world)
def __init__(self, original_pos, vertices, goal_pos, goal_angle, use_param=True, use_discrete=False): """ original_pos: define the original position by (x, y) tuple vertices: define the polygon as an ordered list of its vertices (x, y) tuple with the original_pos as (0, 0). under assumptions: 1. vertices are ordered as either clockwise/counterclockwise 2. the polygon itself is a convex set goal_pos: define the goal position by (x, y) tuple goal_angle: define the goal angle by a float """ # self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) self.done = False self.original_pos = original_pos self.goal_pos = goal_pos self.goal_angle = goal_angle self.world = world(gravity=(0, 0), doSleep=True) self.vertices = vertices self.use_param = use_param # figure out center of mass self.centroid = compute_centroid(vertices) # centeralize polygon by centroid self.original_pos = (original_pos[0] + self.centroid[0], original_pos[1] + self.centroid[1]) self.goal_pos = (goal_pos[0] + self.centroid[0], goal_pos[1] + self.centroid[1]) self.vertices = [(v[0] - self.centroid[0], v[1] - self.centroid[1]) for v in vertices] self.centroid = (0, 0) self.bounding_circle_radius = max([euclidean_dist(v, self.centroid) for v in self.vertices]) # a target box to move around self.box = self.world.CreateDynamicBody(position=self.original_pos, allowSleep=False, userData='target') boxfix = self.box.CreatePolygonFixture(density=1, vertices=self.vertices, friction=0.5) self.actions = [] n = len(self.vertices) if not use_discrete: # figure out actions that relate to orientations for i in range(n): curr = self.vertices[i] self.actions.extend(get_orientation_force(self.centroid, curr, use_param)) # figure out actions that relate to translations for i in range(n): curr = self.vertices[(i - n) % n] next = self.vertices[(i + 1 - n) % n] self.actions.append(get_trans_force(self.centroid, curr, next)) else: discrete_pts_lst = [(p[0]*self.bounding_circle_radius, p[1]*self.bounding_circle_radius) for p in Discrete_Points] for i in range(len(discrete_pts_lst)): for j in range(len(discrete_pts_lst)): if i != j: self.actions.append(self.bounding_param_to_actions(discrete_pts_lst[i], discrete_pts_lst[j])) if use_param: self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('example') pygame.display.iconify()
def __init__(self, corners, size, ppm, terrain=None, rotation=0.0, wall_thickness=10, wall_color=GREEN, background=BLACK, timestep=None): self.corners = [np.array(corner, dtype=float) for corner in corners] self.map_centre = np.average(self.corners, axis=0) self.wall_thickness = wall_thickness self.wall_color = wall_color self.terrain = {} # terrain if terrain is not None else [] self.background = background self.ppm = ppm self.physicals = {} self.rotation = rotation self.size = size self.timestep = timestep self.world = world(gravity=(0, 0), doSleep=True) self.walls = self.generate_walls() self.terrain[self.walls.uuid] = self.walls self.physical_bodies = {}
def __init__(self, world, bodies, bounds=None, **kwargs): super(ManyShapeGeometry, self).__init__(**kwargs) self.world = world self.empty_world = b2.world() self.bodies = bodies obstacles = self.empty_world.CreateStaticBody() moveable_fixtures = {fixture for body in bodies.itervalues() for fixture in body.fixtures} for body in world.bodies: for fixture in body.fixtures: if fixture not in moveable_fixtures: obstacles.CreateFixture(shape=fixture.shape) if bounds is None: self.bounds = world_bounding_box(world) else: self.bounds = bounds self.sample_count = 0 self.rejection_count = 0 # Angle differences will be scaled by this in computing the # distance between points in SE(2) rotation_scale = 1 self.scale = numpy.array([1, 1, rotation_scale])
def __init__(self, cond, mass_list, force_list, init_mouse, time_stamp, ig_mode, prior,reward_stop, mass_answers={}, force_answers={}, n_bodies=None): # --- pybox2d world setup --- self.mass_answers = mass_answers self.force_answers = force_answers # Create the world self.world = world(gravity=(0, 0), doSleep=True) self.bodies = [] self.walls = [] self.data = {} self.cond_list = [None] + cond self.cond = cond[0] # self.cond = cond self.init_mouse = init_mouse self.n_bodies = n_bodies self.bodies_names = [] self.add_pucks(n_bodies) self.add_static_walls() self.mass_list = mass_list self.force_list = force_list self.T = time_stamp self.ig_mode = ig_mode self.prior = copy.deepcopy(prior) self.PRIOR = copy.deepcopy(prior) self.reward_stop = reward_stop if self.ig_mode == 1: self.total_reward = entropy(marginalize_prior(prior, 0)) print("Total reward per game:{}".format(self.total_reward)) elif self.ig_mode == 2: self.total_reward = entropy(marginalize_prior(prior, 1)) print("Total reward per game:{}".format(self.total_reward)) self.step_reward = []
def __init__(self, container, width, height): SimulationBase.__init__(self, container, width, height) # --- pybox2d world setup --- # Create the world self.m_b2dWorld = world(gravity=(0, -10), doSleep=True) self.m_debugDraw = DebugDrawExtended(surface=settings.OBJ_SURFACE) self.m_b2dWorld.renderer = self.m_debugDraw self.m_b2dWorld.warmStarting = True self.m_b2dWorld.continuousPhysics = True self.m_b2dWorld.subStepping = False self.m_groundBody = None self.mouseJoint = None self.colours = { 'mouse_point': b2Color(0, 1, 0), 'joint_line': b2Color(0.8, 0.8, 0.8) } self.m_joints = [] self.init() self.setupWorld()
def __init__(self, render=False, fixed_ur_timestep=False, num_agents=1): debug_homing_simple.xprint(color=PRINT_GREEN, msg='Creating Environment, Physics Setup') self.render = render self.fixed_ur_timestep = fixed_ur_timestep # -------------------- Pygame Setup ---------------------- pygame.init() self.delta_time = 1.0 / TARGET_FPS # 0.016666 self.fps = TARGET_FPS self.accumulator = 0 self.screen = None if self.render: self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Testbed Homing Simple') self.clock = pygame.time.Clock() self.myfont = pygame.font.SysFont("monospace", 15) # -------------------- Environment and PyBox2d World Setup ---------------------- # Goal positions goal1 = (100, 100) goal2 = (SCREEN_WIDTH - goal1[0], SCREEN_HEIGHT - goal1[1]) # 1180, 620 self.goals_pixels = [goal1, goal2] goal1_vec = pixels_to_world(goal1) # b2Vec2(5,31) goal2_vec = vec2(SCREEN_WIDTH / PPM - goal1_vec.x, SCREEN_HEIGHT / PPM - goal1_vec.y) # b2Vec2(59,5) self.goals_vec = [goal1_vec, goal2_vec] # Create the world self.world = world(gravity=(0, 0), doSleep=True) # Border of the map self.border = Border(screen=self.screen, world=self.world) # Agents self.numAgents = num_agents # total numbers of agents in the simulation self.agents = [] for j in range(num_agents): start_pos = pixels_to_world(self.goals_pixels[1]) # start from goal 2 toGoal = Util.normalize(pixels_to_world(self.goals_pixels[0]) - start_pos) forward = vec2(0, 1) angleDeg = Util.angle_indirect(forward, toGoal) angle = Util.deg_to_rad(angleDeg) angle = -angle # start by looking at goal1 a = AgentHomingSimple(screen=self.screen, world=self.world, x=start_pos.x, y=start_pos.y, angle=angle, radius=1.5, id=j, goals=self.goals_vec, num_agents=num_agents) self.agents.append(a) # Affect list of agents to each agent for agent in self.agents: agent.agents_list = self.agents
def __init__(self): self.item_sizes = [] self.height_reward = 0 self.world = world(gravity=(0, -1000), sleep=True) self.colour_list = [] self.ground_body = self.world.CreateStaticBody( position=(320, 20), shapes=polygonShape(box=(640, 30)), angle=0) self.body_list = [self.ground_body] self.init_height = 74 self.colour_list.append((255, 255, 255, 255))
def __init__(self): self.trackWidth = 5.0 self.cartWidth = 0.3 self.cartHeight = 0.2 self.cartMass = 0.5 self.poleMass = 0.1 self.force = 0.2 self.trackThickness = self.cartHeight self.poleLength = self.cartHeight*6 self.poleThickness = 0.04 #self.screenSize = (640,480) #origin upper left self.screenSize = (128,96) #origin upper left self.worldSize = (float(self.trackWidth),float(self.trackWidth)) #origin at center self.world = b2.world(gravity=(0,-10),doSleep=True) self.framesPerSecond = 30 # used for dynamics update and for graphics update self.velocityIterations = 8 self.positionIterations = 6 # Make track bodies and fixtures self.trackColor = (100,100,100) poleCategory = 0x0002 f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackWidth/2,self.trackThickness/2)), friction=0.001, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory)) self.track = self.world.CreateStaticBody(position = (0,0), fixtures=f, userData={'color': self.trackColor}) self.trackTop = self.world.CreateStaticBody(position = (0,self.trackThickness+self.cartHeight*1.1), fixtures = f) f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackThickness/2,self.trackThickness/2)), friction=0.001, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory)) self.wallLeft = self.world.CreateStaticBody(position = (-self.trackWidth/2+self.trackThickness/2, self.trackThickness), fixtures=f, userData={'color': self.trackColor}) self.wallRight = self.world.CreateStaticBody(position = (self.trackWidth/2-self.trackThickness/2, self.trackThickness), fixtures=f,userData={'color': self.trackColor}) # Make cart body and fixture f = b2.fixtureDef(shape=b2.polygonShape(box=(self.cartWidth/2,self.cartHeight/2)), density=self.cartMass, friction=0.001, restitution=0.5, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory)) self.cart = self.world.CreateDynamicBody(position=(0,self.trackThickness), fixtures=f, userData={'color':(20,200,0)}) # Make pole pody and fixture # Initially pole is hanging down, which defines the zero angle. f = b2.fixtureDef(shape=b2.polygonShape(box=(self.poleThickness/2, self.poleLength/2)), density=self.poleMass, categoryBits=poleCategory) self.pole = self.world.CreateDynamicBody(position=(0,self.trackThickness+self.cartHeight/2+self.poleThickness-self.poleLength/2), fixtures=f, userData={'color':(200,20,0)}) # Make pole-cart joint self.world.CreateRevoluteJoint(bodyA = self.pole, bodyB = self.cart, anchor=(0,self.trackThickness+self.cartHeight/2 + self.poleThickness))
def __init__(self): self.trackWidth = 5.0 self.cartWidth = 0.3 self.cartHeight = 0.2 self.cartMass = 10 self.poleMass = 1 self.force = 0.2 self.trackThickness = self.cartHeight self.poleLength = 0.5 self.poleThickness = 0.04 self.screenSize = (640,480) #origin upper left self.worldSize = (float(self.trackWidth),float(self.trackWidth)) #origin at center self.world = b2.world(gravity=(0,-9.81),doSleep=True) self.framesPerSecond = 10 # used for dynamics update and for graphics update self.velocityIterations = 8 self.positionIterations = 6 # Make track bodies and fixtures self.trackColor = (100,100,100) poleCategory = 0x0002 f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackWidth/2,self.trackThickness/2)), friction=0.000, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory)) self.track = self.world.CreateStaticBody(position = (0,0), fixtures=f, userData={'color': self.trackColor}) self.trackTop = self.world.CreateStaticBody(position = (0,self.trackThickness+self.cartHeight*1.1), fixtures = f) f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackThickness/2,self.trackThickness/2)), friction=0.000, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory)) self.wallLeft = self.world.CreateStaticBody(position = (-self.trackWidth/2+self.trackThickness/2, self.trackThickness), fixtures=f, userData={'color': self.trackColor}) self.wallRight = self.world.CreateStaticBody(position = (self.trackWidth/2-self.trackThickness/2, self.trackThickness), fixtures=f,userData={'color': self.trackColor}) # Make cart body and fixture f = b2.fixtureDef(shape=b2.polygonShape(box=(self.cartWidth/2,self.cartHeight/2)), density=self.cartMass, friction=0.000, restitution=0.5, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory)) self.cart = self.world.CreateDynamicBody(position=(0,self.trackThickness), fixtures=f, userData={'color':(20,200,0)}) # Make pole pody and fixture # Initially pole is hanging down, which defines the zero angle. f = b2.fixtureDef(shape=b2.polygonShape(box=(self.poleThickness/2, self.poleLength/2)), density=self.poleMass, categoryBits=poleCategory) self.pole = self.world.CreateDynamicBody(position=(0,self.trackThickness+self.cartHeight/2+self.poleThickness-self.poleLength/2), fixtures=f, userData={'color':(200,20,0)}) # Make pole-cart joint rj = self.world.CreateRevoluteJoint(bodyA = self.pole, bodyB = self.cart, anchor=(0,self.trackThickness+self.cartHeight/2+self.poleThickness))
def __init__(self): self.body_list = [] self.world = world(gravity=(0, -100), sleep=False) self.colour_list = [] self.possible_actions = [self.move_up, self.move_down, self.move_left, self.move_right, self.rot_left] num_actions = len(self.possible_actions) self.action_space = np.linspace(0, num_actions - 1, num_actions) print(self.action_space) base_state = self.reset() self.observation_space = np.asarray(base_state)
def reset_screen(self): self.clock = pygame.time.Clock() self.world = world(gravity=(0, 0), contactListener=collision_handler(self), doSleep=False) self.agent_target_pair = [] # agent is at index 0, target is at 1 self.dynamic_obstacle_list = [] self.static_obstacle_list = self.initialise_walls() self.reached_target = False self.collision_detected = False self.is_update_required = True
def __init__(self): self.world = world(gravity=(0, 0), doSleep=True) self.objs = [] self.rod = None self.rod2 = None self.bounding_convex_hull = np.array([]) self.centroid = (0, 0) self.bounding_circle_radius = 0
def __init__( self, contactListener=None, render_window=True, render_video=False, video_file=None, font='arial', font_size=16 ): # Initialize rendering destination params self.render_window = render_window self.render_video = render_video self.video_file = video_file if self.render_video and video_file is None: raise ValueError('Engine error: Specified rendering to video, but did not specify file name') # Initialize world self.world = b2.world( gravity = (0, -50), doSleep = True, contactListener = contactListener ) # Create ground self.add_object( 'ground', { 'position': (GROUND_START, 0) }, 'poly', { 'box': (GROUND_WIDTH, 5), 'friction': 0.5 }, (80, 80, 80, 255), True, 0x01 ) # Create mouse self.add_object( 'mouse', { 'position': (0, 0) }, None, None ) # Initialize pygame modules pygame.init() pygame.font.init() # Initialize rendering decorations self.font = pygame.font.SysFont(font, font_size)
def __init__(self): self.item_sizes = [] self.height_reward = 0 self.world = world(gravity=(0, -1000), sleep=True) self.colour_list = [] self.ground_body = self.world.CreateStaticBody( position=(320, 20), shapes=polygonShape(box=(640, 30)), angle=0) self.body_list = [self.ground_body] self.init_height = 82 self.colour_list.append((255, 255, 255, 255)) self.possible_actions = np.linspace(176, 464, 10) self.action_space = np.linspace(0, 9, 10) self.observation_space = self.reset_world()
def __init__(self): self.world = b2.world(doSleep=True, gravity=(0, 0)) self.to_destroy = set() self.unused_bodies = set() self.objects_to_create_bodies_for = dict() self.collisions =dict() self.collision_callback = CollisionCallback(self) self.ray_cast_callback = RayCastCallback() self.closest_ray_cast_callback = ClosestRayCastCallback() self.world.contactListener = self.collision_callback self.objects = set() self.objects_to_add = set() self.bodies = []
def __init__(self): self.world = world() print('Initializing pygame framework...') # Pygame Initialization pygame.init() caption = "Python Box2D Testbed - Simple backend - " + self.name pygame.display.set_caption(caption) # Screen and debug draw self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) self.font = pygame.font.Font(None, 15) self.groundbody = self.world.CreateBody()
def _createWorld(self): # --- pybox2d world setup --- # Create the world self.world = world(gravity=(0, 0), doSleep=True) # self.rod = self.world.CreateDynamicBody(position=(9.5, 8), allowSleep=False, userData='rod') # rodfix = self.rod.CreatePolygonFixture(density=1, box=(0.25, 1), friction=0.0) # self.rod.linearDamping = 0.3 # self.rod.angularDamping = 0.1 # a target box to move around self.box = self.world.CreateDynamicBody(position=(9, 7), allowSleep=False, userData='target') boxfix = self.box.CreatePolygonFixture(density=1, vertices=[(-0.5, -0.25), (0.5, -0.25), (0, 0.5)], friction=0.5) # self.box.linearDamping = 0.3 # self.box.angularDamping = 0.1 self.origin_dist_pos = math.sqrt( (self.box.position[0] - self.goal_pos[0])**2 + (self.box.position[1] - self.goal_pos[1])**2) self.origin_dist_angle = abs(self.box.angle - self.goal_angle) colors = { 'target': (200, 200, 200, 255), # 'rod': (100, 100, 100, 100), } def my_draw_polygon(polygon, body, fixture): vertices = [(body.transform * v) * PPM for v in polygon.vertices] vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices] k = body.userData if k == None: k = 'default' pygame.draw.polygon(self.screen, colors[k], vertices, 0) pygame.draw.polygon(self.screen, (0, 0, 0, 0), vertices, 5) polygonShape.draw = my_draw_polygon for body in self.world.bodies: for fixture in body.fixtures: fixture.shape.draw(body, fixture)
def __init__(self): self.world = world(gravity=(0, -10)) self.colour_list = [] ground_body = self.world.CreateStaticBody(position=(-5, 20), shapes=polygonShape(box=(50, 5)), angle=15) self.body_list = [ground_body] ground_body = self.world.CreateStaticBody(position=(5, -5), shapes=polygonShape(box=(50, 5)), angle=-15) self.body_list.append(ground_body) self.colour_list.append((255, 255, 255, 255)) self.colour_list.append((255, 255, 255, 255))
def __init__(self): self.world = world(gravity=(0, -10), doSleep=True) self.ground_body = self.world.CreateStaticBody( position=(0, 0), shapes=polygonShape(box=(50, 1)), userData={"color": (255, 255, 255)}) self.blocks = [] self.latestPlan = [] # self.H = 3. # self.W = 0.5 self.dt = 1. / 60 self.locationNoise = 0.0 self.xOffset = 11
def __init__(self, render=False, fixed_ur_timestep=False, num_agents=1, solved_score=100000, seed=None): self.render = render self.fixed_ur_timestep = fixed_ur_timestep # -------------------- Pygame Setup ---------------------- pygame.init() self.delta_time = 1.0 / TARGET_FPS # 0.016666 self.fps = TARGET_FPS self.accumulator = 0 self.screen = None if self.render: self.screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Testbed Homing Simple') self.clock = pygame.time.Clock() self.myfont = pygame.font.SysFont("monospace", 15) # -------------------- Environment and PyBox2d World Setup ---------------------- # Create the world self.world = world(gravity=(0, 0), doSleep=True, contactListener=RaceContactListener()) env = 'RaceCircle' # 'RaceCircle_v2' # 'RaceCircle' if env == 'RaceCircle': self.race = RaceCircle(screen=self.screen, world=self.world) elif env == 'RaceCircle_v2': self.race = RaceCircleV2(screen=self.screen, world=self.world) self.agent = AgentRace(screen=self.screen, world=self.world, x=30, y=30, radius=1.25, solved_score=solved_score, env=env, seed=seed)
def example_world(): """Generate a simple example world for testing""" convex_from_shapely = metis.geometry.convex_box2d_shape_from_shapely obstacle_geometry = shapely.geometry.box(0, 0, 2, 2).difference( shapely.geometry.box(.1, .1, 1.9, 1.9)) moveable_geometry = shapely.geometry.box(-.1, -.1, .1, .1) world = b2.world() obstacles = world.CreateStaticBody() for triangle in metis.geometry.triangulate(obstacle_geometry): obstacles.CreateFixture(shape=convex_from_shapely(triangle)) moveable = world.CreateDynamicBody() moveable.CreateFixture(shape=convex_from_shapely(moveable_geometry)) return world, obstacles, moveable
def create_world(self): """Initialize the c structures""" world = b2.world() obstacles = world.CreateStaticBody() for triangle in triangles_from_shapely(self.obstacle_geometry): _ = obstacles.CreateFixture(shape=triangle) agent = world.CreateDynamicBody() for triangle in triangles_from_shapely(self.agent_geometry): _ = agent.CreateFixture(shape=triangle) bodies = {'robot': agent} for obj, shape in self.object_geometry.iteritems(): body = world.CreateDynamicBody() body.CreateFixture(shape=convex_from_shapely(shape)) bodies[obj] = body return world, agent, bodies
def test_multiobjectgeometry(): convex_from_shapely = metis.geometry.convex_box2d_shape_from_shapely obstacle_geometry = shapely.geometry.box(0, 0, 2, 2).difference( shapely.geometry.box(.1, .1, 1.9, 1.9)) moveable_geometry = shapely.geometry.box(-.1, -.1, .1, .1) world = b2.world() obstacles = world.CreateStaticBody(userData="obstacles") for triangle in metis.geometry.triangulate(obstacle_geometry): obstacles.CreateFixture(shape=convex_from_shapely(triangle)) box1 = world.CreateDynamicBody(userData="box1") box1.CreateFixture(shape=convex_from_shapely(moveable_geometry)) box2 = world.CreateDynamicBody(userData="box2") box2.CreateFixture(shape=convex_from_shapely(moveable_geometry)) geometry = metis.geometry.ManyShapeGeometry( world, {"box1": box1, "box2": box2}) yield check_multiobject_configuration, "free", True, geometry, { 'box1': (.5, .5, 0), 'box2': (1.5, 1.5, 0)} yield check_multiobject_configuration, "rotated", True, geometry, { 'box1': (.5, .5, numpy.pi/4), 'box2': (.65, .65, numpy.pi/4)} yield check_multiobject_configuration, "obstacle_collision", False, \ geometry, {'box1': (0, 0, 0), 'box2': (1.5, 1.5, 0)} yield check_multiobject_configuration, "moveable_collision", False, \ geometry, {'box1': (.5, .5, 0), 'box2': (.6, .6, 0)} yield (check_multiobject_path, "free", True, geometry, {'box1': (.5, .5, 0), 'box2': (1.5, 1.5, 0)}, {'box1': (.5, 1.5, 0), 'box2': (1.5, .5, 0)}) yield (check_multiobject_path, "collision", False, geometry, {'box1': (.5, .5, 0), 'box2': (1.5, 1.5, 0)}, {'box1': (-1.5, 1.5, 0), 'box2': (1.5, .5, 0)}) yield (check_multiobject_path, "missed_collision", True, geometry, {'box1': (.5, .5, 0), 'box2': (1.5, 1.5, 0)}, {'box1': (1.5, 1.5, 0), 'box2': (.5, .5, 0)}) yield (check_multiobject_path, "caught_collision", False, geometry, {'box1': (.5, .5, 0), 'box2': (1.5, 1.5, 0)}, {'box1': (1.5, 1.5, 0)})
def _createWorld(self): # --- pybox2d world setup --- # Create the world self.world = world(gravity=(0, 0), doSleep=True) self.rod = self.world.CreateDynamicBody(position=(10.5, 15), allowSleep=False, userData='rod') rodfix = self.rod.CreatePolygonFixture(density=1, box=(0.25, 1), friction=0.0) # a target box to move around self.box = self.world.CreateDynamicBody(position=(10, 15), allowSleep=False, userData='target') boxfix = self.box.CreatePolygonFixture(density=1, box=(1, 1), friction=0.5) ORIGIN_DIST_POS = math.sqrt((self.box.position[0] - GOAL_POS[0])**2 + (self.box.position[1] - GOAL_POS[1])**2) ORIGIN_DIST_ANGLE = abs(self.box.angle - GOAL_ANGLE) colors = { 'target': (200, 200, 200, 255), 'rod': (100, 100, 100, 100), } def my_draw_polygon(polygon, body, fixture): vertices = [(body.transform * v) * PPM for v in polygon.vertices] vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices] k = body.userData if k == None: k = 'default' pygame.draw.polygon(self.screen, colors[k], vertices, 0) pygame.draw.polygon(self.screen, (0, 0, 0, 0), vertices, 5) polygonShape.draw = my_draw_polygon for body in self.world.bodies: for fixture in body.fixtures: fixture.shape.draw(body, fixture)
def __init__(self, terrain, biped, save=False): self.terrain = terrain self.biped = biped # Create the world self.sim_world = world(gravity=(0, -10), doSleep=True) # Create the terrain (static ground body) self.terrain.world = self.sim_world self.terrain.build(self.sim_world) x0, y0 = self.terrain.get_spawn_pos() self.biped.build(self.sim_world, x0, y0) self.tracker = self.biped.tracker self.starting_position = self.tracker[0] # just x coordinate # Only init history after terrain was built self.history = Data(self.terrain)
def _createWorld(self): # --- pybox2d world setup --- # Create the world self.world = world(gravity=(0, 0), doSleep=True) # self.rod = self.world.CreateDynamicBody(position=(9.5, 8), allowSleep=False, userData='rod') # rodfix = self.rod.CreatePolygonFixture(density=1, box=(0.25, 1), friction=0.0) # self.rod.linearDamping = 0.3 # self.rod.angularDamping = 0.1 # a target box to move around self.box = self.world.CreateDynamicBody(position=(9, 7), allowSleep=False, userData='target') boxfix = self.box.CreatePolygonFixture(density=1, vertices=[(-0.5,-0.25), (0.5,-0.25), (0,0.5)], friction=0.5) # self.box.linearDamping = 0.3 # self.box.angularDamping = 0.1 self.origin_dist_pos = math.sqrt((self.box.position[0] - self.goal_pos[0])**2 + (self.box.position[1] - self.goal_pos[1])**2) self.origin_dist_angle = abs(self.box.angle - self.goal_angle)
def __init__(self, cond, mass_list, force_list, init_mouse, time_stamp, ig_mode, prior): # --- pybox2d world setup --- # Create the world self.world = world(gravity=(0, 0), doSleep=True) self.bodies = [] self.walls = [] self.data = {} self.cond = cond self.init_mouse = init_mouse self.add_pucks() self.add_static_walls() self.mass_list = mass_list self.force_list = force_list self.T = time_stamp self.ig_mode = ig_mode self.prior = copy.deepcopy(prior) self.PRIOR = copy.deepcopy(prior)
def __init__(self, display=False, manual=False): # -------------------- Pygame Setup ---------------------- self.display = display self.manual = manual self.screen = None if self.display: pygame.init() self.screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Environment Race Circle Left') self.clock = pygame.time.Clock() self.myfont = pygame.font.SysFont("monospace", 15) self.delta_time = 1.0 / TARGET_FPS self.fps = TARGET_FPS # -------------------- Environment and PyBox2d World Setup ---------------------- # Create the world self.world = world(gravity=(0, 0), doSleep=True, contactListener=RaceContactListener()) # Create physical objects self.car = Car(screen=self.screen, world=self.world, screen_height=SCREEN_HEIGHT, screen_width=SCREEN_WIDTH, ppm=PPM, env_name='RaceCircleLeft') self.race = RaceMap(screen=self.screen, world=self.world) self.max_episode_steps = 1000 self.prev_shaping = None self.timesteps = None self.orientation = None self.speed = None self.goal_reached = None self.d2g = None # distance to goal self.input_size = 7 self.action_size = 6
def example_world(): """Create an example Box2D world for testing Returns: tuple(world, bodies, configuration): - world is a Box2D world with multiple dynamic bodies - bodies is a dictionary mapping object names to their Box2D body - configuration is an example collision-free configuration """ get_triangles = metis.geometry.box2d_triangles_from_shapely obstacle_geometry = shapely.geometry.box(0, 0, 10, 10) obstacle_geometry = obstacle_geometry.difference( obstacle_geometry.buffer(-.2)) obstacle_geometry = obstacle_geometry.union( shapely.geometry.LineString([(5, 0), (5, 10)]).buffer(.1, cap_style=2)) obstacle_geometry = obstacle_geometry.difference( shapely.geometry.Point(5, 2.5).buffer(1, cap_style=1)) obstacle_geometry = obstacle_geometry.difference( shapely.geometry.Point(5, 7.5).buffer(1, cap_style=1)) world = b2.world() obstacles = world.CreateStaticBody() for triangle in get_triangles(obstacle_geometry): _ = obstacles.CreateFixture(shape=triangle) agent = world.CreateDynamicBody() agent_geometry = shapely.geometry.Polygon([ (2./3., 0.), (-1./3., .4), (-1./3., -.4)]) for triangle in get_triangles(agent_geometry): _ = agent.CreateFixture(shape=triangle) boxes = [world.CreateDynamicBody() for _ in xrange(2)] for box in boxes: box.CreateFixture(shape=b2.polygonShape(box=(.8, .8))) bodies = {'robot': agent, 'box1': boxes[0], 'box2': boxes[1]} sample_configuration = { 'robot': (1, 2, 0), 'box1': (3, 2, -.2), 'box2': (5, 2.5, 0.1)} return world, bodies, sample_configuration
def __init__(self, xsize, ysize, frames=20, start=False): self.xsize = xsize self.ysize = ysize self.timeStep = 1. / frames self.vel_iters = 10 self.pos_iters = 10 self.step = 0 self.world = b2.world(gravity=(0, 0), doSleep=True) self.clients = [] self.objects = [] self.players = [] self.terrain = [] if start: self.status = STATUS_RUNNING else: self.status = STATUS_WAITING self.winner = None self.update_loop = task.LoopingCall(self.doStep)
def __init__(self): pygame.init() self.ppm = STATE_PPM # pixels per meter, make it 1 when training self.target_fps = 20 self.time_step = 1.0 / self.target_fps self.screen_width, self.screen_height = STATE_W, STATE_H # make it 32, 24 while training self.screen = pygame.display.set_mode( (self.screen_width, self.screen_height), 0, 32) self.clock = pygame.time.Clock() self.world = world(gravity=(0, 0), contactListener=collision_handler(self), doSleep=False) self.agent_target_pair = [] # agent is at index 0, target is at 1 self.dynamic_obstacle_list = [] self.static_obstacle_list = self.initialise_walls() self.is_update_required = True self.reached_target = False self.collision_detected = False
def __init__(self, mesh="bodies/worm.obj", muscles="bodies/worm-muscles.obj"): super(BonelessEnv, self).__init__() # How much of the previous spring length to preserve when making a change # (0 transitions immediately to new spring lengths) self.smooth = 0.9 self.time = 0 self.world = world(gravity=(0, -10), doSleep=True) self.ground_body = self.world.CreateStaticBody( position=(0, 0), shapes=polygonShape(box=(50, 1))) self.soft_body = SoftBody(self.world, mesh, muscles) self.PPM = 20.0 # pixels per meter self.SCREEN_WIDTH = 640 self.SCREEN_HEIGHT = 480 self.TARGET_FPS = 30 self.TIME_STEP = 1.0 / self.TARGET_FPS self.viewer = None n_edges = self.soft_body.num_edges() n_verts = self.soft_body.num_vertices() n_muscles = self.soft_body.num_muscles() # Actions: Top-left 2x2 submatrix of each muscle's transformation matrix # Actions: rotation + skew + scale self.action_space = spaces.Box( -np.finfo(np.float32).max * np.ones(3 * n_muscles), np.finfo(np.float32).max * np.ones(3 * n_muscles), dtype=np.float64) # Observations: length of every joint self.observation_space = spaces.Box( -np.finfo(np.float32).max * np.ones(n_edges), np.finfo(np.float32).max * np.ones(n_edges), dtype=np.float64)
def create_se2_geometry(self, fixed_poses, relative_poses, **kwargs): """Create an SE2Geometry object from this instance Objects that do not appear in either fixed_poses or relative_poses are not added to the geometry. Args: fixed_poses (dict): map from object names to absolute poses; objects in this dict are assumed to be fixed in the geometry object relative_poses (dict): map from object names to relative poses; objects in this dict are assumed to be fixed relative to the transforms sampled from the geometry object **kwargs: additional keyword args to pass to the SE2Geometry constructor """ obstacles = self.obstacle_geometry.union(shapely.ops.cascaded_union([ shapely_from_body(self.bodies[body], pose) for body, pose in fixed_poses.iteritems()])) # agent = shapely_from_body(self.bodies['robot'], (0, 0, 0)) agent = shapely.ops.cascaded_union([ shapely_from_body(self.bodies[body], pose) for body, pose in relative_poses.iteritems()]) world = b2.world() static_body = world.CreateStaticBody() for triangle in triangles_from_shapely(obstacles): _ = static_body.CreateFixture(shape=triangle) dynamic = world.CreateDynamicBody() for triangle in triangles_from_shapely(agent): _ = dynamic.CreateFixture(shape=triangle) return metis.geometry.SE2Geometry( world, dynamic.fixtures, bounds=self.obstacle_geometry.bounds, **kwargs)
def __init__(self): self.width = 400 self.time_step = 1.0 / 24.0 self.vel_iters = 6 self.pos_iters = 2 self.height = 300 self.width_real = 0.4 self.scale = self.width / self.width_real self.height_real = self.width_real * self.height / self.width self.origin = np.array([self.width / 2, self.height / 2]) self.world = Box2D.world(gravity=(0.0, 0.0)) self.goal_position = (1.0, 0.0) self.goal_radius = 0.2 * np.sqrt(2) # For plotting model predictions self._traces = dict() # Insert objects, set position in _reset() self.box = Box(self.world, 0.0, 0.0, 0.0) self.arm = Arm(self.world, 0.0, 0.0) self.viewer = None self._state_scalar = 10.0 self._reset()
size = width, height = 800, 600 screen = pg.display.set_mode(size) pg.display.update() run = True # переменна, с помощью ее можно выходить из цикла """А вот тут будет волшебство)""" clock = pg.time.Clock() RED = (255, 0, 0) BLACK = (0, 0, 0) world = world(gravity=(0, -10)) # создание поля ground_body = world.CreateStaticBody( position=(0, 10), shapes=polygonShape(box=(20, 0.5)), ) ground_body2 = world.CreateStaticBody( position=(37, 10), shapes=polygonShape(box=(10, 0.5)), ) ground_body3 = world.CreateStaticBody(position=(0, 0), shapes=polygonShape(box=(50, 1))) body = world.CreateStaticBody(position=(20, 15)) circle = body.CreateCircleFixture(radius=1, density=1, friction=0.3)
# --- constants --- # Box2D deals with meters, but we want to display pixels, # so define a conversion factor: PPM = 20.0 # pixels per meter TARGET_FPS = 60 TIME_STEP = 1.0 / TARGET_FPS SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480 # --- pygame setup --- screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Simple pygame example') clock = pygame.time.Clock() # --- pybox2d world setup --- # Create the world world = world(gravity=(0, -10), doSleep=True) # And a static body to hold the ground shape ground_body = world.CreateStaticBody( position=(0, 0), shapes=polygonShape(box=(50, 1)), ) # Create a couple dynamic bodies body = world.CreateDynamicBody(position=(20, 15)) circle = body.CreateCircleFixture(radius=0.5, density=1, friction=0.3) colors = { staticBody: (255, 255, 255, 255), dynamicBody: (127, 127, 127, 255),
import os import time import gevent import Box2D from Box2D import b2 as box2d from lxml import objectify world = box2d.world(gravity=(0,-10)) from .conf import settings from .scene import scene from .game import Wall def start_simulation(): import Box2D world.bounds, shapes = shapes_from_svg() for shape in shapes: #shape = box2d.polygonShape(vertices=shape) obj = scene.create_object('rocketz.game.ChainShape', shape) return gevent.spawn(simulate) def simulate(): time_delta = 0.01 start = time.time() while True: do_simulate_step(time_delta) done = time.time() time_spend = done - start
box2d.PPM = 20 class Level1(Box2DLevel): def __init__(self, world): super(Level1, self).__init__(world) layer = core.Layer() self.add_layer(layer) self.ground = world.CreateStaticBody( position=(0, -2), shapes=b2.polygonShape(box=(50, 5)) ) self.im0 = sf.Texture.load_from_file(b'princess.png') for y in range(0, 500, 120): for x in range(200, 700, 120): sprite = sf.Sprite(self.im0) sprite.origin = (self.im0.width//2, self.im0.height//2) sprite.position = (x, y) actor = core.Actor(sprite) body = world.CreateDynamicBody() body.CreateCircleFixture(radius=2.5, density=1.0, friction=0.3) actor.add_action(Updater(body), name='box2d') layer.add_actor(actor) game = core.Game(800, 600) level = Level1(b2.world()) game.run(level)
shapes=b2.polygonShape(box=(50, 5)) ) self.im0 = sf.Texture.load_from_file(b'princess.png') for y in range(0, 500, 120): for x in range(200, 700, 120): sprite = sf.Sprite(self.im0) sprite.origin = (self.im0.width//2, self.im0.height//2) sprite.position = (x, y) actor = core.Actor(sprite) body = world.CreateDynamicBody(linearDamping=0.25, angularDamping=0.1) body.CreateCircleFixture(radius=2.5, density=1.0, friction=0.3) actor.add_action(Updater(body), name='box2d') act2 = Move(0.1*random.randrange(5, 20)) actor.add_action(act2) layer.add_actor(actor) def on_collision(self, fixture_a, fixture_b, points, normal): actor_a = fixture_a.body.userData actor_b = fixture_b.body.userData if actor_a: actor_a.add_action(Colorize(1.0, sf.Color.RED), name='mark_col') if actor_b: actor_b.add_action(Colorize(1.0, sf.Color.BLUE), name='mark_col') game = core.Game(800, 600) level = Level1(b2.world(gravity=(0, 0))) game.run(level)
def init_box2d(): global w w = world(gravity=(0, gravity) , doSleep=True )
TARGET_FPS = 60 TIME_STEP = 1.0 / TARGET_FPS SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480 H_OFFSET = 320 V_OFFSET = 240 # setup screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Animation') clock = pygame.time.Clock() start_frame = int(sys.argv[1]) end_frame = int(sys.argv[2]) # construct world world = world(gravity=(0, 0), doSleep=True) # load strokes chains = [] static_chains = [] dynamic_chains = [] for ind in range(0, 5): print(ind) data = pd.read_csv("frame" + str(start_frame) + "stroke" + str(ind) + ".csv", delimiter=",", header=None) data = data_to_vecs(data)[::CHAIN_MULTIPLIER] if ind < 3: chain = load_chain(world, data, dynamic=False) static_chains.append(chain)
# Box2D deals with meters, but we want to display pixels, # so define a conversion factor: PPM=20.0 # pixels per meter TARGET_FPS=60 TIME_STEP=1.0/TARGET_FPS SCREEN_WIDTH, SCREEN_HEIGHT=640,480 # --- pygame setup --- screen=pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT), 0, 32) pygame.display.set_caption('Simple pygame example') clock=pygame.time.Clock() # --- pybox2d world setup --- # Create the world world=b2.world(gravity=(0,-0),doSleep=True) # And a static body to hold the ground shape ground_body=world.CreateStaticBody( position=(0,1), shapes=b2.polygonShape(box=(50,1)), ) # Create a dynamic body box1=world.CreateDynamicBody(position=(10,3+5), angle=0.0) box2=world.CreateDynamicBody(position=(14,5+5), angle=0.0) rj=world.CreateRevoluteJoint( bodyA=box1, bodyB=box2,