예제 #1
0
    def __init__(self,
                 world: BulletWorld,
                 entity: Entity,
                 radius=1,
                 height=2,
                 name='Player',
                 **opts) -> None:
        super().__init__(BulletCapsuleShape(radius / 2, height / 2, 1),
                         radius / 2, name)
        self.np = application.base.render.attachNewNode(self)

        if entity.parent:
            self.np.reparent_to(entity.parent)

        rotation = Vec3(0, 0, 0)
        if None in rotation:
            hpr = entity.getHpr()
            for x in range(len(hpr)):
                rotation[x] = hpr[x]
        self.np.setHpr(rotation)

        self.np.setPos(entity.x, entity.y, entity.z)
        entity.reparent_to(self.np)

        world.attachCharacter(self)

        self.__fall_speed = None
        self.__jump_speed = None
        self.__max_jump_height = None

        for x in opts:
            setattr(self, x, opts[x])
예제 #2
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Plane
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

        # collision
        visNP = loader.loadModel('../models/coryf2.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(render)
        pos = (7., 60.0, 3.8)
        visNP.setPos(pos[0], pos[1], pos[2])

        bodyNPs = BulletHelper.fromCollisionSolids(visNP, True)
        for bodyNP in bodyNPs:
            bodyNP.reparentTo(render)
            bodyNP.setPos(pos[0], pos[1], pos[2])

            if isinstance(bodyNP.node(), BulletRigidBodyNode):
                bodyNP.node().setMass(0.0)
                bodyNP.node().setKinematic(True)
                bodyNP.setCollideMask(BitMask32.allOn())
                self.world.attachRigidBody(bodyNP.node())
예제 #3
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), -1)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.bit(0))

    self.world.attachRigidBody(np.node())

    # Boxes
    self.boxes = [None,]*6

    for i in range(6):
      shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-1'))
      np.node().setMass(1.0)
      np.node().addShape(shape)

      self.world.attachRigidBody(np.node())

      self.boxes[i] = np

      visualNP = loader.loadModel('models/box.egg')
      visualNP.reparentTo(np)

    self.boxes[0].setPos(-3, -3, 0)
    self.boxes[1].setPos( 0, -3, 0)
    self.boxes[2].setPos( 3, -3, 0)
    self.boxes[3].setPos(-3,  3, 0)
    self.boxes[4].setPos( 0,  3, 0)
    self.boxes[5].setPos( 3,  3, 0)

    self.boxes[0].setCollideMask(BitMask32.bit(1))
    self.boxes[1].setCollideMask(BitMask32.bit(2))
    self.boxes[2].setCollideMask(BitMask32.bit(3))
    self.boxes[3].setCollideMask(BitMask32.bit(1))
    self.boxes[4].setCollideMask(BitMask32.bit(2))
    self.boxes[5].setCollideMask(BitMask32.bit(3))

    self.boxNP = self.boxes[0]

    self.world.setGroupCollisionFlag(0, 1, True)
    self.world.setGroupCollisionFlag(0, 2, True)
    self.world.setGroupCollisionFlag(0, 3, True)

    self.world.setGroupCollisionFlag(1, 1, False)
    self.world.setGroupCollisionFlag(1, 2, True)
예제 #4
0
    def __init__(self,
                 camera,
                 debug=False,
                 audio3d=None,
                 client=None,
                 server=None):
        self.objects = {}

        self.incarnators = []

        self.collidables = set()

        self.updatables = set()
        self.updatables_to_add = set()
        self.garbage = set()
        self.scene = NodePath('world')

        # Set up the physics world. TODO: let maps set gravity.
        self.gravity = DEFAULT_GRAVITY
        self.physics = BulletWorld()
        self.physics.set_gravity(self.gravity)

        self.debug = debug

        if debug:
            debug_node = BulletDebugNode('Debug')
            debug_node.show_wireframe(True)
            debug_node.show_constraints(True)
            debug_node.show_bounding_boxes(False)
            debug_node.show_normals(False)
            np = self.scene.attach_new_node(debug_node)
            np.show()
            self.physics.set_debug_node(debug_node)
예제 #5
0
파일: z1.py 프로젝트: t4nuj/3d-pathfinding
    def __init__(self):
        ShowBase.__init__(self)
        loadPrcFileData('', 'bullet-enable-contact-events true')

        world = BulletWorld()
        self.world = world
        world.setGravity(Vec3(0, 0, -9.81))
        base.cam.setPos(0,-50,1)

        # Cameras
        base.camNode.setActive(0)
        self.cam1 = base.makeCamera(base.win, displayRegion=(0,.5,0.5,1))
        self.cam2 = base.makeCamera(base.win, displayRegion=(.5,1,0.5,1))
        self.cam1.setPos(-10,-50,1)
        self.cam2.setPos(10,-50,1)
        # base.camList[0].setPos(0,-100, 1)

        # Plane
        shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        node = BulletRigidBodyNode('Ground')
        node.addShape(shape)
        np = render.attachNewNode(node)
        np.setPos(0, 0, 0)
        self.world.attachRigidBody(node)
        scene = loader.loadModel('Ground2/Ground2')
        scene.reparentTo(render)
        self.newGame()

        taskMgr.add(self.update, 'update')
예제 #6
0
 def __init__(self,
              camera,
              debug=False,
              audio3d=None,
              client=None,
              server=None):
     self.objects = {}
     self.incarnators = []
     self.collidables = set()
     self.updatables = set()
     self.updatables_to_add = set()
     self.garbage = set()
     self.render = NodePath('world')
     self.camera = camera
     self.audio3d = audio3d
     self.ambient = self._make_ambient()
     self.celestials = CompositeObject()
     self.sky = self.attach(Sky())
     # Set up the physics world. TODO: let maps set gravity.
     self.gravity = DEFAULT_GRAVITY
     self.physics = BulletWorld()
     self.physics.set_gravity(self.gravity)
     self.debug = debug
     self.client = client
     self.server = server
     if debug:
         debug_node = BulletDebugNode('Debug')
         debug_node.show_wireframe(True)
         debug_node.show_constraints(True)
         debug_node.show_bounding_boxes(False)
         debug_node.show_normals(False)
         np = self.render.attach_new_node(debug_node)
         np.show()
         self.physics.set_debug_node(debug_node)
    def generate(self):
        DistributedObjectAI.generate(self)
        self.air.battleZones[self.zoneId] = self

        self.bspLoader = BSPLoader()
        self.bspLoader.setAi(True)
        self.bspLoader.setMaterialsFile("phase_14/etc/materials.txt")
        #self.bspLoader.setTextureContentsFile("phase_14/etc/texturecontents.txt")
        self.bspLoader.setServerEntityDispatcher(self)
        AvatarWatcher.zoneId = self.zoneId
        
        # Link up networked entities
        from src.coginvasion.szboss import (DistributedTriggerAI, DistributedFuncDoorAI,
                                            DistributedButtonAI, DistributedFuncRotatingAI, LogicCounter,
                                            HintsAI, InfoTimer, InfoBgmAI)
        from src.coginvasion.szboss.InfoPlayerStart import InfoPlayerStart
        self.bspLoader.linkServerEntityToClass("trigger_once",          DistributedTriggerAI.DistributedTriggerOnceAI)
        self.bspLoader.linkServerEntityToClass("trigger_multiple",      DistributedTriggerAI.DistributedTriggerMultipleAI)
        self.bspLoader.linkServerEntityToClass("func_door",             DistributedFuncDoorAI.DistributedFuncDoorAI)
        self.bspLoader.linkServerEntityToClass("func_button",           DistributedButtonAI.DistributedButtonAI)
        self.bspLoader.linkServerEntityToClass("func_rotating",         DistributedFuncRotatingAI.DistributedFuncRotatingAI)
        self.bspLoader.linkServerEntityToClass("logic_counter",         LogicCounter.LogicCounter)
        self.bspLoader.linkServerEntityToClass("info_hint_cover",       HintsAI.InfoHintCover)
        self.bspLoader.linkServerEntityToClass("info_timer",            InfoTimer.InfoTimer)
        self.bspLoader.linkServerEntityToClass("info_player_start",     InfoPlayerStart)
        self.bspLoader.linkServerEntityToClass("info_bgm",              InfoBgmAI.InfoBgmAI)
        
        self.physicsWorld = BulletWorld()
        self.physicsWorld.setGravity(Vec3(0, 0, -32.1740))
        self.bspLoader.setPhysicsWorld(self.physicsWorld)
