def LaunchBomb(self, position, velocity):
        """
        A bomb is a simple circle which has the specified position and velocity.
        position and velocity must be b2Vec2's.
        """
        if self.bomb:
            self.world.DestroyBody(self.bomb)
            self.bomb = None

        bd = box2d.b2BodyDef()
        bd.allowSleep = True
        bd.position = position
        bd.isBullet = True
        self.bomb = self.world.CreateBody(bd)
        self.bomb.SetLinearVelocity(velocity)

        sd = box2d.b2CircleDef()
        sd.radius = 0.3
        sd.density = 20.0
        sd.restitution = 0.1

        minV = position - (0.3,0.3)
        maxV = position + (0.3,0.3)

        aabb = box2d.b2AABB()
        aabb.lowerBound = minV
        aabb.upperBound = maxV

        if self.world.InRange(aabb):
            self.bomb.CreateShape(sd)
            self.bomb.SetMassFromShapes()
Beispiel #2
0
    def makeping(self, rname, rnd):
        tank = self.tanks[rname]
        body = tank.turret

        segmentLength = 65.0

        blocalpos = box2d.b2Vec2(1.12, 0)

        segment = box2d.b2Segment()
        laserStart = (1.12, 0)
        laserDir = (segmentLength, 0.0)
        segment.p1 = body.GetWorldPoint(laserStart)
        segment.p2 = body.GetWorldVector(laserDir)
        segment.p2+=segment.p1

        lambda_, normal, shape = self.w.RaycastOne(segment, False, None)
        hitp = (1 - lambda_) * segment.p1 + lambda_ * segment.p2
        angle = tank.get_turretangle()
        dist = box2d.b2Distance(segment.p1, hitp)

        if shape is not None:
            hitbody = shape.GetBody()
            kind = hitbody.userData['kind']
            if kind == 'tank':
                actor = hitbody.userData['actor']
                if actor._pinged != rnd - 1:
                    actor._pinged = rnd
            return kind, angle, dist
        else:
            
            
            return 'w', angle, 0
def createCircle(position, r=0.3, dynamic=True, bMatplotlib = True):
    global world, fig, ax
    bodyDef = Box2D.b2BodyDef()
    fixtureDef = Box2D.b2FixtureDef()
    if dynamic:
        bodyDef.type = Box2D.b2_dynamicBody
        fixtureDef.density = 1
    else:
        bodyDef.type = Box2D.b2_staticBody
        fixtureDef.density = 0

    bodyDef.position = position

    if(abs(world.gravity[1]) > 1):
        bodyDef.linearDamping = 0.1
        bodyDef.angularDamping = 0.1
    else:
        bodyDef.linearDamping = 70
        bodyDef.angularDamping = 30

    body = world.CreateBody(bodyDef)
    fixture = body.CreateFixture(shape=Box2D.b2CircleShape(radius=r), density=1.0, friction=0.3)
    
    if(bMatplotlib): 
        createGlobalFigure()
        fixture.userData = drawCircle(ax,position,r)
    
    return body
Beispiel #4
0
    def __init__(self, env, size, pos, world):
        # static rectangle shaped prop
        # pars:
        # size - array [width, height]
        # position - array [x, y], in world meters, of center

        self.env = env
        self.size = size
        self.pos = pos

        # initialize body
        bdef = Box2D.b2BodyDef()
        bdef.position = Box2D.b2Vec2(self.pos[0], self.pos[1])
        bdef.angle = 0
        bdef.fixedRotation = True
        self.body = world.CreateBody(bdef)

        # strange rect due to Box2D's way of representing objects
        self.rect = pygame.rect.Rect(self.pos[0] - self.size[0]/2,
                                     self.pos[1] - self.size[1]/2,
                                     self.size[0], self.size[1])

        # initialize shape
        fixdef = Box2D.b2FixtureDef()
        fixdef.shape = Box2D.b2PolygonShape()
        fixdef.shape.SetAsBox(self.size[0]/2, self.size[1]/2)
        fixdef.restitution = 0.4
        self.body.CreateFixture(fixdef)
Beispiel #5
0
    def __init__(self):
        self.count = 1000
        self.force = 10

        self.robots = {}
        self.bullets = []
        self.sprites = {}
        self.to_destroy = []

        halfx = 30
        self.ahalfx = 20
        halfy = 25
        self.ahalfy = 20

        gravity = (0, 0)
        doSleep = True

        self.timeStep = 1.0 / 60.0
        self.velIterations = 10
        self.posIterations = 8


        aabb = box2d.b2AABB()
        aabb.lowerBound = (-halfx, -halfy)
        aabb.upperBound = (halfx, halfy)

        self.w = box2d.b2World(gravity, doSleep)

        self.makearena()
Beispiel #6
0
    def __init__(self):
        self.count = 1000
        self.force = 10

        self.tanks = {}
        self.bullets = []
        self.sprites = {}
        self.to_destroy = []

        halfx = 30
        self.ahalfx = 20
        halfy = 25
        self.ahalfy = 20

        gravity = (0, 0)
        doSleep = True

        self.timeStep = 1.0 / 60.0
        self.velIterations = 10
        self.posIterations = 8


        aabb = box2d.b2AABB()
        aabb.lowerBound = (-halfx, -halfy)
        aabb.upperBound = (halfx, halfy)

        self.w = box2d.b2World(aabb, gravity, doSleep)
        self.w.GetGroundBody().SetUserData({'actor': None})

        self.makearena()
    def __init__(self, **kw):
        super(Framework, self).__init__(**kw)

        # Initialize the text display group
        self.textGroup = grText(self)

        # Load the font and record the screen dimensions
        self.font = pyglet.font.load(self.fontname, self.fontsize)
        self.screenSize = box2d.b2Vec2(self.width, self.height)

        # Box2D Initialization
        self.worldAABB = box2d.b2AABB()
        self.worldAABB.lowerBound = (-200.0, -100.0)
        self.worldAABB.upperBound = ( 200.0, 200.0)
        gravity = (0.0, -10.0)

        doSleep = True
        self.world = box2d.b2World(self.worldAABB, gravity, doSleep)
        self.destructionListener = fwDestructionListener()
        self.boundaryListener = fwBoundaryListener()
        self.contactListener = fwContactListener()
        self.debugDraw = fwDebugDraw()

        self.debugDraw.surface = self.screen

        self.destructionListener.test = self
        self.boundaryListener.test = self
        self.contactListener.test = self
        
        self.world.SetDestructionListener(self.destructionListener)
        self.world.SetBoundaryListener(self.boundaryListener)
        self.world.SetContactListener(self.contactListener)
        self.world.SetDebugDraw(self.debugDraw)

        self._viewCenter = box2d.b2Vec2(0,10.0)
