Beispiel #1
0
def beneath(game):
    vertex = [[(10, game.HEIGHT - game.HEIGHT / 10),
               (10, game.HEIGHT - game.HEIGHT / 20)],
              [(10, game.HEIGHT - game.HEIGHT / 20),
               (game.WIDTH - game.WIDTH / 10, game.HEIGHT - game.HEIGHT / 20)],
              [(game.WIDTH - game.WIDTH / 10, game.HEIGHT - game.HEIGHT / 20),
               (game.WIDTH - game.WIDTH / 10, game.HEIGHT - game.HEIGHT / 10)]
    ]
    vertex = [[game.to_world(pt) for pt in vert] for vert in vertex]
    game.world.CreateStaticBody(
        shapes=[B2.b2EdgeShape(vertices=vertex[0]),
                B2.b2EdgeShape(vertices=vertex[1]),
                B2.b2EdgeShape(vertices=vertex[2])],
        position=(1, 0))
Beispiel #2
0
    def randomize(self, N, x0, x1, rng):
        # randomize how hilly the terrain is. lower number = softer hills
        terrain_freq = 10 + 14 * rng.rand()
        # construct random terrain using frequency domain low-freq noise
        modulus = np.exp(-np.arange(N) / terrain_freq) * rng.randn(N)
        argument = rng.randn(N)
        freqspace = modulus * np.cos(argument) + 1j * modulus * np.sin(
            argument)
        z = np.fft.fft(freqspace).real
        zmin = np.min(z)
        zmax = np.max(z)
        self.z = (TERRAIN_Z_RANGE / (zmax - zmin)) * (z - zmin)
        self.x = np.linspace(x0, x1, N)

        # construct box2d world for lidar.
        self.world = Box2D.b2World()
        verts = zip(self.x, self.z)
        nverts = len(verts)
        for i in range(nverts - 1):
            p0, p1 = verts[i], verts[i + 1]
            edge = Box2D.b2EdgeShape(vertices=[p0, p1])
            body = Box2D.b2BodyDef(
                type=Box2D.b2_staticBody,
                fixtures=Box2D.b2FixtureDef(shape=edge, friction=0),
            )
            self.world.CreateBody(body)
Beispiel #3
0
    def create_screen_bounding_box(self):
        screen_center = (self.screenWidth_m / 2, self.screenHeight_m / 2)
        bottom_left = (-screen_center[0], -screen_center[1])
        bottom_right = (screen_center[0], -screen_center[1])
        top_right = (screen_center[0], screen_center[1])
        top_left = (-screen_center[0], screen_center[1])

        self.bounding_box = self.world.CreateStaticBody(
            position=screen_center,
            shapes=[
                Box2D.b2EdgeShape(vertices=[bottom_left, bottom_right]),
                Box2D.b2EdgeShape(vertices=[bottom_right, top_right]),
                Box2D.b2EdgeShape(vertices=[top_right, top_left]),
                Box2D.b2EdgeShape(vertices=[top_left, bottom_left])
            ])
        self.bounding_box.userData = BouncingBalls.BodyData(
            "world_bounding_box", visible=False)
    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 #5
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 #6
0
 def _init_box2d(self):
     assert (self.x is not None)
     assert (self.z is not None)
     # construct box2d world for lidar.
     self.world = Box2D.b2World()
     verts = zip(self.x, self.z)
     nverts = len(verts)
     for i in range(nverts - 1):
         p0, p1 = verts[i], verts[i + 1]
         edge = Box2D.b2EdgeShape(vertices=[p0, p1])
         body = Box2D.b2BodyDef(
             type=Box2D.b2_staticBody,
             fixtures=Box2D.b2FixtureDef(shape=edge, friction=0),
         )
         self.world.CreateBody(body)