예제 #8
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Plane
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
        np.node().addShape(shape)
        np.setPos(0, 0, -1)
        np.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(np.node())

        # initial vehicles
        self.vehicles = []
        #self.vehicles.append(basicVehicle(self,[13,2,0.5],18)) # [10,0.1,0.5] is vehicle start position
        self.vehicles.append(
            basicVehicle(self, [10, 0.1, 0.5],
                         18))  # [10,0.1,0.5] is vehicle start position
        sensor = basicSensor(self)  # initial sensor
        sensor.setVehicle(self.vehicles[0])
        self.vehicles[0].setSensor(sensor)
        self.vehicles[0].sensor.align()
        agent = basicAgent(50, 10.8, 15)  # initial agent
        agent.setVehicle(self.vehicles[0])
        self.vehicles[0].setAgent(agent)
예제 #9
0
    def __init__(self):
        ShowBase.__init__(self)
        # Bullet Physics Setup
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        node = BulletRigidBodyNode('Ground')
        node.addShape(shape)
        ground_np = self.render.attachNewNode(node)
        ground_np.setPos(0, 0, -60)
        # noinspection PyArgumentList
        self.world.attach(node)

        # Mouse and Camera Setup
        self.disable_mouse()
        self.camera.set_pos(20, -150, 5)
        self.follow_np = self.render.attach_new_node('Follow')

        # Instructions
        self.add_instruction('(p) to generate a Plane', 0.06)
        self.add_instruction('(b) to generate a Cuboid/Box', 0.12)
        self.add_instruction('(s) to generate a Spheroid', 0.18)
        self.add_instruction('(c) to generate a Cylinder', 0.24)
        self.add_instruction('(f1) to toggle wireframe', 0.30)
        self.add_instruction('(esc) to exit', 0.36)
        # Input
        self.accept('escape', sys.exit, [0])
        self.accept('p', self.generate_plane)
        self.accept('b', self.generate_cuboid)
        self.accept('s', self.generate_spheroid)
        self.accept('c', self.generate_cylinder)
        self.accept('f1', self.toggle_wireframe)

        self.task_mgr.add(self.update, 'update')
예제 #10
0
    def __init__(self, root_nodepath, world):
        self.world = BulletWorld()
        self.world.setGravity((0, 0, -9.81))

        self._timestep = 1 / world.tick_rate

        # # Seems that this does not function
        # on_contact_added = PythonCallbackObject(self._on_contact_added)
        # self.world.set_contact_added_callback(on_contact_added)
        # on_filter = PythonCallbackObject(self._filter_collision)
        # self.world.set_filter_callback(on_filter)

        self.listener = DirectObject()
        self.listener.accept('bullet-contact-added', self._on_contact_added)
        self.listener.accept('bullet-contact-destroyed', self._on_contact_removed)

        self.tracked_contacts = defaultdict(int)
        self.existing_collisions = set()

        # Debugging info
        debug_node = BulletDebugNode('Debug')
        debug_node.showWireframe(True)
        debug_node.showConstraints(True)
        debug_node.showBoundingBoxes(False)
        debug_node.showNormals(False)

        # Add to world
        self.debug_nodepath = root_nodepath.attachNewNode(debug_node)
        self.world.set_debug_node(debug_node)
        self.debug_nodepath.show()
예제 #11
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-3, 0, 4)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(0, 0, 0)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Slider
        frameA = TransformState.make_pos_hpr(LPoint3(2, 0, 0),
                                             LVector3(0, 0, 45))
        frameB = TransformState.make_pos_hpr(LPoint3(0, -3, 0),
                                             LVector3(0, 0, 0))

        slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
        slider.set_debug_draw_size(2.0)
        slider.set_lower_linear_limit(0)
        slider.set_upper_linear_limit(6)
        slider.set_lower_angular_limit(-60)
        slider.set_upper_angular_limit(60)
        self.world.attach(slider)
class TerrainPhysics():
    def __init__(self, ):
        # World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))


    def setup(self, terrain, player):
        """Bullet has to be started before some things in the program to avoid crashes."""
        self.terrain = terrain
        self.player = player

        # Demo
        spawn = player.attachNewNode("spawnPoint")
        spawn.setPos(0, -5, 7)
        self.demo = TerrainPhysicsDemo2(self.world, spawn)
        taskMgr.add(self.update, 'physics')

    def test(self):
        self.demo.start()

    def update(self, task):
        dt = globalClock.getDt()
        self.world.doPhysics(dt)
        return task.cont
예제 #13
0
def rayHit(pfrom, pto, geom):
    """
    NOTE: this function is quite slow
    find the nearest collision point between vec(pto-pfrom) and the mesh of nodepath

    :param pfrom: starting point of the ray, Point3
    :param pto: ending point of the ray, Point3
    :param geom: meshmodel, a panda3d datatype
    :return: None or Point3

    author: weiwei
    date: 20161201
    """

    bulletworld = BulletWorld()
    facetmesh = BulletTriangleMesh()
    facetmesh.addGeom(geom)
    facetmeshnode = BulletRigidBodyNode('facet')
    bullettmshape = BulletTriangleMeshShape(facetmesh, dynamic=True)
    bullettmshape.setMargin(0)
    facetmeshnode.addShape(bullettmshape)
    bulletworld.attachRigidBody(facetmeshnode)
    result = bulletworld.rayTestClosest(pfrom, pto)

    if result.hasHit():
        return result.getHitPos()
    else:
        return None
예제 #14
0
    def __init__(self, scene, suncgDatasetRoot=None, debug=False, objectMode='box',
                 agentRadius=0.1, agentHeight=1.6, agentMass=60.0, agentMode='capsule'):

        super(Panda3dBulletPhysics, self).__init__()

        self.__dict__.update(scene=scene, suncgDatasetRoot=suncgDatasetRoot, debug=debug, objectMode=objectMode,
                             agentRadius=agentRadius, agentHeight=agentHeight, agentMass=agentMass, agentMode=agentMode)

        if suncgDatasetRoot is not None:
            self.modelCatMapping = ModelCategoryMapping(os.path.join(
                suncgDatasetRoot, "metadata", "ModelCategoryMapping.csv"))
        else:
            self.modelCatMapping = None

        self.bulletWorld = BulletWorld()
        self.bulletWorld.setGravity(Vec3(0, 0, -9.81))

        if debug:
            debugNode = BulletDebugNode('physic-debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(False)
            debugNode.showBoundingBoxes(True)
            debugNode.showNormals(False)
            self.debugNodePath = self.scene.scene.attachNewNode(debugNode)
            self.debugNodePath.show()
            self.bulletWorld.setDebugNode(debugNode)
        else:
            self.debugNodePath = None

        self._initLayoutModels()
        self._initAgents()
        self._initObjects()

        self.scene.worlds['physics'] = self
예제 #15
0
파일: physics.py 프로젝트: croxis/itf
class PhysicsSystem(sandbox.EntitySystem):
    """System that interacts with the Bullet physics world"""
    def init(self):
        self.accept("addSpaceship", self.addSpaceship)
        self.world = BulletWorld()

    def begin(self):
        dt = globalClock.getDt()
        self.world.doPhysics(dt)
        #world.doPhysics(dt, 10, 1.0/180.0)

    def process(self, entity):
        pass

    def addSpaceship(self, component, shipName, position, linearVelcocity):
        component.bulletShape = BulletSphereShape(5)
        component.node = BulletRigidBodyNode(shipName)
        component.node.setMass(1.0)
        component.node.addShape(component.bulletShape)
        component.nodePath = universals.solarSystemRoot.attachNewNode(component.node)
        addBody(component.node)
        position = sandbox.get_system(solarSystem.SolarSystemSystem).solarSystemRoot.find("**/Earth").getPos()
        #component.nodePath.setPos(position + Point3(6671, 0, 0))
        component.nodePath.setPos(position)
        #component.node.setLinearVelocity(Vec3(0, 7.72983, 0))
        component.node.setLinearVelocity(linearVelcocity)
예제 #16
0
 def __init__(self):
     # a dynamic world, moving objects or objects which react to other objects should be placed here
     self.dynamic_world = BulletWorld()
     CollisionGroup.set_collision_rule(self.dynamic_world)
     self.dynamic_world.setGravity(Vec3(0, 0, -9.81))  # set gravity
     # a static world which used to query position/overlap .etc. Don't implement doPhysics() in this world
     self.static_world = BulletWorld()
예제 #17
0
    def __init__(self, objpath, handpkg, gdb):
        self.objtrimesh=trimesh.load_mesh(objpath)
        self.objcom = self.objtrimesh.center_mass
        self.objtrimeshconv=self.objtrimesh.convex_hull
        # oc means object convex
        self.ocfacets, self.ocfacetnormals = self.objtrimeshconv.facets_over(.9999)

        # for dbaccess
        self.dbobjname = os.path.splitext(os.path.basename(objpath))[0]

        # use two bulletworld, one for the ray, the other for the tabletop
        self.bulletworldray = BulletWorld()
        self.bulletworldhp = BulletWorld()
        # plane to remove hand
        self.planebullnode = cd.genCollisionPlane(offset=0)
        self.bulletworldhp.attachRigidBody(self.planebullnode)

        self.handpkg = handpkg
        self.handname = handpkg.getHandName()
        self.hand = handpkg.newHandNM(hndcolor=[0,1,0,.1])
        # self.rtq85hnd = rtq85nm.Rtq85NM(hndcolor=[1, 0, 0, .1])

        # for dbsave
        # each tpsmat4 corresponds to a set of tpsgripcontacts/tpsgripnormals/tpsgripjawwidth list
        self.tpsmat4s = None
        self.tpsgripcontacts = None
        self.tpsgripnormals = None
        self.tpsgripjawwidth = None

        # for ocFacetShow
        self.counter = 0

        self.gdb = gdb
        self.loadFreeAirGrip()
예제 #18
0
    def setup(self):

        # World
        self.worldNP = render.attachNewNode("World")
        self.GUI = self.worldNP.attachNewNode("GUI")
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode("Debug"))
        self.debugNP.show()
        self.debugNP.node().showWireframe(True)
        self.debugNP.node().showConstraints(True)
        self.debugNP.node().showBoundingBoxes(False)
        self.debugNP.node().showNormals(True)

        self.setDefaults()
        self.addGUI()
        self.createCurve()

        self.world = BulletWorld()
        # self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setGravity(Vec3(0, 0, 0))
        self.world.setDebugNode(self.debugNP.node())

        # Plane (static)
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        nodePath = self.worldNP.attachNewNode(BulletRigidBodyNode("Ground"))
        nodePath.node().addShape(shape)
        nodePath.setPos(0, 0, 0)
        nodePath.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(nodePath.node())

        self.loadModel()