Beispiel #8
0
    def __init__(self, x, y, puntos, dinamica=True, densidad=1.0,
            restitucion=0.56, friccion=10.5, amortiguacion=0.1,
            fisica=None, sin_rotacion=False):

        Figura.__init__(self)

        self._escala = 1

        self.puntos = puntos
        self.dinamica = dinamica
        self.fisica = fisica
        self.sin_rotacion = sin_rotacion

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        self.vertices = [(convertir_a_metros(x1) * self._escala, convertir_a_metros(y1) * self._escala) for (x1, y1) in self.puntos]

        fixture = box2d.b2FixtureDef(shape=box2d.b2PolygonShape(vertices=self.vertices),
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)

        self.userData = { 'id' : self.id }
        fixture.userData = self.userData

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(0, 0), fixtures=fixture)
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(position=(0, 0), fixtures=fixture)

        self._cuerpo.fixedRotation = self.sin_rotacion
Beispiel #9
0
    def __init__(self, world, x0, y0, theta0):
        # constants
        self.radius = 0.5

        # coordinates for drawing
        self.theta = theta0
        self.x = x0
        self.y = y0
        
        # first define a body
        bodyDef = physics.b2BodyDef()
        bodyDef.position = (self.x, self.y)
        # create body in our world
        self.body = world.CreateBody(bodyDef)

        # then define the attached shape
        # (it's a circle)
        shapeDef = physics.b2CircleDef()
        shapeDef.radius = self.radius
        shapeDef.density = 3
        # create the shape
        self.shape = self.body.CreateShape(shapeDef)
        # attach a mass
        self.body.SetMassFromShapes()

        # fixtures
        self.shape.friction = 1.0
        self.shape.restitution = 0.1

        # initial angular velocity
        self.body.angularVelocity = -30.0
 def LaunchRandomBomb(self):
     """
     Create a new bomb and launch it at the testbed.
     """
     p = box2d.b2Vec2( box2d.b2Random(-15.0, 15.0), 30.0 )
     v = -5.0 * p
     self.LaunchBomb(p, v)
Beispiel #11
0
    def __init__(self,world,top,size):


        scenter=(top[0]+(size[0]/2),
                top[1]+(size[1]/2))
        wcenter=world.s2wPos(scenter)

        extends=world.s2wScale(size)

        #print 'top: '+str(top)
        #print 'scenter: '+str(scenter)
        #print 'wcenter: '+str(wcenter)
        #print world.w2sPos(wcenter)
        #print 'size: '+str(size)
        #print 'extends: '+str(extends)
        #print world.w2sScale(extends)


        # Physics
        walldef=Box2D.b2BodyDef()
        walldef.position=Box2D.b2Vec2(wcenter[0],wcenter[1])
        walldef.userData={}
        wallbody=world.world.CreateBody(walldef)
        wallbody.iswall=True
        wallshape=Box2D.b2PolygonDef()
        width, height = extends
        wallshape.SetAsBox(width/2, height/2)
        wallbody.CreateShape(wallshape)

        # Display
        self.image=pygame.Surface(size)
        self.image.fill((56,71,216))
        self.rect = self.image.get_rect()
        self.rect.topleft=top
Beispiel #12
0
 def perform(self, time):
     """
     Morph line into real collideable figure.
     """
     #Define geometry and time data
     actor = self.master.owner
     v1 = actor.b2body.GetLocalPoint(pixels_to_tiles((self.start.x, self.start.y)))
     v2 = actor.b2body.GetLocalPoint(pixels_to_tiles((self.end.x, self.end.y)))
     if v2.x <= v1.x:
         v1, v2 = v2, v1
     vlen = math.sqrt((v2.x-v1.x)*(v2.x-v1.x)+(v2.y-v1.y)*(v2.y-v1.y))
     vcent = ((v1.x+v2.x)/2.0, (v1.y+v2.y)/2.0)
     vangle = math.asin((v2.y-v1.y)/vlen)
     v = self.end - self.start
     start = gm.Point2(self.start.x, self.start.y)
     self.trace = gm.LineSegment2(start, v)
     self.cshape = shape_to_cshape(self.trace)
     self.set_time_to_complete(time)
     self.b2fixture = actor.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(vlen, 0,
                                                                                              vcent, vangle)),
                                                                 isSensor=True, userData=self))
     self.b2fixture.filterData.categoryBits = B2SWING
     self.b2fixture.filterData.maskBits = B2HITZONE | B2SWING | B2BODYPART
     actor.world.addEventHandler(self.b2fixture, self.on_begin_contact, self.on_end_contact)
     self.schedule(self.update)
Beispiel #13
0
    def makeping(self, rname, rnd):
        robot = self.robots[rname]
        body = robot.turret

        segmentLength = 65.0

        blocalpos = box2d.b2Vec2(1.12, 0)

        segment = box2d.b2Segment()
        laserStart = (1.12, 0)
        laserDir = (segmentLength, 0.0)
        segment.p1 = body.GetWorldPoint(laserStart)
        segment.p2 = body.GetWorldVector(laserDir)
        segment.p2+=segment.p1

        lambda_, normal, shape = self.w.RaycastOne(segment, False, None)
        hitp = (1 - lambda_) * segment.p1 + lambda_ * segment.p2
        angle = robot.get_turretangle()
        dist = box2d.b2Distance(segment.p1, hitp)

        if shape is not None:
            hitbody = shape.GetBody()
            kind = hitbody.userData['kind']
            if kind == 'robot':
                actor = hitbody.userData['actor']
                if actor._pinged != rnd - 1:
                    actor._pinged = rnd
            return kind, angle, dist
        else:
            # Not sure why shape returns None here. Seems to be when the
            #   robot is pressed right up against a wall, though.
            return 'w', angle, 0
 def __init__(self,centre,radius,tc = None,angle=0):
     self.dead = False
     self.tc = tc
     if tc != None:
         self.InitPolygons(tc)
         self.visible = True
     else:
         self.visible = False
     self.bodydef = box2d.b2BodyDef()
     #This is inefficient, but it doesn't want to grab properly otherwise. Shitty hack but whatever
     self.bodydef.allowSleep = False
     self.midpoint = radius*math.sqrt(2)*globals.physics.scale_factor
     self.bodydef.position = box2d.b2Vec2(*(centre*globals.physics.scale_factor))
     self.bodydef.angle = angle
     self.shape = self.CreateShape(radius)
     self.shape.isSensor = self.is_sensor
     if not self.static:
         self.shape.userData = self
     if self.filter_group != None:
         self.shape.filter.groupIndex = self.filter_group
     self.bodydef.isBullet = self.isBullet
     self.body = globals.physics.world.CreateBody(self.bodydef)
     self.shape.density = self.mass
     self.shape.friction = 0.7
     self.shapeI = self.body.CreateShape(self.shape)
     self.child_joint = None
     self.parent_joint = None
     self.ExtraShapes()
     self.PhysUpdate([])
     self.health = Gobject.initial_health
    def create_mouse_joint(self, x, y):
        """ create a mouse joint to the body on world coordinates x, y """
        if self.mouse_joint:
            return
        world_coord = box2d.b2Vec2(self.debugDraw.screen_to_world((x, y)))
        aabb = box2d.b2AABB()
        aabb.lowerBound = world_coord - (0.001, 0.001)
        aabb.upperBound = world_coord + (0.001, 0.001)
        max_count = 10
        count, shapes = self.world.Query(aabb, max_count)

        body = (body for shape, body in ((shape, shape.GetBody())
                                         for shape in shapes)
                if not body.IsStatic()
                and body.GetMass() > 0.0
                and shape.TestPoint(body.GetXForm(), world_coord))
        body = list(itertools.islice(body, 1))
        body = body[0] if len(body) == 1 else None
        if body:
            md = box2d.b2MouseJointDef()
            md.body1 = self.world.GetGroundBody()
            md.body2 = body
            md.target = world_coord
            md.maxForce = 1000 * body.GetMass()
            self.mouse_joint = self.world.CreateJoint(md)
            body.WakeUp()