Beispiel #7
0
 def setup_b2body(self):
     super(Actor, self).setup_b2body()
     pix_to_tile = pixels_to_tiles
     rx, ry = pix_to_tile((self.cshape.rx, self.cshape.ry))
     self.b2body.CreateFixture(
         b2.b2FixtureDef(
             shape=b2.b2PolygonShape(
                 vertices=[(-rx, ry), (-rx, -ry + 0.1), (-rx + 0.1, -ry), (rx - 0.1, -ry), (rx, -ry + 0.1), (rx, ry)]
             )
         )
     )
     self.b2body.fixtures[-1].filterData.categoryBits = B2SMTH | B2ACTOR
     self.b2body.CreateFixture(
         b2.b2FixtureDef(shape=b2.b2EdgeShape(vertex1=(-rx, -ry), vertex2=(rx, -ry)), isSensor=True)
     )
     self.b2body.fixtures[-1].filterData.categoryBits = B2GNDSENS
     self.b2body.fixtures[-1].filterData.maskBits = B2LEVEL | B2ACTOR
     self.world.addEventHandler(self.b2body.fixtures[-1], self.on_ground_begin, self.on_ground_end)
Beispiel #8
0
    def build(self):
        root = Widget()
        root.bind(on_touch_move=self.generate_one)

        self.world = world = b2d.b2World(gravity=(0, -100))

        # plane for the ground, all other the window.
        # The ground
        ground = self.world.CreateBody(
            shapes=b2d.b2EdgeShape(vertices=[(0, 0), (1000, 0)])
        )

        # generate circles
        self.circles = []
        for x in xrange(5):
            c = Circle(y=500 + x * 5, x=500+x, world=world)
            self.circles.append(c)
            root.add_widget(c)
        Clock.schedule_interval(self._update_world, 1 / 60.)

        return root
Beispiel #9
0
def _create_fixtures(left_border : float, right_border : float, bottom_border : float, top_border : float):
    # create in clockwise rotation so the edges face inwards
    vertices = (
        (left_border, bottom_border),
        (left_border, top_border),
        (right_border, top_border),
        (right_border, bottom_border)
    )
    fixture_defs = []
    for i, _ in enumerate(vertices):
        next_i = (i + 1) % 4

        side_border_shape = Box2D.b2EdgeShape()
        side_border_shape.vertex1 = vertices[i]
        side_border_shape.vertex2 = vertices[next_i]

        border_fixture_def = Box2D.b2FixtureDef()
        border_fixture_def.shape = side_border_shape
        border_fixture_def.friction = 0
        border_fixture_def.density = 0
        border_fixture_def.filter.categoryBits = CollisionFilterCategory.BORDER
        fixture_defs.append(border_fixture_def)
    
    return fixture_defs
Beispiel #10
0
def add_fixture(b2_world_body, jsw, jsw_fixture):
    """add a fixture to a body

    :param b2_world_body: a body
    :type b2_world_body: b2Body

    :param jsw: dictionary defining all the gropups of data
                in the json file
    :type jsw: dict(sting: variant)

    :param jsw_fixture: a fixture
    :type jsw_fixture: b2Fixture

    """

    # create and fill fixture definition
    fixtureDef = b2.b2FixtureDef()

    # Done with issues:
    ### missing pybox2d "filter" b2BodyDef property

    # special case for rube documentation of
    # "filter-categoryBits": 1, //if not present, interpret as 1
    if "filter-categoryBits" in list(jsw_fixture.keys()):
        setAttr(jsw_fixture, "filter-categoryBits", fixtureDef, "categoryBits")
    else:
        fixtureDef.categoryBits = 1

    # special case for Rube Json property
    # "filter-maskBits": 1, //if not present, interpret as 65535
    if "filter-maskBits" in list(jsw_fixture.keys()):
        setAttr(jsw_fixture, "filter-maskBits", fixtureDef, "maskBits")
    else:
        fixtureDef.maskBits = 65535

    setAttr(jsw_fixture, "density", fixtureDef)
    setAttr(jsw_fixture, "group_index", fixtureDef, "groupIndex")
    setAttr(jsw_fixture, "friction", fixtureDef)
    setAttr(jsw_fixture, "sensor", fixtureDef, "isSensor")
    setAttr(jsw_fixture, "restitution", fixtureDef)

    # fixture has one shape that is
    # polygon, circle or chain in json
    # chain may be open or loop, or edge in pyBox2D
    if "circle" in list(jsw_fixture.keys()):  # works ok
        if jsw_fixture["circle"]["center"] == 0:
            center_b2Vec2 = b2.b2Vec2(0, 0)
        else:
            center_b2Vec2 = rubeVecToB2Vec2(jsw_fixture["circle"]["center"])
        fixtureDef.shape = b2.b2CircleShape(
            pos=center_b2Vec2,
            radius=jsw_fixture["circle"]["radius"],
        )

    if "polygon" in list(jsw_fixture.keys()):  # works ok
        polygon_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["polygon"]["vertices"])
        fixtureDef.shape = b2.b2PolygonShape(vertices=polygon_vertices)

    if "chain" in list(jsw_fixture.keys()):  # works ok
        chain_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["chain"]["vertices"])

        if len(chain_vertices) >= 3:
            # closed-loop b2LoopShape
            # Done
            if "hasNextVertex" in list(jsw_fixture["chain"].keys()):

                # del last vertice to prevent crash from first and last
                # vertices being to close
                del chain_vertices[-1]

                fixtureDef.shape = b2.b2LoopShape(
                    vertices_loop=chain_vertices,
                    count=len(chain_vertices),
                )

                setAttr(
                    jsw_fixture["chain"],
                    "hasNextVertex",
                    fixtureDef.shape,
                    "m_hasNextVertex",
                )
                setB2Vec2Attr(
                    jsw_fixture["chain"],
                    "nextVertex",
                    fixtureDef,
                    "m_nextVertex",
                )

                setAttr(
                    jsw_fixture["chain"],
                    "hasPrevVertex",
                    fixtureDef.shape,
                    "m_hasPrevVertex",
                )
                setB2Vec2Attr(jsw_fixture["chain"], "prevVertex",
                              fixtureDef.shape, "m_prevVertex")

            else:  # open-ended ChainShape
                # Done
                fixtureDef.shape = b2.b2ChainShape(
                    vertices_chain=chain_vertices,
                    count=len(chain_vertices),
                )

        # json chain is b2EdgeShape
        # Done
        if len(chain_vertices) < 3:
            fixtureDef.shape = b2.b2EdgeShape(vertices=chain_vertices, )

    # create fixture
    b2_world_body.CreateFixture(fixtureDef)