예제 #19
0
def bulletRayHit(pfrom, pto, geom):
    """
    NOTE: this function is quite slow
    find the nearest collision point between vec(pto-pfrom) and the mesh of nodepath

    :param pfrom: starting point of the ray, Point3
    :param pto: ending point of the ray, Point3
    :param geom: meshmodel, a panda3d datatype
    :return: None or Point3

    author: weiwei
    date: 20161201
    """

    bulletworld = BulletWorld()
    facetmesh = BulletTriangleMesh()
    facetmesh.addGeom(geom)
    facetmeshnode = BulletRigidBodyNode('facet')
    bullettmshape = BulletTriangleMeshShape(facetmesh, dynamic=True)
    bullettmshape.setMargin(1e-6)
    facetmeshnode.addShape(bullettmshape)
    bulletworld.attach(facetmeshnode)
    result = bulletworld.rayTestClosest(pfrom, pto)

    if result.hasHit():
        return result.getHitPos()
    else:
        return None
예제 #20
0
    def __init__(self, objpath, handpkg, gdb):
        self.objtrimesh = trimesh.load_mesh(objpath)
        self.objcom = self.objtrimesh.center_mass
        self.objtrimeshconv = self.objtrimesh.convex_hull
        # oc means object convex
        self.ocfacets, self.ocfacetnormals = self.objtrimeshconv.facets_over(
            .9999)

        # for dbaccess
        self.dbobjname = os.path.splitext(os.path.basename(objpath))[0]

        # use two bulletworld, one for the ray, the other for the tabletop
        self.bulletworldray = BulletWorld()
        self.bulletworldhp = BulletWorld()
        # plane to remove hand
        self.planebullnode = cd.genCollisionPlane(offset=0)
        self.bulletworldhp.attachRigidBody(self.planebullnode)

        self.handpkg = handpkg
        self.handname = handpkg.getHandName()
        self.hand = handpkg.newHandNM(hndcolor=[0, 1, 0, .1])
        # self.rtq85hnd = rtq85nm.Rtq85NM(hndcolor=[1, 0, 0, .1])

        # for dbsave
        # each tpsmat4 corresponds to a set of tpsgripcontacts/tpsgripnormals/tpsgripjawwidth list
        self.tpsmat4s = None
        self.tpsgripcontacts = None
        self.tpsgripnormals = None
        self.tpsgripjawwidth = None

        # for ocFacetShow
        self.counter = 0

        self.gdb = gdb
        self.loadFreeAirGrip()
예제 #21
0
    def SetupBulletTerrain(self):
        self.worldNP = self.render.attachNewNode('World')
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        img = PNMImage(Filename(self.PngDEM))
        if self.MeterScale < 1.1:
            shape = BulletHeightfieldShape(img, self.HeightRange, ZUp)
        else:
            shape = BulletHeightfieldShape(img, self.HeightRange, ZUp)

        shape.setUseDiamondSubdivision(True)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Heightfield'))
        np.node().addShape(shape)

        offset = self.MeterScale * self.PixelNr / 2.0
        np.setPos(+offset, +offset,
                  +(self.HeightRange / 2.0) + self.OffsetHeight)

        np.setSx(self.MeterScale)
        np.setSy(self.MeterScale)
        np.setCollideMask(BitMask32.allOn())

        self.world.attachRigidBody(np.node())
예제 #22
0
    def __init__(self):
        base.accept('f1', self.toggleDebug)

        self.debugNode = BulletDebugNode('Debug')
        self.debugNode.showWireframe(True)
        self.debugNode.showConstraints(True)
        self.debugNode.showBoundingBoxes(False)
        self.debugNode.showNormals(False)
        self.debugNP = base.render.attachNewNode(self.debugNode)
        # self.debugNP.show()

        # World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Terrain
        visNP = base.loader.loadModel('models/terrain.egg')

        mesh = BulletTriangleMesh()
        for x in visNP.findAllMatches('**/+GeomNode'):
            geom = x.node().getGeom(0)
            mesh.addGeom(geom)
        shape = BulletTriangleMeshShape(mesh, dynamic=True)

        body = BulletRigidBodyNode('Bowl')
        bodyNP = base.render.attachNewNode(body)
        bodyNP.node().addShape(shape)
        bodyNP.setPos(0, 0, 1)
        bodyNP.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(bodyNP.node())

        visNP.reparentTo(bodyNP)

        shapex = BulletBoxShape(5)
        bodyx = BulletRigidBodyNode('Egg')
        bodyNPx = base.render.attachNewNode(bodyx)
        bodyNPx.setPos(0, 0, 3)
        bodyNPx.node().setMass(100.0)
        bodyNPx.node().addShape(shapex)
        self.world.attachRigidBody(bodyNPx.node())
        # visNP.reparentTo(bodyNPx)

        # Player
        self.players = []
        self.myId = -1
        self.speed = Vec3(0, 0, 0)
        self.walk_speed = 2.5

        # Camera
        base.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)

        # SkySphere
        Sky()

        self.initCam()
예제 #23
0
    def __init__(self, objpath, nxtrobot, handpkg, gdb):

        self.graphtpp0 = GraphTpp(objpath, nxtrobot, handpkg, gdb, 'rgt')
        self.armname = armname

        self.gdb = gdb
        self.robot = nxtrobot
        self.hand = handpkg.newHandNM(hndcolor=[1, 0, 0, .1])

        # plane to remove hand
        self.bulletworld = BulletWorld()
        self.planebullnode = cd.genCollisionPlane()
        self.bulletworld.attachRigidBody(self.planebullnode)

        # add tabletop plane model to bulletworld
        this_dir, this_filename = os.path.split(__file__)
        ttpath = Filename.fromOsSpecific(
            os.path.join(
                os.path.split(this_dir)[0] + os.sep, "grip", "supports",
                "tabletop.egg"))
        self.ttnodepath = NodePath("tabletop")
        ttl = loader.loadModel(ttpath)
        ttl.instanceTo(self.ttnodepath)

        # self.endnodeids is a dictionary where
        # self.endnodeids['rgt'] equals self.startnodeids
        # self.endnodeids['lft'] equals self.endnodeids # in right->left order
        self.endnodeids = {}

        # load retraction distances
        self.rethandx, self.retworldz, self.retworlda, self.worldz = self.gdb.loadIKRet(
        )
        # worlda is default for the general grasps on table top
        # for assembly at start and goal, worlda is computed by assembly planner
        self.worlda = Vec3(0, 0, 1)

        self.gnodesplotpos = {}

        self.freegripid = []
        self.freegripcontacts = []
        self.freegripnormals = []
        self.freegriprotmats = []
        self.freegripjawwidth = []

        # for start and goal grasps poses:
        radiusgrip = 1
        self.__xyzglobalgrippos_startgoal = {}
        for k, globalgripid in enumerate(self.graphtpp.globalgripids):
            xypos = [
                radiusgrip *
                math.cos(2 * math.pi / len(self.graphtpp.globalgripids) * k),
                radiusgrip *
                math.sin(2 * math.pi / len(self.graphtpp.globalgripids) * k)
            ]
            self.__xyzglobalgrippos_startgoal[globalgripid] = [
                xypos[0], xypos[1], 0
            ]

        self.__loadFreeAirGrip()