Beispiel #16
0
 def setup_world(self):
     self.worldAABB = box2d.b2AABB()
     self.worldAABB.lowerBound = (-2000.0, -2000.0)
     self.worldAABB.upperBound = (2000.0, 2000.0)
     self.gravity = (0.0, -9.81)
     doSleep = False
     self.world = box2d.b2World(self.worldAABB, self.gravity, doSleep) 
 def tryStop(self, horiz=True, vert=False):
     #print "trying to stop"
     self.curVel = self.body.GetLinearVelocity()
     if horiz:
         self.body.ApplyForce(Box2D.b2Vec2(FPS*(-self.curVel.x)*self.body.GetMass(),0), self.body.GetWorldCenter())
     if vert:
         self.body.ApplyForce(Box2D.b2Vec2(0,FPS*(-self.curVel.y)*self.body.GetMass()), self.body.GetWorldCenter())
Beispiel #18
0
 def load(self, angle, radius, length):
     _x, _y=length*math.cos(angle),length*math.sin(angle)
     position= self.parent.body.position.x+_x, self.parent.body.position.y+_y
     bd=box2d.b2BodyDef()
     bd.fixedRotation=False
     bd.position=position
     
     sd=box2d.b2CircleDef()
     sd.radius=radius
     sd.density=1.0
     sd.filter.categoryBits= PistonBall.catBits
   
     self.body=WorldConfig.world.CreateBody(bd)
     self.body.CreateShape(sd)
     self.body.SetMassFromShapes()
     self.body.userData=self
         
     pjd=box2d.b2PrismaticJointDef() 
     pjd.Initialize(self.parent.body, self.body, self.parent.body.position, (math.cos(angle), math.sin(angle)))
     pjd.motorSpeed = 30.0
     pjd.maxMotorForce = 1000.0
     pjd.enableMotor = True
     pjd.lowerTranslation = 0.0
     pjd.upperTranslation = 10.0
     pjd.enableLimit = True
     
     self.joint=WorldConfig.world.CreateJoint(pjd).getAsType()
Beispiel #19
0
    def load(self):
        bodyDef = box2d.b2BodyDef()

        if self.shape.type == WorldConfig.BOX:
            bodyDef.position = self.shape.center[0], self.shape.center[1]
            body = WorldConfig.world.CreateBody(bodyDef)
            
            shapeDef = box2d.b2PolygonDef()
            shapeDef.SetAsBox(self.shape.width / 2, self.shape.height / 2)            
        elif self.shape.type == WorldConfig.POLYGON:
            body = WorldConfig.world.CreateBody(bodyDef)
            
            shapeDef = box2d.b2PolygonDef()
            shapeDef.setVertices(self.shape.points)
        elif self.shape.type == WorldConfig.CIRCLE:
            bodyDef.position = self.shape.x, self.shape.y
            body = WorldConfig.world.CreateBody(bodyDef)
            
            shapeDef = box2d.b2CircleDef()
            shapeDef.radius = self.shape.radius
        else:
            raise 'unknown shape'
            return 
                         
#        shapeDef.density = 1
#        shapeDef.friction = 0.1
#        shapeDef.restitution = 1.0
        shapeDef.filter.categoryBits = Wall.catBits
#        shapeDef.filter.maskBits = Wall.maskBits
        body.CreateShape(shapeDef)
        body.SetMassFromShapes()
        body.userData = self
        self.body = body
Beispiel #20
0
    def load(self, size):
        bd=box2d.b2BodyDef()
        bd.position=self.shape.center[0], self.shape.center[1]

        sd=box2d.b2PolygonDef()
        sd.SetAsBox(size[0]/2.0, size[1]/2.0)
        sd.filter.categoryBits= BallGen.catBits
        self.body=WorldConfig.world.CreateBody(bd)
        self.body.CreateShape(sd)
        self.body.SetMassFromShapes()
        self.body.userData = self

        sd.density=2.0
        sd.SetAsBox(0.1, 1.8)
        bd.isBullet=True
        bd.position=self.body.position.x+1, self.body.position.y+4
        body_bar=WorldConfig.world.CreateBody(bd)
        body_bar.CreateShape(sd)
        body_bar.SetMassFromShapes()
                
        jd= box2d.b2RevoluteJointDef()
        jd.Initialize(self.body, body_bar, (self.body.position.x+1, self.body.position.y+size[1]/2.0))
        jd.maxMotorTorque= 30000.0
        jd.motorSpeed    = 2* box2d.b2_pi
        jd.enableMotor   = True        
        WorldConfig.world.CreateJoint(jd).getAsType()
        
        self.body_bar=body_bar
Beispiel #21
0
    def __init__(self, screen_size, gravity=(
            0.0, -9.0), ppm=100.0, renderer='pygame'):
        """ Init the world with boundaries and gravity, and init colors.

            Parameters:
              screen_size .. (w, h) -- screen size in pixels [int]
              gravity ...... (x, y) in m/s^2  [float] default: (0.0, -9.0)
              ppm .......... pixels per meter [float] default: 100.0
              renderer ..... which drawing method to use (str) default: 'pygame'

            Return: class Elements()
        """
        self.set_screenSize(screen_size)
        self.set_drawingMethod(renderer)

        # Create Subclasses
        self.add = add_objects.Add(self)
        self.callbacks = callbacks.CallbackHandler(self)
        self.camera = camera.Camera(self)

        # Gravity + Bodies will sleep on outside
        self.gravity = gravity
        self.doSleep = True

        # Create the World
        self.world = box2d.b2World(self.gravity, self.doSleep)
        bodyDef = box2d.b2BodyDef()
        self.world.groundBody = self.world.CreateBody(bodyDef)

        # Init Colors
        self.init_colors()

        # Set Pixels per Meter
        self.ppm = ppm
    def MouseDown(self, p):
        """
        Indicates that there was a left click at point p (world coordinates)
        """
        if self.mouseJoint != None:
            return

        # Make a small box.
        aabb = box2d.b2AABB()
        d = box2d.b2Vec2(0.001, 0.001)
        aabb.lowerBound = p - d
        aabb.upperBound = p + d

        # Query the world for overlapping shapes.
        body = None
        k_maxCount = 10

        (count, shapes) = self.world.Query(aabb, k_maxCount)
        for shape in shapes:
            shapeBody = shape.GetBody()
            if shapeBody.IsStatic() == False and shapeBody.GetMass() > 0.0:
                if shape.TestPoint(shapeBody.GetXForm(), p): # is it inside?
                    body = shapeBody
                    break
        
        if body:
            md = box2d.b2MouseJointDef()
            md.body1   = self.world.GetGroundBody()
            md.body2   = body
            md.target  = p
            md.maxForce= 1000.0 * body.GetMass()
            self.mouseJoint = self.world.CreateJoint(md)
            body.WakeUp()