Beispiel #11
0
    def __init__(self,
                 world_size=50,
                 gravity=-1,
                 num_obstacles=3,
                 obstacle_sizes=3,
                 obstacle_noise=1,
                 xinit=None,
                 yinit=None,
                 rinit=None,
                 targetx=None,
                 targety=None):

        # physics world
        self.world = b2.b2World(gravity=(0, gravity))

        # static objects in the scene that do not move
        # for drawing purposes
        # the drawer should scale these for visualization when drawing

        # create a box around the working area
        # vertices are in physics coords.
        a = 1
        box_vertices = [(a, a), (world_size - a, a),
                        (world_size - a, world_size - a), (a, world_size - a)]
        self.time = 0

        # a static body. A body is just a point with no shape
        self._box = self.world.CreateStaticBody(shapes=b2.b2EdgeShape(
            vertices=box_vertices))
        # fixtures are added shapes to point-wise bodies.
        # these determine the collisions and such while the bodies contain
        # the speed and such
        for i in range(4):
            verts = [box_vertices[i], box_vertices[(i + 1) % 4]]
            self._box.CreateEdgeFixture(vertices=verts, density=0, friction=0)

        # for each obstacle
        for i in range(num_obstacles):

            # find a good obstacle position
            while True:

                # compute random obstacle position
                x = random.uniform(0, world_size)
                y = random.uniform(0, world_size)

                # Euclidian distance to initial AUV position
                d = math.sqrt((x - xinit)**2 + (y - yinit)**2)

                # maximum obstacle radius
                r = obstacle_sizes + obstacle_noise - obstacle_noise / 2

                # minimum collision free distance
                if d > rinit + r:
                    pass
                else:
                    continue

                # Euclidian distance to target position
                d = math.sqrt((x - targetx)**2 + (y - targety)**2)

                # minimum confliction free distance
                if d > r + C.TARGET_AREA:
                    break
                else:
                    continue

            pos = [x, y]
            verts = _make_random_obstacle(pos, obstacle_sizes, obstacle_noise)
            obs = self.world.CreateStaticBody(shapes=b2.b2PolygonShape(
                vertices=verts))