예제 #24
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

    #img = PNMImage(Filename('models/elevation2.png'))
    #shape = BulletHeightfieldShape(img, 1.0, ZUp)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(np.node())

    # Box
    shape = BulletBoxShape(Vec3(1.0, 3.0, 0.3))

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
    np.node().setMass(10.0)
    np.node().addShape(shape)
    np.setPos(3, 0, 4)
    np.setH(20.0)
    np.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(np.node())

    # Character
    self.crouching = False

    h = 1.75
    w = 0.4
    shape = BulletCapsuleShape(w, h - 2 * w, ZUp)

    self.character = BulletCharacterControllerNode(shape, 0.4, 'Player')
    # self.character.setMass(1.0)
    self.characterNP = self.worldNP.attachNewNode(self.character)
    self.characterNP.setPos(-2, 0, 14)
    self.characterNP.setH(45)
    self.characterNP.setCollideMask(BitMask32.allOn())
    self.world.attachCharacter(self.character)

    self.actorNP = Actor('models/ralph/ralph.egg', {
                         'run' : 'models/ralph/ralph-run.egg',
                         'walk' : 'models/ralph/ralph-walk.egg',
                         'jump' : 'models/ralph/ralph-jump.egg'})
    self.actorNP.reparentTo(self.characterNP)
    self.actorNP.setScale(0.3048) # 1ft = 0.3048m
    self.actorNP.setH(180)
    self.actorNP.setPos(0, 0, -1)
예제 #25
0
    def create_physics(self):
        """Create the physical world, and start a task to simulate physics"""

        self.world = BulletWorld()
        self.world.set_gravity((0, 0, -9.81))

        self.physics_on = False
        self.taskMgr.add(self.step_physics, "physics")
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().showWireframe(True)
        self.debugNP.node().showConstraints(True)
        self.debugNP.node().showBoundingBoxes(False)
        self.debugNP.node().showNormals(False)

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attachNewNode(bodyA)
        bodyNP.node().addShape(shape)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(-3, 0, 4)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyA)

        # Box B
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attachNewNode(bodyB)
        bodyNP.node().addShape(shape)
        bodyNP.node().setMass(1.0)
        bodyNP.node().setDeactivationEnabled(False)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(0, 0, 0)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyB)

        # Slider
        frameA = TransformState.makePosHpr(Point3(2, 0, 0), Vec3(0, 0, 45))
        frameB = TransformState.makePosHpr(Point3(0, -3, 0), Vec3(0, 0, 0))

        slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
        slider.setDebugDrawSize(2.0)
        slider.setLowerLinearLimit(0)
        slider.setUpperLinearLimit(6)
        slider.setLowerAngularLimit(-60)
        slider.setUpperAngularLimit(60)
        self.world.attachConstraint(slider)
예제 #27
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Ground
        shape = BulletPlaneShape(LVector3(0, 0, 1), 0)

        #img = PNMImage(Filename('models/elevation.png'))
        #shape = BulletHeightfieldShape(img, 1.0, ZUp)

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Ground'))
        np.node().add_shape(shape)
        np.set_pos(0, 0, -1)
        np.set_collide_mask(BitMask32.all_on())

        self.world.attach(np.node())

        # Box
        shape = BulletBoxShape(LVector3(1.0, 3.0, 0.3))

        np = self.worldNP.attach_new_node(BulletRigidBodyNode('Box'))
        np.node().set_mass(10.0)
        np.node().add_shape(shape)
        np.set_pos(3, 0, 4)
        np.setH(20.0)
        np.set_collide_mask(BitMask32.all_on())

        self.world.attach(np.node())

        # Character
        self.crouching = False

        h = 1.75
        w = 0.4
        shape = BulletCapsuleShape(w, h - 2 * w, ZUp)
        self.character = BulletCharacterControllerNode(shape, 0.4, 'Player')
        self.characterNP = self.worldNP.attach_new_node(self.character)
        self.characterNP.set_pos(-2, 0, 14)
        self.characterNP.set_h(45)
        self.characterNP.set_collide_mask(BitMask32.all_on())
        self.world.attach(self.character)

        self.actorNP = Actor(
            'samples/roaming-ralph/models/ralph.egg.pz', {
                'run': 'samples/roaming-ralph/models/ralph-run.egg.pz',
                'walk': 'samples/roaming-ralph/models/ralph-walk.egg.pz'
            })
        self.actorNP.reparent_to(self.characterNP)
        self.actorNP.set_scale(0.3048)  # 1ft = 0.3048m
        self.actorNP.setH(180)
        self.actorNP.set_pos(0, 0, -1)
예제 #28
0
    def __init__(self, objpath,objpathWorkcell, handpkg, dbidstablepos,readser):
        self.dbobjname = os.path.splitext(os.path.basename(objpath))[0]

        self.objtrimesh=None

        self.dbidstablepos = dbidstablepos

        [objrotmat, objposmat]=self.loadDropStablePos()
        self.loadObjModel(objpath,objrotmat,objposmat)

        self.objcom = self.objtrimesh.center_mass
        self.objtrimeshconv=self.objtrimesh.convex_hull
        # oc means object convex
        self.ocfacets, self.ocfacetnormals = self.objtrimeshconv.facets_over(.9999)

        # for dbaccess

        # use two bulletworld, one for the ray, the other for the tabletop
        self.bulletworldray = BulletWorld()
        self.bulletworldhp = BulletWorld()
        # plane to remove hand
        self.planebullnode = cd.genCollisionPlane(offset=-55)
        self.bulletworldhp.attachRigidBody(self.planebullnode)


        #workcell to remove hand

        self.workcellmesh = trimesh.load_mesh(objpathWorkcell)
        self.objgeom = pandageom.packpandageom(self.workcellmesh.vertices, self.workcellmesh.face_normals,
                                               self.workcellmesh.faces)
        self.objmeshbullnode = cd.genCollisionMeshGeom(self.objgeom)
        self.bulletworldhp.attachRigidBody(self.objmeshbullnode)
        node = GeomNode('obj')
        node.addGeom(self.objgeom)
        self.worcell = NodePath('obj')
        self.worcell.attachNewNode(node)
        self.worcell.reparentTo(base.render)


        self.handpkg = handpkg
        self.handname = handpkg.getHandName()
        self.hand = handpkg.newHandNM(hndcolor=[0,1,0,.1])
        # self.rtq85hnd = rtq85nm.Rtq85NM(hndcolor=[1, 0, 0, .1])

        # for dbsave
        # each tpsmat4 corresponds to a set of tpsgripcontacts/tpsgripnormals/tpsgripjawwidth list
        self.tpsmat4s = None
        self.tpsgripcontacts = None
        self.tpsgripnormals = None
        self.tpsgripjawwidth = None

        # for ocFacetShow
        self.counter = 0

        self.gdb = gdb
        #get dropfreegrip

        self.loadDropfreeGrip()