Beispiel #23
0
def create_body(world, shape_type, position = (0, 0), angle = 0,
friction = None, restitution = None, density = None, linear_damping = None,
is_sensor = False, fixed_rotation = False,
body_type = Box2D.b2_dynamicBody, user_data = None, **kwargs):
	"""Creates a body.
	All parameters should be self-explanatory with a quick skim of the Box2D manual.
	
	**kwargs will be set on the shape type after its construction."""
	shape = shape_type()
	for i, j in kwargs.iteritems():
		setattr(shape, i, j)
	fixture_def = Box2D.b2FixtureDef()
	if friction is not None:
		fixture_def.friction = friction
	if restitution is not None:
		fixture_def.restitution = restitution
	if density is not None:
		fixture_def.density = density
	fixture_def.shape = shape
	fixture_def.isSensor = is_sensor
	body_def = Box2D.b2BodyDef()
	body_def.type = body_type
	body_def.position = position
	body_def.angle = angle
	body = world.CreateBody(body_def)
	body.CreateFixture(fixture_def)
	body.userData = user_data
	if linear_damping:
		body.linearDamping = linear_damping
	body.fixedRotation = fixed_rotation
	return body
 def handle_enter(self, parameters):
     self.next_state = parameters['next_state']
     self.next_state_parameters = parameters.setdefault('parameters', {})
     self.next_state_parameters={'totalScore':parameters['totalScore'],'edit':parameters['edit']}
     
     self.delay = parameters.setdefault('delay', 2000)
     self.time_passed = 0
     self.background = None
     self.shader = None
     self.screenFont = pygame.font.Font("data/font/fsex2p00_public.ttf", 70)
     text = u"Тоглоом дууслаа"
     self.message = self.screenFont.render(text, True, (255,255,255))
             
     bodyDef = box2d.b2BodyDef()
     bodyDef.position = (8, -2)
     bodyDef.angle = -0.5
     bodyDef.userData = self
     self.message_body = self.world.CreateBody(bodyDef)
     shapeDef = box2d.b2PolygonDef()
     shapeDef.density = 0.5
     shapeDef.friction = 0.95
     shapeDef.restitution = 0.5
     shapeDef.SetAsBox(self.message.get_width()/2.0/self.pixels_per_unit, 
                       self.message.get_height()/2.0/self.pixels_per_unit)
     self.message_body.CreateShape(shapeDef)
     self.message_body.SetMassFromShapes()
     self.message_body.SetLinearVelocity = box2d.b2Vec2(100.0,0)
Beispiel #25
0
    def Grapple(self,pos):
        if self.joint:
            self.UnGrapple()
            return
        diff = pos - self.GetPos()
        distance,angle = cmath.polar(complex(diff.x,diff.y))
        angle = (angle - (math.pi/2) - self.GetAngle())%(math.pi*2)
        #0 = pi*2 is straight ahead, pi is behind.
        #so 0.75 pi to 1.25 pi is allowed
        if not (angle <= self.min_shoot and angle >= self.max_shoot):
            return
        if distance > self.max_grapple:
            return

        #We need to determine if this point is in any objects...
        #We'll create a small AABB around the point, and get the list of potentially intersecting shapes,
        #then test each one to see if the point is inside it
        aabb = box2d.b2AABB()
        phys_pos = pos*self.physics.scale_factor
        #First of all make sure it's not inside us
        trans = box2d.b2XForm()
        trans.SetIdentity()
        p = phys_pos - Point(*self.body.position)
        if self.shapeI.TestPoint(trans,tuple(p)):
            return

        aabb.lowerBound.Set(phys_pos.x-0.1,phys_pos.y-0.1)
        aabb.upperBound.Set(phys_pos.x+0.1,phys_pos.y+0.1)
        (count,shapes) = self.physics.world.Query(aabb,10)
        for shape in shapes:
            trans = box2d.b2XForm()
            trans.SetIdentity()
            p = phys_pos - Point(*shape.GetBody().position)
            if shape.TestPoint(trans,tuple(p)):
                self.touching = shape
                self.contact  = p
                break
        else:
            self.touching = None
            self.contact  = None
        if not self.touching:
            return
        globals.sounds.grapple.play()
        #Tell the other body that it's in a joint with us so that 
        target = self.touching.userData
        if target == None:
            self.touching = None
            self.contact = None
            return

        target.parent_joint = self
        self.child_joint    = target

        joint = box2d.b2DistanceJointDef()
        joint.Initialize(self.body,self.touching.GetBody(),self.body.GetWorldCenter(),tuple(phys_pos))
        joint.collideConnected = True
        self.joint = self.physics.world.CreateJoint(joint)
        self.grappled = True
        self.grapple_quad.Enable()
    def SetProjectileBLPosition(self, dx, dy):

        projectile_start_pos = box2d.b2Vec2(dx,dy)
        projectile_start_pos.Normalize()
        projectile_start_pos.mul_float(self.midpoint.x + 30)
        projectile_start_pos.add_vector(box2d.b2Vec2(self.body.GetWorldCenter()[0] / globals.physics.scale_factor, self.body.GetWorldCenter()[1] / globals.physics.scale_factor))

        self.projectile_position = Point(projectile_start_pos[0], projectile_start_pos[1])
Beispiel #27
0
 def create_physics_world(self, size):
     # create world
     worldAABB = box2d.b2AABB()
     worldAABB.lowerBound = (-10, -10)
     worldAABB.upperBound = (size[0] + 10, size[1] + 10)
     gravity = box2d.b2Vec2(0.0, 0.0)
     doSleep = True
     world = box2d.b2World(worldAABB, gravity, doSleep)
     return world
Beispiel #28
0
	def __init__(self, world, x, y):
		bodyDef = b2.b2BodyDef()
		bodyDef.position = (x, y)
		self.body = world.CreateBody(bodyDef)
		shapeDef = b2.b2CircleDef()
		shapeDef.radius = 0.25
		shapeDef.isSensor = True
		self.body.CreateShape(shapeDef)
		self.body.userData = self
Beispiel #29
0
def update_shapes(world):
    # Check to see if any objects are sleeping or coming to a stop. 
    # Then give them a little push.
    for body in world.bodyList:
        v = body.GetLinearVelocity()
        if body.IsSleeping() or v.LengthSquared() < 0.2:
            i = body.GetWorldVector((box2d.b2Random(-200,200), box2d.b2Random(-200,200)))
            p = body.GetWorldPoint((0.0, 0.0))
            body.ApplyImpulse(i, p)
Beispiel #30
0
    def test_b2EdgeShape(self):
        world = b2.b2World()

        v1=(-10.0, 0.0)
        v2=(-7.0, -1.0)
        v3=(-4.0, 0.0)

        ground=world.CreateStaticBody(shapes=
                [b2.b2EdgeShape(vertices=[None, v1, v2, v3])])