Beispiel #12
0
    # static objects in the scene that do not move
    # for drawing purposes
    # the drawer should scale these for visualization when drawing

    # create a simple line for the seafloor
    floor_x = 0
    floor_y = 1
    floor_length = 100
    # vertices are in physics coords.
    floor_vertices = [(floor_x - floor_length, floor_y),
                      (floor_x + floor_length, floor_y)]

    # a static body. A body is just a point with no shape
    floor = world.CreateStaticBody(
        shapes=b2.b2EdgeShape(
            vertices=floor_vertices))
    # fixtures are added shapes to point-wise bodies.
    # these determine the collisions and such while the bodies contain
    # the speed and such
    floor.CreateEdgeFixture(vertices=floor_vertices,
                            density=0,
                            friction=0.1)

    # auv starting position
    auv_x = 5
    auv_y = floor_y + 10
    auv_l = 3
    auv_h = 1
    # CCW, centered on the rectangle center
    auv_vertices = [
        # top right
def add_fixture(
        b2_world_body,
        jsw,
        jsw_fixture,
        ):
     # create and fill fixture definition
    fixtureDef = b2.b2FixtureDef()

    # Done with issues:
    ### missing pybox2d "filter" b2BodyDef property

    # special case for rube documentation of
    #"filter-categoryBits": 1, //if not present, interpret as 1
    if "filter-categoryBits" in jsw_fixture.keys():
        setAttr(jsw_fixture, "filter-categoryBits", fixtureDef, "categoryBits")
    else:
        fixtureDef.categoryBits = 1

    # special case for Rube Json property
    #"filter-maskBits": 1, //if not present, interpret as 65535
    if "filter-maskBits" in jsw_fixture.keys():
        setAttr(jsw_fixture, "filter-maskBits", fixtureDef, "maskBits")
    else:
        fixtureDef.maskBits = 65535

    setAttr(jsw_fixture, "density", fixtureDef)
    setAttr(jsw_fixture, "filter-groupIndex", fixtureDef, "groupIndex")
    setAttr(jsw_fixture, "friction", fixtureDef)
    setAttr(jsw_fixture, "sensor", fixtureDef, "isSensor")
    setAttr(jsw_fixture, "restitution", fixtureDef)

    # fixture has one shape that is
    # polygon, circle or chain in json
    # chain may be open or loop, or edge in pyBox2D
    if "circle" in jsw_fixture.keys():  # works ok
        if jsw_fixture["circle"]["center"] == 0:
            center_b2Vec2 = b2.b2Vec2(0, 0)
        else:
            center_b2Vec2 = rubeVecToB2Vec2(
                jsw_fixture["circle"]["center"]
                )
        fixtureDef.shape = b2.b2CircleShape(
            pos=center_b2Vec2,
            radius=jsw_fixture["circle"]["radius"],
            )

    if "polygon" in jsw_fixture.keys():  # works ok
        polygon_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["polygon"]["vertices"]
            )
        fixtureDef.shape = b2.b2PolygonShape(vertices=polygon_vertices)

    if "chain" in jsw_fixture.keys():  # works ok
        chain_vertices = rubeVecArrToB2Vec2Arr(
            jsw_fixture["chain"]["vertices"]
            )

        if len(chain_vertices) >= 3:
            # closed-loop b2LoopShape
            # Done
            if "hasNextVertex" in jsw_fixture["chain"].keys():

                # del last vertice to prevent crash from first and last
                # vertices being to close
                del chain_vertices[-1]

                fixtureDef.shape = b2.b2LoopShape(
                    vertices_loop=chain_vertices,
                    count=len(chain_vertices),
                    )

                setAttr(
                    jsw_fixture["chain"],
                    "hasNextVertex",
                    fixtureDef.shape,
                    "m_hasNextVertex",
                    )
                setB2Vec2Attr(
                    jsw_fixture["chain"],
                    "nextVertex",
                    fixtureDef,
                    "m_nextVertex",
                    )

                setAttr(
                    jsw_fixture["chain"],
                    "hasPrevVertex",
                    fixtureDef.shape,
                    "m_hasPrevVertex",
                    )
                setB2Vec2Attr(
                    jsw_fixture["chain"],
                    "prevVertex",
                    fixtureDef.shape,
                    "m_prevVertex"
                    )

            else:  # open-ended ChainShape
                # Done
                fixtureDef.shape = b2.b2ChainShape(
                    vertices_chain=chain_vertices,
                    count=len(chain_vertices),
                    )

        # json chain is b2EdgeShape
        # Done
        if len(chain_vertices) < 3:
            fixtureDef.shape = b2.b2EdgeShape(
                vertices=chain_vertices,
                )

    # create fixture
    b2_world_body.CreateFixture(fixtureDef)