예제 #29
0
    def setup(self):
        self.worldNP = render.attach_new_node('World')

        # World
        self.debugNP = self.worldNP.attach_new_node(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().show_wireframe(True)
        self.debugNP.node().show_constraints(True)
        self.debugNP.node().show_bounding_boxes(False)
        self.debugNP.node().show_normals(False)

        self.world = BulletWorld()
        self.world.set_gravity(LVector3(0, 0, -9.81))
        self.world.set_debug_node(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attach_new_node(bodyA)
        bodyNP.node().add_shape(shape)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(-2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyA)

        # Box B
        shape = BulletBoxShape(LVector3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attach_new_node(bodyB)
        bodyNP.node().add_shape(shape)
        bodyNP.node().set_mass(1.0)
        bodyNP.node().set_deactivation_enabled(False)
        bodyNP.set_collide_mask(BitMask32.all_on())
        bodyNP.set_pos(2, 0, 1)

        visNP = loader.load_model('models/box.egg')
        visNP.clear_model_nodes()
        visNP.reparent_to(bodyNP)

        self.world.attach(bodyB)

        # Hinge
        pivotA = LPoint3(2, 0, 0)
        pivotB = LPoint3(-4, 0, 0)
        axisA = LVector3(0, 0, 1)
        axisB = LVector3(0, 0, 1)

        hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA,
                                      axisB, True)
        hinge.set_debug_draw_size(2.0)
        hinge.set_limit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
        self.world.attach(hinge)
예제 #30
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()
        self.debugNP.node().showWireframe(True)
        self.debugNP.node().showConstraints(True)
        self.debugNP.node().showBoundingBoxes(False)
        self.debugNP.node().showNormals(False)

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Box A
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyA = BulletRigidBodyNode('Box A')
        bodyNP = self.worldNP.attachNewNode(bodyA)
        bodyNP.node().addShape(shape)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(-2, 0, 1)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyA)

        # Box B
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        bodyB = BulletRigidBodyNode('Box B')
        bodyNP = self.worldNP.attachNewNode(bodyB)
        bodyNP.node().addShape(shape)
        bodyNP.node().setMass(1.0)
        bodyNP.node().setDeactivationEnabled(False)
        bodyNP.setCollideMask(BitMask32.allOn())
        bodyNP.setPos(2, 0, 1)

        visNP = loader.loadModel('models/box.egg')
        visNP.clearModelNodes()
        visNP.reparentTo(bodyNP)

        self.world.attachRigidBody(bodyB)

        # Hinge
        pivotA = Point3(2, 0, 0)
        pivotB = Point3(-4, 0, 0)
        axisA = Vec3(0, 0, 1)
        axisB = Vec3(0, 0, 1)

        hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA,
                                      axisB, True)
        hinge.setDebugDrawSize(2.0)
        hinge.setLimit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
        self.world.attachConstraint(hinge)
예제 #31
0
    def setup(self):
        self.worldNP = render.attachNewNode('World')

        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        self.debugNP.show()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        self.world.setDebugNode(self.debugNP.node())

        # Ground
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
        np.node().addShape(shape)
        np.setPos(0, 0, 0)
        np.setCollideMask(BitMask32(0x0f))

        self.world.attachRigidBody(np.node())

        # Box
        shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(0, 0, 4)
        np.setCollideMask(BitMask32(0x0f))

        self.world.attachRigidBody(np.node())

        self.boxNP = np
        visualNP = loader.loadModel('models/box.egg')
        visualNP.reparentTo(self.boxNP)

        # Sphere
        shape = BulletSphereShape(0.6)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Sphere'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(3, 0, 4)
        np.setCollideMask(BitMask32(0x0f))

        self.world.attachRigidBody(np.node())

        # Cone
        shape = BulletConeShape(0.6, 1.0)

        np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone'))
        np.node().setMass(1.0)
        np.node().addShape(shape)
        np.setPos(6, 0, 4)
        np.setCollideMask(BitMask32(0x0f))

        self.world.attachRigidBody(np.node())
예제 #32
0
def genAvailableFAGsSgl(base, basepath, baseMat4, objpath, objMat4, gdb, handpkg):
    """
    find the collision freeairgrips of objpath without considering rotation

    :param base: panda base
    :param basepath: the path of base object
    :param objpath: the path of obj object, the object to be assembled
    :param baseMat4, objMat4: all in world coordinates, not relative
    :param gdb: grasp db
    :param handpkg: hand package
    :return: [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair]

    author: weiwei
    date: 20170307
    """

    bulletworld = BulletWorld()

    robothand = handpkg.newHandNM(hndcolor=[1, 0, 0, .1])

    basetrimesh = trimesh.load_mesh(basepath)
    basenp = pg.packpandanp(basetrimesh.vertices, basetrimesh.face_normals, basetrimesh.faces)
    basenp.setMat(baseMat4)
    basebullnode = cd.genCollisionMeshNp(basenp, base.render)

    bulletworld.attachRigidBody(basebullnode)

    dbobjname = os.path.splitext(os.path.basename(objpath))[0]
    objfag = F*g(gdb, dbobjname, handpkg)

    assgripcontacts = []
    assgripnormals = []
    assgriprotmat4s = []
    assgripjawwidth = []
    assgripidfreeair = []
    for i, rotmat in enumerate(objfag.freegriprotmats):
        assgrotmat = rotmat*objMat4
        robothand.setMat(assgrotmat)
        # detect the collisions when hand is open!
        robothand.setJawwidth(robothand.jawwidthopen)
        hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp)
        result0 = bulletworld.contactTest(hndbullnode)
        robothand.setJawwidth(objfag.freegripjawwidth[i])
        hndbullnode = cd.genCollisionMeshMultiNp(robothand.handnp)
        result1 = bulletworld.contactTest(hndbullnode)
        if (not result0.getNumContacts()) and (not result1.getNumContacts()):
            cct0 = objMat4.xformPoint(objfag.freegripcontacts[i][0])
            cct1 = objMat4.xformPoint(objfag.freegripcontacts[i][1])
            cctn0 = objMat4.xformPoint(objfag.freegripnormals[i][0])
            cctn1 = objMat4.xformPoint(objfag.freegripnormals[i][1])
            assgripcontacts.append([cct0, cct1])
            assgripnormals.append([cctn0, cctn1])
            assgriprotmat4s.append(assgrotmat)
            assgripjawwidth.append(objfag.freegripjawwidth[i])
            assgripidfreeair.append(objfag.freegripids[i])

    return [assgripcontacts, assgripnormals, assgriprotmat4s, assgripjawwidth, assgripidfreeair]
예제 #33
0
    def __init__(self):
        from panda3d.bullet import BulletWorld
        self._world = BulletWorld()
        self._world.set_gravity(0, 0, -9.807)

        self.tick_rate = None
        self.time = 0.0

        self._rigid_bodies = {}
예제 #34
0
    def __init__(self, objpath, gdb, handpkg, base):
        """
        initialization

        :param objpath: path of the object
        :param base: for the loadFreeAirGrip --> genHandPairs functions (for collision detection)

        author: weiwei
        date: 20161215, tsukuba
        """

        self.handpkg = handpkg
        self.handname = handpkg.getHandName()
        self.hand0 = handpkg.newHandNM(hndcolor=[1, 0, 0, .1])
        self.hand1 = handpkg.newHandNM(hndcolor=[0, 0, 1, .1])

        self.objtrimesh = trimesh.load_mesh(objpath)
        self.objnp = pg.packpandanp(self.objtrimesh.vertices,
                                    self.objtrimesh.face_normals,
                                    self.objtrimesh.faces)
        self.dbobjname = os.path.splitext(os.path.basename(objpath))[0]
        # mat4list is nested list, floatingposemat4 is list (the flat version of mat4lsit), they are essentially the same
        self.mat4list = []
        self.floatingposemat4 = []
        # gridsfloatingposemat4s is self.floatingposemat4 translated to different grids
        self.gridsfloatingposemat4s = []
        self.icos = None

        self.floatinggripids = []
        self.floatinggripmat4s = []
        self.floatinggripcontacts = []
        self.floatinggripnormals = []
        self.floatinggripjawwidth = []
        self.floatinggripidfreeair = []

        self.bulletworld = BulletWorld()
        self.handpairList = []

        self.gdb = gdb

        self.__loadFreeAirGrip(base)

        # for IK
        self.floatinggripikfeas_rgt = []
        self.floatinggripikfeas_handx_rgt = []
        self.floatinggripikfeas_lft = []
        self.floatinggripikfeas_handx_lft = []

        # for ik-feasible pairs
        self.floatinggrippairsids = []
        self.floatinggrippairshndmat4s = []
        self.floatinggrippairscontacts = []
        self.floatinggrippairsnormals = []
        self.floatinggrippairsjawwidths = []
        self.floatinggrippairsidfreeairs = []

        self.__genPandaRotmat4()