Beispiel #31
0
    def _rect(
            self,
            pos,
            width,
            height,
            angle=0,
            dynamic=True,
            density=1.0,
            restitution=0.16,
            friction=0.5):
        # Add a rect without correcting any settings
        # meaning, pos and vertices are in meters
        # angle is now in radians ((degrees * pi) / 180))
        x, y = pos
        bodyDef = box2d.b2BodyDef()
        bodyDef.position = (x, y)

        userData = {'color': self.parent.get_color()}
        bodyDef.userData = userData

        # Create the Body
        if not dynamic:
            density = 0
        else:
            bodyDef.type = box2d.b2_dynamicBody

        body = self.parent.world.CreateBody(bodyDef)

        self.parent.element_count += 1

        # Add a shape to the Body
        boxDef = box2d.b2FixtureDef()
        polygonShape = box2d.b2PolygonShape()

        polygonShape.SetAsBox(width, height, (0, 0), angle)
        boxDef.shape = polygonShape
        boxDef.density = density
        boxDef.restitution = restitution
        boxDef.friction = friction
        body.CreateFixture(boxDef)

        return body
Beispiel #32
0
    def __init__(self, fisica, pilas, x, y, ancho, alto, dinamica=True,
                 densidad=1.0, restitucion=0.56, friccion=10.5,
                 amortiguacion=0.1, sin_rotacion=False, sensor=False):

        Figura.__init__(self, fisica, pilas)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)

        self._ancho = utils.convertir_a_metros(ancho)
        self._alto = utils.convertir_a_metros(alto)
        self._escala = 1

        self.fisica = fisica

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not dinamica:
            densidad = 0

        shape = box2d.b2PolygonShape(box=(self._ancho/2, self._alto/2))
        shape.SetAsBox(self._ancho/2.0, self._alto/2.0)
        fixture = box2d.b2FixtureDef(shape=shape,
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)

        # Agregamos un identificador para controlarlo posteriormente en
        # las colisiones.
        self.userData = {'id': self.id, 'figura': self}
        fixture.userData = self.userData

        self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(x, y), fixtures=fixture)

        self.sin_rotacion = sin_rotacion
        self.sensor = sensor
        self.dinamica = dinamica

        if not dinamica:
            self._cuerpo.mass = 1000000
Beispiel #33
0
    def attachRobotBody(self, world, **kargs):
        robotBody = world.CreateDynamicBody(**kargs)
        robotBody.CreateFixture(shape=Box2D.b2CircleShape(pos=(0, 0),
                                                          radius=self.radius),
                                density=1.0,
                                **kargs)

        for i, angle in enumerate(
                numpy.linspace(0, math.pi * 2, self.nbumpers + 1)[:-1]):
            c = numpy.array(
                (self.radius * math.sin(angle), self.radius * math.cos(angle)))
            robotBody.CreateFixture(
                shape=Box2D.b2PolygonShape(box=(self.bumper_w / 2,
                                                self.bumper_h / 2,
                                                (c[0], c[1]), angle)),
                density=0.01,
                isSensor=True,
                userData='b' + str(i))
        self.robotBody = robotBody
        return robotBody
Beispiel #34
0
def createTri(position, r=0.3, dynamic=True):
    global world, fig, ax
    bodyDef = Box2D.b2BodyDef()
    fixtureDef = Box2D.b2FixtureDef()
    if dynamic:
        bodyDef.type = Box2D.b2_dynamicBody
        fixtureDef.density = 1
    else:
        bodyDef.type = Box2D.b2_staticBody
        fixtureDef.density = 0

    bodyDef.position = position
    bodyDef.linearDamping = 70
    bodyDef.angularDamping = 50
    body = world.CreateBody(bodyDef)
    v = [(-r,-r),(0,r),(r,-r)]
    fixture = body.CreateFixture(shape=Box2D.b2PolygonShape(vertices=v), density=1.0, friction=0.3)
    body.userData = {"name":"tri"}

    return body
Beispiel #35
0
 def update(self):
     if self.body.linearVelocity.LengthSquared() < 0.01:
         self.body.PutToSleep()
     if self.kill:
         self.body.PutToSleep()
         if self.number > 0:
             world = self.body.GetWorld()
             world.DestroyBody(self.body)
         else:
             self.body.position = b2.b2Vec2(4, 4)
             self.kill = False
Beispiel #36
0
    def introduce_roads():
        # Introduce traffic map 
        self.traffic = Traffic()
        self.map_scale = OBS_SCALE   # map px per meters. set it to OBS_SCALE so no resizing necessary when getting observation

        contours = self.loadMap()
        num_contour = len(contours)
        print("num", num_contour)
        obstacles = []

        for contour in contours:
            vertices = []
            for item in contour:
                new_vec = b2.b2Vec2(float(item[0][0]/BOX_SCALE), float(item[0][1]/BOX_SCALE))
                vertices.append(new_vec)
            print("vertices")
            print(vertices)
            contour_shape = b2.b2PolygonShape(vertices=vertices)
            obstacle = self.world.CreateStaticBody(position=(0,0), shapes=contour_shape)
            obstacles.append(obstacle)
Beispiel #37
0
def add_asteroid_play_space(world: Box2D.b2World, left_border: float,
                            right_border: float, bottom_border: float,
                            top_border: float):
    fixture_shape = Box2D.b2PolygonShape()
    width = right_border - left_border + PLAYSPACE_PADDING
    height = top_border - bottom_border + PLAYSPACE_PADDING
    fixture_shape.SetAsBox(
        width, height,
        Box2D.b2Vec2(left_border + width / 2, bottom_border + height / 2), 0)

    fixture_def = Box2D.b2FixtureDef()
    fixture_def.shape = fixture_shape
    fixture_def.isSensor = True

    play_space_body_def = Box2D.b2BodyDef()
    play_space_body_def.fixtures = [fixture_def]
    play_space_body_def.type = Box2D.b2_staticBody
    play_space_body_def.position = (0, 0)

    return world.CreateBody(play_space_body_def)
Beispiel #38
0
def NNSD2D():
    a = 1
    b = np.sqrt(np.pi / 3)

    parameters = Box2D.Parameters(a, b)
    title = "2D box\n" + str(parameters)

    spectrum = Box2D.CalculateSpectrum(parameters, 1000000)
    unfolded = StretchSpectrum(spectrum)
    spacings = LevelSpacing(unfolded)

    PlotLevelDensity(spectrum,
                     lambda x: Box2D.LevelDensity(parameters, x),
                     extraTitle=title)
    PlotCummulativeLevelDensity(
        spectrum,
        lambda x: Box2D.CummulativeLevelDensity(parameters, x),
        extraTitle=title)

    PlotNNSD(spacings, Poisson, extraTitle=title)
Beispiel #39
0
 def add_line(self, p1, p2):
     p1 = self.renderer.to_world_frame(p1)
     p2 = self.renderer.to_world_frame(p2)
     m = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
     p1 = (p1[0] - m[0], p1[1] - m[1])  # compute p1 coordinates wrt m
     p2 = (p2[0] - m[0], p2[1] - m[1])  # compute p2 coordinates wrt m
     line = self.world.CreateStaticBody(
         position=m, shapes=[Box2D.b2EdgeShape(vertices=[p1, p2])])
     line.active = False
     line.userData = BouncingBalls.BodyData("line", visible=False)
     print("Warning line rendering disabled!")
Beispiel #40
0
 def __init__(self):
     self.action_space = spaces.Box( np.array([-1,0,0]), np.array([+1,+1,+1]) )  # steer, gas, brake
     self.observation_space = spaces.Box(low=0, high=255, shape=(STATE_H, STATE_W, 3))
     self.world = Box2D.b2World((0,0), contactListener=FrictionDetector(self))
     self.viewer = None
     self.invisible_state_window = None
     self.invisible_video_window = None
     self.road = None
     self.car = None
     self.reward = 0.0
     self.prev_reward = 0.0
Beispiel #41
0
    def __init__(self):
        self._seed()
        self.viewer = None

        self.world = Box2D.b2World()
        self.moon = None
        self.lander = None
        self.particles = []

        self.prev_reward = None
        self._reset()
Beispiel #42
0
 def __init__(self):
     self._seed()
     self.world = Box2D.b2World((0, 0),
                                contactListener=FrictionDetector(self))
     self.viewer = None
     self.invisible_state_window = None
     self.invisible_video_window = None
     self.road = None
     self.car = None
     self.reward = 0.0
     self.prev_reward = 0.0
Beispiel #43
0
    def PreSolve(self, contact, old_manifold):
        """
        This is a critical function when there are many contacts in the world.
        It should be optimized as much as possible.
        """
        if not (self.settings.drawContactPoints
                or self.settings.drawContactNormals or self.using_contacts):
            return
        elif len(self.points) > self.settings.maxContactPoints:
            return

        manifold = contact.manifold
        if manifold.pointCount == 0:
            return

        _, state2 = b2.b2GetPointStates(old_manifold, manifold)
        if not state2:
            return

        worldManifold = contact.worldManifold

        for i, _ in enumerate(state2):
            point = worldManifold.points[0]
            bodyA = contact.fixtureA.body
            bodyB = contact.fixtureB.body
            vA = bodyA.GetLinearVelocityFromWorldPoint(point)
            vB = bodyB.GetLinearVelocityFromWorldPoint(point)
            approachVelocity = b2.b2Dot(vB - vA, worldManifold.normal)
            # print("approachVelocity", approachVelocity)
            if abs(approachVelocity) > 1.0:
                self.collision = True

            self.points.append({
                'fixtureA': contact.fixtureA,
                'fixtureB': contact.fixtureB,
                'bodyA': bodyA,
                'bodyB': bodyB,
                'position': worldManifold.points[i],
                'normal': worldManifold.normal,
                'state': state2[i]
            })
Beispiel #44
0
 def __init__(self, world, number, x, y):
     self.kill = False
     self.number = number
     if number > 8:
         self.color = self.colors[number - 8]
         self.stripe = True
     else:
         self.color = self.colors[number]
         self.stripe = False
     bodyDef = b2.b2BodyDef()
     bodyDef.position = (x, y)
     bodyDef.linearDamping = 0.9
     self.body = world.CreateBody(bodyDef)
     shapeDef = b2.b2CircleDef()
     shapeDef.radius = 0.3
     shapeDef.density = 1.7
     shapeDef.friction = 0.03
     shapeDef.restitution = 0.95
     self.body.CreateShape(shapeDef)
     self.body.SetMassFromShapes()
     self.body.userData = self
Beispiel #45
0
def rubeVecToB2Vec2(rube_vec):
    """converter from rube json vector to b2Vec2 array

    :param rube_vec: a 2D vector in rube syntax
    :type rube_vec: a dict with x an y keys and a single item

    :return: a 2D point
    :rtype: b2Vec2

    """
    # converter from rube json vector to b2Vec2
    return b2.b2Vec2(rube_vec["x"], rube_vec["y"])
Beispiel #46
0
 def test_world(self):
     try:
         world = Box2D.b2World(Box2D.b2Vec2(0.0, -10.0), True)
         world = Box2D.b2World((0.0, -10.0), True)
         world = Box2D.b2World([0.0, -10.0], False)
         world = Box2D.b2World([0.0, -10.0])
         world = Box2D.b2World()
         world = Box2D.b2World(gravity=[0.0, -10.0])
     except Exception:
         self.fail("Failed to create world (%s)" % sys.exc_info()[1])
Beispiel #47
0
    def __init__(self, agent = True, num_bots = 1, track_form = 'X', \
                 write = False, data_path = 'car_racing_positions.csv', \
                 start_file = True, training_epoch = False):
        EzPickle.__init__(self)
        self.seed()
        self.contactListener_keepref = MyContactListener(self)
        self.world = Box2D.b2World(
            (0, 0), contactListener=self.contactListener_keepref)
        self.viewer = None
        self.invisible_state_window = None
        self.invisible_video_window = None
        self.road = None
        self.agent = agent
        self.car = None
        self.bot_cars = None
        self.reward = 0.0
        self.prev_reward = 0.0
        self.track_form = track_form
        self.data_path = data_path
        self.write = write
        self.training_epoch = training_epoch

        if write:
            car_title = ['car_angle', 'car_pos_x', 'car_pos_y']
            bots_title = []
            for i in range(num_bots):
                bots_title.extend([
                    f'car_bot{i+1}_angle', f'car_bot{i+1}_pos_x',
                    f'car_bot{i+1}_pos_y'
                ])
            with open(data_path, 'w') as f:
                f.write(','.join(car_title + bots_title))
                f.write('\n')

        # check the target position:
        self.moved_distance = deque(maxlen=1000)
        self.target = (0, 0)
        self.num_bots = num_bots

        self.start_file = start_file
        if start_file:
            with open("start_file.csv", 'r') as f:
                lines = f.readlines()
                self.start_positions = lines[15].strip().split(",")
                self.num_bots = len(self.start_positions) - 1

        self.action_space = spaces.Box(np.array([-1, 0, 0]),
                                       np.array([+1, +1, +1]),
                                       dtype=np.float32)  # steer, gas, brake
        self.observation_space = spaces.Box(low=0,
                                            high=255,
                                            shape=(STATE_H, STATE_W, 3),
                                            dtype=np.uint8)
Beispiel #48
0
def separate(verticesVec):
    # create an img
    vec = np.asarray(verticesVec)
    img = np.zeros((500, 500, 3))
    convex_polygon_list = []
    vec = vec[::-1]  # reverse the order, converting CCW to
    figsVec = calcShapes(vec)
    for i in range(len(vec)):
        verticesVec = []  # list of type b2Vec2
        vec = figsVec[i]
        for j in range(len(vec)):
            verticesVec.append(b2.b2Vec2(vec[j][0] / scale, vec[j][1] / scale))