예제 #35
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), -1)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.bit(0))

    self.world.attachRigidBody(np.node())

    # Boxes
    self.boxes = [None,]*6

    for i in range(6):
      shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box-1'))
      np.node().setMass(1.0)
      np.node().addShape(shape)

      self.world.attachRigidBody(np.node())

      self.boxes[i] = np

      visualNP = loader.loadModel('models/box.egg')
      visualNP.reparentTo(np)

    self.boxes[0].setPos(-3, -3, 0)
    self.boxes[1].setPos( 0, -3, 0)
    self.boxes[2].setPos( 3, -3, 0)
    self.boxes[3].setPos(-3,  3, 0)
    self.boxes[4].setPos( 0,  3, 0)
    self.boxes[5].setPos( 3,  3, 0)

    self.boxes[0].setCollideMask(BitMask32.bit(1))
    self.boxes[1].setCollideMask(BitMask32.bit(2))
    self.boxes[2].setCollideMask(BitMask32.bit(3))
    self.boxes[3].setCollideMask(BitMask32.bit(1))
    self.boxes[4].setCollideMask(BitMask32.bit(2))
    self.boxes[5].setCollideMask(BitMask32.bit(3))

    self.boxNP = self.boxes[0]

    self.world.setGroupCollisionFlag(0, 1, True)
    self.world.setGroupCollisionFlag(0, 2, True)
    self.world.setGroupCollisionFlag(0, 3, True)

    self.world.setGroupCollisionFlag(1, 1, False)
    self.world.setGroupCollisionFlag(1, 2, True)
예제 #36
0
파일: world.py 프로젝트: jorjuato/pavara
 def __init__(self, camera, debug=False, audio3d=None, client=None, server=None):
     self.objects = {}
     self.incarnators = []
     self.collidables = set()
     self.updatables = set()
     self.updatables_to_add = set()
     self.garbage = set()
     self.render = NodePath('world')
     self.camera = camera
     self.audio3d = audio3d
     self.ambient = self._make_ambient()
     self.celestials = CompositeObject()
     self.sky = self.attach(Sky())
     # Set up the physics world. TODO: let maps set gravity.
     self.gravity = DEFAULT_GRAVITY
     self.physics = BulletWorld()
     self.physics.set_gravity(self.gravity)
     self.debug = debug
     self.client = client
     self.server = server
     if debug:
         debug_node = BulletDebugNode('Debug')
         debug_node.show_wireframe(True)
         debug_node.show_constraints(True)
         debug_node.show_bounding_boxes(False)
         debug_node.show_normals(False)
         np = self.render.attach_new_node(debug_node)
         np.show()
         self.physics.set_debug_node(debug_node)
  def setupPhysics(self, use_default_objs = True):

    # setting up physics world and parent node path 
    self.physics_world_ = BulletWorld()
    self.world_node_ = self.render.attachNewNode('world')
    self.cam.reparentTo(self.world_node_)
    self.cam.setPos(self.world_node_,0, -self.cam_zoom_*6, self.cam_step_*25)
    self.physics_world_.setGravity(Vec3(0, 0, -9.81))

    self.debug_node_ = self.world_node_.attachNewNode(BulletDebugNode('Debug'))
    self.debug_node_.show()
    self.debug_node_.node().showWireframe(True)
    self.debug_node_.node().showConstraints(True)
    self.debug_node_.node().showBoundingBoxes(False)
    self.debug_node_.node().showNormals(True)    
    self.physics_world_.setDebugNode(self.debug_node_.node())
    self.debug_node_.hide()
    self.object_nodes_ = []
    self.controlled_objects_ = []
    
    self.ground_ = None
    if use_default_objs:

      # setting up ground
      self.ground_ = self.world_node_.attachNewNode(BulletRigidBodyNode('Ground'))
      self.ground_.node().addShape(BulletPlaneShape(Vec3(0, 0, 1), 0))
      self.ground_.setPos(0,0,0)
      self.ground_.setCollideMask(BitMask32.allOn())
      self.physics_world_.attachRigidBody(self.ground_.node())
  
      self.setupLevel()
예제 #38
0
    def __init__(self):

        ## Setup a bullet world.

        # World Node (MAIN)
        self.worldNP = render.attachNewNode("World")

        # World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, worldGravity))
        PHYSICS["WORLD"] = self.world

        # Add the simulation method to the taskmgr
        taskMgr.add(self.update, "update bullet world")

        # Setup test World
        self.box = ""
        self.hinge = ""
        self.pickTest = False
        self.sensor = ""

        # test the class test
        self.test = MakeObject(self, "Box1", "b", 20.0)
        self.test.bodyNP.setPos(0, 1, 1)

        pos = 1

        # for x in range(5):
        # x = MakeObject(self, 'box', 'b', 5.0)
        # pos += 1
        # x.bodyNP.setPos(0, 0, pos)

        self.accept("e", self.playerPickup)
        self.accept("f1", self.showDebug)
        self.setup_world()
예제 #39
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    p0 = Point3(-20, -20, 0)
    p1 = Point3(-20, 20, 0)
    p2 = Point3(20, -20, 0)
    p3 = Point3(20, 20, 0)
    mesh = BulletTriangleMesh()
    mesh.addTriangle(p0, p1, p2)
    mesh.addTriangle(p1, p2, p3)
    shape = BulletTriangleMeshShape(mesh, dynamic=False)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh'))
    np.node().addShape(shape)
    np.setPos(0, 0, -2)
    np.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(np.node())

    # Soft body world information
    info = self.world.getWorldInfo()
    info.setAirDensity(1.2)
    info.setWaterDensity(0)
    info.setWaterOffset(0)
    info.setWaterNormal(Vec3(0, 0, 0))

    # Softbody
    for i in range(50):
      p00 = Point3(-2, -2, 0)
      p10 = Point3( 2, -2, 0)
      p01 = Point3(-2,  2, 0)
      p11 = Point3( 2,  2, 0)
      node = BulletSoftBodyNode.makePatch(info, p00, p10, p01, p11, 6, 6, 0, True)
      node.generateBendingConstraints(2)
      node.getCfg().setLiftCoefficient(0.004)
      node.getCfg().setDynamicFrictionCoefficient(0.0003)
      node.getCfg().setAeroModel(BulletSoftBodyConfig.AMVertexTwoSided)
      node.setTotalMass(0.1)
      node.addForce(Vec3(0, 2, 0), 0)

      np = self.worldNP.attachNewNode(node)
      np.setPos(self.Vec3Rand() * 10 + Vec3(0, 0, 20))
      np.setHpr(self.Vec3Rand() * 16)
      self.world.attachSoftBody(node)

      fmt = GeomVertexFormat.getV3n3t2()
      geom = BulletHelper.makeGeomFromFaces(node, fmt, True)
      node.linkGeom(geom)
      nodeV = GeomNode('')
      nodeV.addGeom(geom)
      npV = np.attachNewNode(nodeV)
예제 #40
0
    def __init__(self):
        self.register_signals()

        self.world = BulletWorld()
        self.world.setGravity((0, 0, -9.81))

        # # Seems that this does not function
        # on_contact_added = PythonCallbackObject(self._on_contact_added)
        # self.world.set_contact_added_callback(on_contact_added)

        # on_filter = PythonCallbackObject(self._filter_collision)
        # self.world.set_filter_callback(on_filter)

        self.listener = DirectObject()
        self.listener.accept('bullet-contact-added', self._on_contact_added)
        self.listener.accept('bullet-contact-destroyed', self._on_contact_removed)

        debug_node = BulletDebugNode('Debug')
        debug_node.showWireframe(True)
        debug_node.showConstraints(True)
        debug_node.showBoundingBoxes(False)
        debug_node.showNormals(False)

        self.debug_nodepath = render.attachNewNode(debug_node)
        self.world.set_debug_node(debug_node)

        self.debug_nodepath.show()
예제 #41
0
파일: world.py 프로젝트: airvoss/pavara
    def __init__(self, camera, debug=False, audio3d=None, client=None, server=None):
        self.objects = {}

        self.incarnators = []

        self.collidables = set()

        self.updatables = set()
        self.updatables_to_add = set()
        self.garbage = set()
        self.scene = NodePath('world')


        # Set up the physics world. TODO: let maps set gravity.
        self.gravity = DEFAULT_GRAVITY
        self.physics = BulletWorld()
        self.physics.set_gravity(self.gravity)

        self.debug = debug

        if debug:
            debug_node = BulletDebugNode('Debug')
            debug_node.show_wireframe(True)
            debug_node.show_constraints(True)
            debug_node.show_bounding_boxes(False)
            debug_node.show_normals(False)
            np = self.scene.attach_new_node(debug_node)
            np.show()
            self.physics.set_debug_node(debug_node)
예제 #42
0
파일: tdSim.py 프로젝트: ajaybha/OpenBiped
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()
    self.debugNP.node().showWireframe(True)
    self.debugNP.node().showConstraints(True)
    self.debugNP.node().showBoundingBoxes(False)
    self.debugNP.node().showNormals(True)

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())


    self.model = TinyDancer(self.world,self.worldNP)
    #floor
    shape = BulletBoxShape(Vec3(100, 100, 1))
    floor = BulletRigidBodyNode('Floor')
    bodyNP = self.worldNP.attachNewNode(floor)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(0, 0, -12)

    visNP = loader.loadModel('models/black.egg')
    visNP.setScale(Vec3(200, 200, 2))
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(floor)
예제 #43
0
  def setup(self):
    # World
    self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.hide()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Create starting platforms
    Platform(self.render, self.world, self.loader, 0, 1, 2, 0, 0, -3)
    Platform(self.render, self.world, self.loader, 0, 2, 2, 100, 100, -3)

    # Generate platforms
    PlatformFactory(self.render, self.world, self.loader)
    
    # Create player character
    self.player = Player(self.render, self.world, 0, 0, 0)
    
    # Music and sound
    self.level1Music = base.loader.loadSfx("sounds/level1.mp3")
    self.level1Music.setLoop()
    self.level1Music.setVolume(0.4)
    self.level1Music.play()
    self.level2Music = base.loader.loadSfx("sounds/level2.mp3")
    self.level2Music.setLoop()
    self.level2Music.setVolume(0.4)
    self.winMusic = base.loader.loadSfx("sounds/win.ogg")
    self.winMusic.setLoop()
    self.winMusic.setVolume(0.4)
    self.laughSound = base.loader.loadSfx("sounds/laugh.ogg")
    self.collectSound = base.loader.loadSfx("sounds/collect.mp3")
    
    self.createMainMenu()
예제 #44
0
    def setupWorld2(self):
        # create bullet world
        self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug'))
        #self.debugNP.show()

        self.world2 = BulletWorld()
        self.world2.setGravity(Vec3(0, 0, -9.81))
        self.world2.setDebugNode(self.debugNP.node())
예제 #45
0
    def create_physics(self):
        """Create the physical world, and start a task to simulate physics"""

        self.world = BulletWorld()
        self.world.set_gravity((0, 0, -9.81))

        self.physics_on = False
        self.taskMgr.add(self.step_physics, "physics")
예제 #46
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()
    self.debugNP.node().showWireframe(True)
    self.debugNP.node().showConstraints(True)
    self.debugNP.node().showBoundingBoxes(False)
    self.debugNP.node().showNormals(False)

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Box A
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyA = BulletRigidBodyNode('Box A')
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(-3, 0, 4)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyA)

    # Box B
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(0, 0, 0)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyB)

    # Slider
    frameA = TransformState.makePosHpr(Point3(2, 0, 0), Vec3(0, 0, 45))
    frameB = TransformState.makePosHpr(Point3(0, -3, 0), Vec3(0, 0, 0))

    slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
    slider.setDebugDrawSize(2.0)
    slider.setLowerLinearLimit(0)
    slider.setUpperLinearLimit(6)
    slider.setLowerAngularLimit(-60)
    slider.setUpperAngularLimit(60)
    self.world.attachConstraint(slider)
예제 #47
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, 0)
    np.setCollideMask(BitMask32(0x0f))

    self.world.attachRigidBody(np.node())

    # Box
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Box'))
    np.node().setMass(1.0)
    np.node().addShape(shape)
    np.setPos(0, 0, 4)
    np.setCollideMask(BitMask32(0x0f))

    self.world.attachRigidBody(np.node())

    self.boxNP = np
    visualNP = loader.loadModel('models/box.egg')
    visualNP.reparentTo(self.boxNP)

    # Sphere
    shape = BulletSphereShape(0.6)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Sphere'))
    np.node().setMass(1.0)
    np.node().addShape(shape)
    np.setPos(3, 0, 4)
    np.setCollideMask(BitMask32(0x0f))

    self.world.attachRigidBody(np.node())

    # Cone
    shape = BulletConeShape(0.6, 1.0)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone'))
    np.node().setMass(1.0)
    np.node().addShape(shape)
    np.setPos(6, 0, 4)
    np.setCollideMask(BitMask32(0x0f))

    self.world.attachRigidBody(np.node())
예제 #48
0
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()
    self.debugNP.node().showWireframe(True)
    self.debugNP.node().showConstraints(True)
    self.debugNP.node().showBoundingBoxes(False)
    self.debugNP.node().showNormals(False)

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Box A
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyA = BulletRigidBodyNode('Box A')
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(-2, 0, 1)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyA)

    # Box B
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(2, 0, 1)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyB)

    # Hinge
    pivotA = Point3(2, 0, 0)
    pivotB = Point3(-4, 0, 0)
    axisA = Vec3(0, 0, 1)
    axisB = Vec3(0, 0, 1)

    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(-90, 120, softness=0.9, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
예제 #49
0
 def initBullet(self):
     self.world = BulletWorld()
     #self.world.setGravity(Vec3(0, 0, -9.81))
     self.world.setGravity(Vec3(0, 0, -1.62))
     
     groundShape = BulletPlaneShape(Vec3(0, 0, 1), 0)
     groundNode = BulletRigidBodyNode('Ground')
     groundNode.addShape(groundShape)
     self.world.attachRigidBody(groundNode)
예제 #50
0
class World:
    def __init__(self):
        self.init_bullet()
        self.init_skybox()

    def init_bullet(self):
        self.bullet_world = BulletWorld()

    def update_bullet(self, task):
        dt = ClockObject.getGlobalClock().getDt()
        self.bullet_world.doPhysics(dt)
        return task.cont

    def init_skybox(self):
        # This should probably have its own class..
        self.sky_material = Material()
        self.sky_material.clearAmbient()
        self.sky_material.clearEmission()
        self.sky_material.setAmbient(VBase4(1, 1, 1, 1))

        # This loads "basic_skybox_#" # being 0-6
        # If the skybox was made in spacescape the files must be renamed to
        # work properly, and the 2 and 3 files should be switched.
        self.skybox_texture = loader.loadCubeMap("images/skybox/red_nebula_purple_flares/Red_nebula_#.png")

        # TODO: Figure out a way (if possible) to allow 3d objects to be seen
        # through the skysphere, It already kinda does this, but its weird.

        self.skybox = NodePath(loader.loadModel("models/skybox.x"))
        self.skybox.setLightOff()
        self.skybox.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # self.skybox.setTwoSided(True) BETTER ^
        self.skybox.setScale(5000)
        self.skybox.clearDepthWrite
        self.skybox.setDepthWrite(False)
        self.skybox.setMaterial(self.sky_material, 1)
        self.skybox.setTexture(self.skybox_texture)
        self.skybox.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
        # This makes it so objects behind the skybox are rendered
        self.skybox.setBin("back_to_front", 40)
        # projects the texture as it looks from render
        self.skybox.setTexProjector(TextureStage.getDefault(), render, self.skybox)
        self.skybox.setCompass()
        self.skybox.reparentTo(base.camera)
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()
    self.debugNP.node().showWireframe(True)
    self.debugNP.node().showConstraints(True)
    self.debugNP.node().showBoundingBoxes(False)
    self.debugNP.node().showNormals(False)

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Box A
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyA = BulletRigidBodyNode('Box A')
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(-1, 0, 4)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyA)

    # Box B
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.node().setLinearDamping(0.6)
    bodyNP.node().setAngularDamping(0.6)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(2, 0, 0)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyB)

    # Spherical Constraint
    pivotA = Point3(2, 0, 0)
    pivotB = Point3(0, 0, 4)

    joint = BulletSphericalConstraint(bodyA, bodyB, pivotA, pivotB)
    joint.setDebugDrawSize(2.0)
    self.world.attachConstraint(joint)