Beispiel #49
0
 def __init__(self):
     self.seed()
     self.world = Box2D.b2World(gravity=(0, 0))
     self.pusher = None
     self.box = None
     #Actions: x-movement, y-movement (clipped -1 to 1)
     self.action_space = spaces.Box(np.ones(2) * -1, \
                                    np.ones(2), dtype=np.float32)
     #State: x-pusher, y-pusher, x-box, y-box, x-goal, y-goal
     self.observation_space = spaces.Box(np.ones(6) * MIN_COORD, \
                                         np.ones(6) * MAX_COORD, dtype=np.float32)
     self.reset()
Beispiel #50
0
    def motor(self, body, pt, torque=900, speed=-10):
        # Revolute joint to the background with motor torque applied
        b1 = self.parent.world.groundBody
        pt = self.to_b2vec(pt)

        jointDef = box2d.b2RevoluteJointDef()
        jointDef.Initialize(b1, body, pt)
        jointDef.maxMotorTorque = torque
        jointDef.motorSpeed = speed
        jointDef.enableMotor = True

        self.parent.world.CreateJoint(jointDef)
Beispiel #51
0
    def _ball(
            self,
            pos,
            radius,
            dynamic=True,
            density=1.0,
            restitution=0.16,
            friction=0.5):
        # Add a ball without correcting any settings
        # meaning, pos and vertices are in meters
        # Define the body
        x, y = pos
        bodyDef = box2d.b2BodyDef()
        bodyDef.position = (x, y)

        userData = {'color': self.parent.get_color()}
        bodyDef.userData = userData

        # Create the Body
        if not dynamic:
            density = 0
        else:
            bodyDef.type = box2d.b2_dynamicBody

        body = self.parent.world.CreateBody(bodyDef)

        self.parent.element_count += 1

        # Add a shape to the Body
        circleShape = box2d.b2CircleShape()
        circleShape.radius = radius
        circleDef = box2d.b2FixtureDef()
        circleDef.shape = circleShape
        circleDef.density = density
        circleDef.restitution = restitution
        circleDef.friction = friction

        body.CreateFixture(circleDef)

        return body
Beispiel #52
0
    def __init__(self):
        self._player_maximum_thrust = 2

        self._physics_world = Box2D.b2World(gravity=(0,0), doSleep=False, contactListener=ContactDamageInflicter(self))

        self._asteroid_shape = Box2D.b2CircleShape()
        self._asteroid_shape.radius = ASTEROID_RADIUS

        self._asteroid_fixture = Box2D.b2FixtureDef()
        self._asteroid_fixture.shape = self._asteroid_shape
        self._asteroid_fixture.density = 10
        self._asteroid_fixture.restitution = 1
        self._asteroid_fixture.friction = 1
        self._asteroid_fixture.filter.categoryBits = CollisionFilterCategory.ASTEROID
        self._asteroid_fixture.filter.maskBits = CollisionFilterCategory.ASTEROID | CollisionFilterCategory.PLAYER 

        self._ship_shape = Box2D.b2CircleShape()
        self._ship_shape.radius = PLAYER_RADIUS

        ship_fixture = Box2D.b2FixtureDef()
        ship_fixture.shape = self._ship_shape
        ship_fixture.density = 5
        ship_fixture.restitution = 1
        ship_fixture.friction = 1
        ship_fixture.filter.categoryBits = CollisionFilterCategory.PLAYER
        ship_fixture.filter.maskBits = CollisionFilterCategory.ASTEROID | CollisionFilterCategory.BORDER

        self._player_base_friction = 0.02
        self._player_thrust_extra_friction = 0.02

        self._player_maximum_turn_thrust = 1
        self._thrust_extra_turn_thrust = -0.3
        self._base_rotational_friction = 0.1
        self._thrust_extra_rotational_friction = 0.05

        ship_body_def = Box2D.b2BodyDef()
        ship_body_def.position = (
            5 + random() * (RIGHT_BORDER_X - 10),
            5 + random() * (TOP_BORDER_Y - 10)
        )
        ship_body_def.angle = random() * pi * 2
        ship_body_def.linearVelocity = (0,0)
        ship_body_def.linearDamping = self._player_base_friction
        ship_body_def.angularVelocity = 0
        ship_body_def.angularDamping = self._base_rotational_friction
        ship_body_def.fixtures = [ship_fixture]
        ship_body_def.type = Box2D.b2_dynamicBody
        ship_body_def.allowSleep = False

        self._player_ship = self._physics_world.CreateBody(ship_body_def)

        self._asteroids = self._create_starting_asteroids()
        self._asteroids_to_kill = []
        self._asteroid_extra_spawn_accumulator = 0
        self._asteroids_avoided_count = 0

        self._borders = borders.add_borders(self._physics_world, LEFT_BORDER_X, RIGHT_BORDER_X, BOTTOM_BORDER_Y, TOP_BORDER_Y)
        self._asteroid_play_space = asteroid_play_space.add_asteroid_play_space(self._physics_world, LEFT_BORDER_X, RIGHT_BORDER_X, BOTTOM_BORDER_Y, TOP_BORDER_Y)

        self.player_current_health = MAX_PLAYER_HEALTH
Beispiel #53
0
    def __init__(self, x0, target):
        super(PointMassWorld, self).__init__()
        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = b2.b2_pi
        self.initial_linear_velocity = (x0[2], x0[3])
        self.initial_angular_velocity = 0

        ground = self.world.CreateBody(position=(0, 20))
        ground.CreateEdgeChain([(-20, -20), (-20, 20), (20, 20), (20, -20),
                                (-20, -20)])

        xf1 = b2.b2Transform()
        xf1.angle = 0.3524 * b2.b2_pi
        xf1.position = b2.b2Mul(xf1.R, (1.0, 0.0))

        xf2 = b2.b2Transform()
        xf2.angle = -0.3524 * b2.b2_pi
        xf2.position = b2.b2Mul(xf2.R, (-1.0, 0.0))
        self.body = self.world.CreateDynamicBody(
            position=self.initial_position,
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            angularDamping=5,
            linearDamping=0.1,
            shapes=[
                b2.b2PolygonShape(
                    vertices=[xf1 * (-1, 0), xf1 * (1, 0), xf1 * (0, .5)]),
                b2.b2PolygonShape(
                    vertices=[xf2 * (-1, 0), xf2 * (1, 0), xf2 * (0, .5)])
            ],
            shapeFixture=b2.b2FixtureDef(density=1.0),
        )
        self.target = self.world.CreateStaticBody(
            position=target,
            angle=self.initial_angle,
            shapes=[
                b2.b2PolygonShape(
                    vertices=[xf1 * (-1, 0), xf1 * (1, 0), xf1 * (0, .5)]),
                b2.b2PolygonShape(
                    vertices=[xf2 * (-1, 0), xf2 * (1, 0), xf2 * (0, .5)])
            ],
        )
        self.target.active = False
Beispiel #54
0
    def __init__(self,
                 screen_size,
                 gravity=(0.0, -9.0),
                 ppm=100.0,
                 renderer='pygame'):
        """ Init the world with boundaries and gravity, and init colors.
        
            Parameters:
              screen_size .. (w, h) -- screen size in pixels [int]
              gravity ...... (x, y) in m/s^2  [float] default: (0.0, -9.0)
              ppm .......... pixels per meter [float] default: 100.0
              renderer ..... which drawing method to use (str) default: 'pygame'

            Return: class Elements()
        """
        self.set_screenSize(screen_size)
        self.set_drawingMethod(renderer)

        # Create Subclasses
        self.add = add_objects.Add(self)
        self.callbacks = callbacks.CallbackHandler(self)
        self.camera = camera.Camera(self)

        # Set Boundaries
        self.worldAABB = box2d.b2AABB()
        self.worldAABB.lowerBound = (-100.0, -100.0)
        self.worldAABB.upperBound = (100.0, 100.0)

        # Gravity + Bodies will sleep on outside
        self.gravity = gravity
        self.doSleep = True

        # Create the World
        self.world = box2d.b2World(self.worldAABB, self.gravity, self.doSleep)

        # Init Colors
        self.init_colors()

        # Set Pixels per Meter
        self.ppm = ppm
Beispiel #55
0
    def __init__(self,
                 n_walkers=2,
                 position_noise=1e-3,
                 angle_noise=1e-3,
                 reward_mech='local',
                 forward_reward=1.0,
                 fall_reward=-100.0,
                 drop_reward=-100.0,
                 terminate_on_fall=True):
        EzPickle.__init__(self, n_walkers, position_noise, angle_noise,
                          reward_mech, forward_reward, fall_reward,
                          drop_reward, terminate_on_fall)

        self.seed()
        self.viewer = None

        self.world = Box2D.b2World()
        self.terrain = None

        self.n_walkers = n_walkers
        init_x = TERRAIN_STEP * TERRAIN_STARTPAD / 2
        init_y = TERRAIN_HEIGHT + 2 * LEG_H
        self.start_x = [
            init_x + WALKER_SEPERATION * i * TERRAIN_STEP
            for i in xrange(self.n_walkers)
        ]
        self.walkers = [
            BipedalWalker(self.world, init_x=sx, init_y=init_y)
            for sx in self.start_x
        ]

        self.package_scale = n_walkers / 1.75
        self.package_length = PACKAGE_LENGTH / SCALE * self.package_scale

        self.total_agents = n_walkers

        self.prev_shaping = np.zeros(self.n_walkers)
        self.prev_package_shaping = 0.0

        self.position_noise = position_noise
        self.angle_noise = angle_noise
        self._reward_mech = reward_mech

        self.terrain_length = int(TERRAIN_LENGTH * n_walkers * 1 / 8.)

        self.forward_reward = forward_reward
        self.fall_reward = fall_reward
        self.drop_reward = drop_reward

        self.terminate_on_fall = terminate_on_fall

        self.reset()
Beispiel #56
0
def createBox(position,
              w=1.0,
              h=1.0,
              wdiv=1,
              hdiv=1,
              bDynamic=True,
              density=1,
              friction=0.3,
              damping=0,
              collisionGroup=None,
              restitution=None,
              bCollideNoOne=False,
              name="",
              angle=0):
    global world
    bodyDef = Box2D.b2BodyDef()
    bodyDef.position = position

    if (abs(world.gravity[1]) > 1):
        bodyDef.linearDamping = damping
        bodyDef.angularDamping = 0
    else:
        bodyDef.linearDamping = 70
        bodyDef.angularDamping = 50

    if bDynamic: bodyDef.type = Box2D.b2_dynamicBody
    else: bodyDef.type = Box2D.b2_staticBody

    body = world.CreateBody(bodyDef)
    body.userData = {"name": name}

    dw = w / float(wdiv)
    dh = h / float(hdiv)

    for i in range(hdiv):
        for j in range(wdiv):
            x = 2 * j * dw + (1 - wdiv) * dw
            y = 2 * i * dh + (1 - hdiv) * dh
            fixtureDef = createBoxFixture((x, y),
                                          width=dw,
                                          height=dh,
                                          bDynamic=bDynamic,
                                          density=density,
                                          friction=friction,
                                          collisionGroup=collisionGroup,
                                          restitution=restitution,
                                          angle=angle)
            if (bCollideNoOne):
                fixtureDef.filter.maskBits = 0x0000
            fixture = body.CreateFixture(fixtureDef)

    return body
    def __init__(self):
        self._seed()
        self.viewer = None
        self.world = Box2D.b2World()

        self.objects = []
        self.joints = []

        high = np.array([1] * 16)
        self.action_space = spaces.Box(-1, +1, (10,))
        self.observation_space = spaces.Box(-high, high)

        self._reset()
Beispiel #58
0
 def __init__(self, control_noise=0.):
     self.control_noise = control_noise
     self.seed()
     self.world = Box2D.b2World(gravity=(0, 0))
     self.pusher = None
     self.box = None
     # Actions: x-movement, y-movement (clipped -1 to 1)
     self.action_space = spaces.Box(np.ones(2) * -1, np.ones(2), dtype=np.float32)
     # State: pusher xy position, box xy position, pusher xy velocity, box xy velocity, goal xy position
     self.observation_space = spaces.Box(np.ones(10) * MIN_COORD, np.ones(10) * MAX_COORD, dtype=np.float32)
     self.reset()
     self.drawer = OpencvDrawFuncs(w=240, h=180, ppm=40)
     self.drawer.install()
Beispiel #59
0
    def __init__(self, world: Box2D.b2World, position=None, orientation=None):
        if self.__class__ == Body:
            raise NotImplementedError(
                'Abstract class Body cannot be instantiated.')
        self._color = np.array((93, 133, 195))
        self._highlight_color = np.array((238, 80, 62))

        if position is None:
            position = [.0, .0]
        position = np.asarray(position)

        if orientation is None:
            orientation = .0

        self._world = world
        self._body: Box2D.b2Body = world.CreateDynamicBody(
            position=Box2D.b2Vec2(*(_world_scale * position)),
            angle=orientation,
            linearDamping=self._linear_damping,
            angularDamping=self._angular_damping)
        self._body.linearVelocity = Box2D.b2Vec2(*[.0, .0])
        self._body.angularVelocity = .0
Beispiel #60
0
def createCircle(position,
                 r=0.3,
                 bDynamic=True,
                 bCollideNoOne=False,
                 density=1,
                 damping=0.1,
                 restitution=1,
                 friction=200,
                 name=""):
    global world, fig, ax
    bodyDef = Box2D.b2BodyDef()
    bodyDef.position = position
    if bDynamic:
        bodyDef.type = Box2D.b2_dynamicBody
    else:
        bodyDef.type = Box2D.b2_staticBody

    if (abs(world.gravity[1]) > 1):
        bodyDef.linearDamping = damping
        bodyDef.angularDamping = damping
    else:
        bodyDef.linearDamping = 70
        bodyDef.angularDamping = 30

    body = world.CreateBody(bodyDef)
    shape = Box2D.b2CircleShape(radius=r)

    mask = 0x0009
    if (bCollideNoOne):
        mask = 0x0000

    fixture = body.CreateFixture(maskBits=mask,
                                 shape=shape,
                                 density=density,
                                 restitution=restitution,
                                 friction=friction)
    body.userData = {"name": name}

    return body