예제 #52
0
	def setupWorld(self):
		self.worldBullet = BulletWorld()
		self.worldBullet.setGravity(Vec3(0, 0, -GRAVITY))
		self.terrSteepness = -1
		wNP = render.attachNewNode('WorldNode')
		
		self.audioMgr.loadSFX("snowCrunch01")
		self.audioMgr.loadBGM("snowmanWind")
		
		return wNP
  def setup(self):
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()
    self.debugNP.node().showWireframe(True)
    self.debugNP.node().showConstraints(True)
    self.debugNP.node().showBoundingBoxes(False)
    self.debugNP.node().showNormals(False)

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())

    # Box A
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyA = BulletRigidBodyNode('Box A')
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(-2, 0, 4)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyA)

    # Box B
    shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(0, 0, 0)

    visNP = loader.loadModel('models/box.egg')
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyB)

    # Cone
    frameA = TransformState.makePosHpr(Point3(0, 0, -2), Vec3(0, 0, 90))
    frameB = TransformState.makePosHpr(Point3(-5, 0, 0), Vec3(0, 0, 0))

    cone = BulletConeTwistConstraint(bodyA, bodyB, frameA, frameB)
    cone.setDebugDrawSize(2.0)
    cone.setLimit(30, 45, 170, softness=1.0, bias=0.3, relaxation=8.0)
    self.world.attachConstraint(cone)
예제 #54
0
    def __init__(self, objpath, gdb, handpkg, base):
        """
        initialization

        :param objpath: path of the object
        :param base: for the loadFreeAirGrip --> genHandPairs functions (for collision detection)

        author: weiwei
        date: 20161215, tsukuba
        """

        self.handpkg = handpkg
        self.handname = handpkg.getHandName()
        self.hand0 = handpkg.newHandNM(hndcolor=[1,0,0,.1])
        self.hand1 = handpkg.newHandNM(hndcolor=[0,0,1,.1])

        self.objtrimesh = trimesh.load_mesh(objpath)
        self.objnp = pg.packpandanp(self.objtrimesh.vertices, self.objtrimesh.face_normals, self.objtrimesh.faces)
        self.dbobjname = os.path.splitext(os.path.basename(objpath))[0]
        # mat4list is nested list, floatingposemat4 is list (the flat version of mat4lsit), they are essentially the same
        self.mat4list = []
        self.floatingposemat4 = []
        # gridsfloatingposemat4s is self.floatingposemat4 translated to different grids
        self.gridsfloatingposemat4s = []
        self.icos = None

        self.floatinggripids = []
        self.floatinggripmat4s = []
        self.floatinggripcontacts = []
        self.floatinggripnormals = []
        self.floatinggripjawwidth = []
        self.floatinggripidfreeair = []

        self.bulletworld = BulletWorld()
        self.handpairList = []

        self.gdb = gdb

        self.__loadFreeAirGrip(base)

        # for IK
        self.floatinggripikfeas_rgt = []
        self.floatinggripikfeas_handx_rgt = []
        self.floatinggripikfeas_lft = []
        self.floatinggripikfeas_handx_lft = []

        # for ik-feasible pairs
        self.floatinggrippairsids = []
        self.floatinggrippairshndmat4s = []
        self.floatinggrippairscontacts = []
        self.floatinggrippairsnormals = []
        self.floatinggrippairsjawwidths = []
        self.floatinggrippairsidfreeairs = []

        self.__genPandaRotmat4()
예제 #55
0
    def __init__(self, player_tag):
        ShowBase.__init__(self)
        self.__player_tag = player_tag
        self.__rotations = {}

        # Panda pollutes the global namespace.  Some of the extra globals can be referred to in nicer ways
        # (for example self.render instead of render).  The globalClock object, though, is only a global!  We
        # create a reference to it here, in a way that won't upset PyFlakes.
        self.globalClock = __builtins__["globalClock"]

        # Turn off the debugging system which allows the camera to be adjusted directly by the mouse.
        self.disableMouse()

        # Set up physics: the ground plane and the capsule which represents the player.
        self.world = BulletWorld()

        # The ground first:
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        node = BulletRigidBodyNode('Ground')
        node.addShape(shape)
        np = self.render.attachNewNode(node)
        np.setPos(0, 0, 0)
        self.world.attachRigidBody(node)

        # Load the 3dWarehouse model.
        cathedral = self.loader.loadModel("3dWarehouse_Reykjavik_Cathedral.egg")
        cathedral.reparentTo(self.render)
        cathedral.setScale(0.5)

        # Load the Blender model.
        self.humanoid = Actor("player.egg")
        self.humanoid.setScale(0.5)
        self.humanoid.reparentTo(self.render)
        self.humanoid.loop("Walk")

        humanoidPosInterval1 = self.humanoid.posInterval(58, Point3(13, -10, 0), startPos=Point3(13, 10, 0))
        humanoidPosInterval2 = self.humanoid.posInterval(58, Point3(13, 10, 0), startPos=Point3(13, -10, 0))
        humanoidHprInterval1 = self.humanoid.hprInterval(3, Point3(180, 0, 0), startHpr=Point3(0, 0, 0))
        humanoidHprInterval2 = self.humanoid.hprInterval(3, Point3(0, 0, 0), startHpr=Point3(180, 0, 0))

        # Make the Blender model walk up and down.
        self.humanoidPace = Sequence(humanoidPosInterval1, humanoidHprInterval1, humanoidPosInterval2,
                                     humanoidHprInterval2, name="humanoidPace")

        self.humanoidPace.loop()

        # Create a light so we can see the scene.
        dlight = DirectionalLight('dlight')
        dlight.setColor(VBase4(2, 2, 2, 0))
        dlnp = self.render.attachNewNode(dlight)
        dlnp.setHpr(0, -60, 0)
        self.render.setLight(dlnp)

        # Create a task to update the scene regularly.
        self.taskMgr.add(self.update, "UpdateTask")
예제 #56
0
class GameState(ShowBase):
    def __init__(self):
        loadPrcFile("server-config.prc")
        ShowBase.__init__(self)
        self.__rotations = {}

        # Panda pollutes the global namespace.  Some of the extra globals can be referred to in nicer ways
        # (for example self.render instead of render).  The globalClock object, though, is only a global!  We
        # create a reference to it here, in a way that won't upset PyFlakes.
        self.globalClock = __builtins__["globalClock"]

        # Set up physics: the ground plane and the capsule which represents the player.
        self.world = BulletWorld()

        # The ground first:
        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        node = BulletRigidBodyNode("Ground")
        node.addShape(shape)
        np = self.render.attachNewNode(node)
        np.setPos(0, 0, 0)
        self.world.attachRigidBody(node)

        # Create a task to update the scene regularly.
        self.taskMgr.add(self.update, "UpdateTask")

    # Update the scene by turning objects if necessary, and processing physics.
    def update(self, task):
        asyncore.loop(timeout=0.1, use_poll=True, count=1)
        Player.update_all()

        for node, angular_velocity in self.__rotations.iteritems():
            node.setAngularMovement(angular_velocity)

        dt = self.globalClock.getDt()
        self.world.doPhysics(dt)
        return task.cont

    def set_angular_velocity(self, node, angular_velocity):
        if angular_velocity != 0:
            self.__rotations[node] = angular_velocity
        elif node in self.__rotations:
            del self.__rotations[node]
예제 #57
0
    def __init__(self):

        #self.gui = loadGui()
        #init_pause_state(self.menu)
        init_pause_state()
        test = World()

        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9))

        self.world.setDebugNode(debugNP.node())

        #Add a gravity region
        self.add_gravity_region(
                (100, 100, 100),
                (100, -400, 0),
                (0, 0, 1000))

        taskMgr.add(self.update_bullet, 'update_bullet')

        self.bulletList = self.loadBulletList()

        base.disableMouse()

        self.loadLevel()
        self.initClasses()
        self.setCamera()
        self.addWinProps()

        #TODO: Fix the healthbars
        #self.gui.healthBar("Player1")
        #self.gui.healthBar("AI1")
        #self.gui.healthBar("AI2")
        #self.gui.healthBar("AI3")

        self.loadStation()

        self.addlight()

        self.createControls()

        taskMgr.add(self.updateMenus, 'MenuUpdater')
        print("Instance of game class running.")

        self.simmpoleXP()
        self.flipsXP()
    def __init__(self,gravity=(0,0,-9.81)):
        self.world = BulletWorld()
        self.world.setGravity(Vec3(gravity))

        self.addShape = {}
        self.addShape['sphere']   = self.__addSphere  
        self.addShape['box']      = self.__addBox
        self.addShape['cylinder'] = self.__addCylinder
        self.addShape['capsule']  = self.__addCapsule
        self.addShape['cone']     = self.__addCone
        self.addShape['hull']     = self.__addConvexHull
        self.addShape['trimesh']  = self.__addTriangleMesh