コード例 #1
0
ファイル: dropblt.py プロジェクト: xwavex/pyhiro
    def __init__(self, base, objpath, bdebug=False):
        self.base = base

        self.smiley = loader.loadModel(objpath)
        self.smileyCount = 0

        self.setupBullet()
        self.addGround()
        # self.addWalls()

        self.partlist = []

        taskMgr.doMethodLater(.1, self.addSmiley, "AddSmiley")
        taskMgr.add(self.updateBlt, "UpdateBlt")

        if bdebug:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            bullcldrnp = self.base.render.attachNewNode("bulletcollider")
            debugNP = bullcldrnp.attachNewNode(debugNode)
            debugNP.show()
            self.bltWorld.setDebugNode(debugNP.node())
コード例 #2
0
ファイル: dropblt.py プロジェクト: wanweiwei07/pyhiro
    def __init__(self, base, objpath, bdebug = False):
        self.base = base

        self.smiley = loader.loadModel(objpath)
        self.smileyCount = 0

        self.setupBullet()
        self.addGround()
        # self.addWalls()

        self.partlist = []

        taskMgr.doMethodLater(.1, self.addSmiley, "AddSmiley")
        taskMgr.add(self.updateBlt, "UpdateBlt")

        if bdebug:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            bullcldrnp = self.base.render.attachNewNode("bulletcollider")
            debugNP = bullcldrnp.attachNewNode(debugNode)
            debugNP.show()
            self.bltWorld.setDebugNode(debugNP.node())
コード例 #3
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()
コード例 #4
0
ファイル: physics.py プロジェクト: TurBoss/PyAuthServer
    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()
コード例 #5
0
 def __init__(self):
     debugNode = BulletDebugNode('DebugNode')
     debugNode.showWireframe(True)
     debugNode.showConstraints(True)
     debugNode.showBoundingBoxes(True)
     debugNode.showNormals(True)
     self.debugNP = render.attachNewNode(debugNode)
コード例 #6
0
	def __init__(self):
		debugNode = BulletDebugNode('DebugNode')
		debugNode.showWireframe(True)
		debugNode.showConstraints(True)
		debugNode.showBoundingBoxes(True)
		debugNode.showNormals(True)
		self.debugNP = render.attachNewNode(debugNode)
コード例 #7
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
コード例 #8
0
 def setup_debug(self):
     debug_node = BulletDebugNode('Debug')
     debug_node.showWireframe(True)
     debug_node.showConstraints(True)
     debug_node.showBoundingBoxes(True)
     debug_node.showNormals(True)
     self.world.setDebugNode(debug_node)
     return debug_node
コード例 #9
0
    def enablePhysicsDebug(self):
        debugnode = BulletDebugNode('Physics-Debug')
        debugnode.showWireframe(True)
        debugnode.showConstraints(True)

        debugNP = render.attachNewNode(debugnode)
        if self.physics_world != None:
            self.physics_world.setDebugNode(debugNP.node())
            debugNP.show()
コード例 #10
0
 def _debug_mode(self):
     debugNode = BulletDebugNode('Debug')
     debugNode.showWireframe(True)
     debugNode.showConstraints(True)
     debugNode.showBoundingBoxes(False)
     debugNode.showNormals(True)
     debugNP = self.render.attachNewNode(debugNode)
     self.physics_world.dynamic_world.setDebugNode(debugNP.node())
     self.debug_node = debugNP
コード例 #11
0
	def setupDebug(self):
		debug = BulletDebugNode()
		debug.showWireframe(False) # Yeah, don't set this to true unless you want to emulate an 80's computer running Crysis on Ultra settings.
		debug.showConstraints(True)
		debug.showBoundingBoxes(True) # This is the main use I have for it.
		debug.showNormals(True)
		debugNP = render.attachNewNode(debug)
		self.worldBullet.setDebugNode(debugNP.node())
		debugNP.hide()
		return debugNP
コード例 #12
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()
コード例 #13
0
ファイル: engine.py プロジェクト: PlumpMath/meo_tech
    def showBulletDebug(self):
        """Show bullet Debug"""
        # Bullet DEBUG
        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()

        self.bulletWorld.setDebugNode(debugNP.node())
コード例 #14
0
 def setupDebug(self):
     debug = BulletDebugNode()
     debug.showWireframe(
         False
     )  # Yeah, don't set this to true unless you want to emulate an 80's computer running Crysis on Ultra settings.
     debug.showConstraints(True)
     debug.showBoundingBoxes(True)  # This is the main use I have for it.
     debug.showNormals(True)
     debugNP = render.attachNewNode(debug)
     self.worldBullet.setDebugNode(debugNP.node())
     debugNP.hide()
     return debugNP
コード例 #15
0
ファイル: engine.py プロジェクト: grimfang/quickShadows
    def showBulletDebug(self):
        """Show bullet Debug"""
        # Bullet DEBUG
        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()

        self.bulletWorld.setDebugNode(debugNP.node())
コード例 #16
0
ファイル: TankWorld.py プロジェクト: ursulawolz/tanCS
	def drawDebugNode(self):
		debugNode = BulletDebugNode('Debug')
		debugNode.showWireframe(True)
		debugNode.showConstraints(True)
		debugNode.showBoundingBoxes(False)
		debugNode.showNormals(False)
		self.debugNP = render.attachNewNode(debugNode)

		#print "TankWorld.drawDebugNode: debug node activated" 
		self.accept('9', self.debugNP.show)
		self.accept('8', self.debugNP.hide)

		self.__bulletWorld.setDebugNode(debugNode)
コード例 #17
0
    def setupBulletPhysics(self):
        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        self.debugNP = render.attachNewNode(debugNode)

        self.mondePhysique = BulletWorld()
        self.mondePhysique.setGravity(Vec3(0, 0, -9.81))
        self.mondePhysique.setDebugNode(self.debugNP.node())
        taskMgr.add(self.updatePhysics, "updatePhysics")

        taskMgr.add(self.updateCarte, "updateCarte")
コード例 #18
0
    def __init__(self, base):
        self.__base = base
        self.__base.world = BulletWorld()
        bulletcolliderrender = self.__base.render.attachNewNode("bulletcollider")

        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        self.__debugNP = bulletcolliderrender.attachNewNode(debugNode)
        self.__base.world.setDebugNode(self.__debugNP.node())

        self.worldrigidbodylist = []
コード例 #19
0
ファイル: mc.py プロジェクト: fcostin/gravbot
    def __init__(self):
        ShowBase.__init__(self)
        utilities.setApp(self)

        loadPrcFileData('', 'bullet-enable-contact-events true')

        self.world = World(10)

        self.taskMgr.add(self.update, "update")

        self.accept("a", self.world.player.moveLeft, [True])
        self.accept("a-up", self.world.player.moveLeft, [False])

        self.accept("d", self.world.player.moveRight, [True])
        self.accept("d-up", self.world.player.moveRight, [False])

        self.accept("space", self.world.player.jump, [True])
        self.accept("space-up", self.world.player.jump, [False])

        self.accept("c", self.world.player.crouch, [True])
        self.accept("c-up", self.world.player.crouch, [False])

        self.accept("mouse1", self.world.player.activate, [])

        self.accept("escape", sys.exit, [])

        self.accept('bullet-contact-added', self.onContactAdded) 
        self.accept('bullet-contact-destroyed', self.onContactDestroyed) 

        self.accept("h", self.showDBG, [True])
        self.accept("h-up", self.showDBG, [False])

        self.prevTime = 0

        self.mousePos = Point2()
        base.disableMouse()

        self.rl = base.camLens.makeCopy()

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

        self.world.bw.setDebugNode(self.debugNP.node())
コード例 #20
0
ファイル: physicsManager.py プロジェクト: PlumpMath/lext
    def setPhysicsDebug(self, _bool=False):
        debugNode = BulletDebugNode('Debug')
        self.debugNP = render.attachNewNode(debugNode)

        if _bool:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            self.debugNP = render.attachNewNode(debugNode)
            self.physicsWorld.setDebugNode(self.debugNP.node())
            self.debugNP.show()
        else:
            self.debugNP.hide()
コード例 #21
0
ファイル: physicsManager.py プロジェクト: grimfang/lext
    def setPhysicsDebug(self, _bool=False):
        debugNode = BulletDebugNode('Debug')
        self.debugNP = render.attachNewNode(debugNode)

        if _bool:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            self.debugNP = render.attachNewNode(debugNode)
            self.physicsWorld.setDebugNode(self.debugNP.node())
            self.debugNP.show()
        else:
            self.debugNP.hide()
コード例 #22
0
    def __init__(self, toggledebug=False):
        self.world = BulletWorld()
        self._toggledebug = toggledebug
        if self._toggledebug:
            bulletcolliderrender = base.render.attachNewNode(
                "bulletboxcollider")
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            self._debugNP = bulletcolliderrender.attachNewNode(debugNode)
            self.world.setDebugNode(self._debugNP.node())

        self.worldrigidbodylist = []
        self._isupdateworldadded = False
コード例 #23
0
    def __init__(self, app):
        self.app = app

        utilities.setApp(self.app)

        self.world = World(10)

        self.app.taskMgr.add(self.update, "update")

        self.app.accept("a", self.world.player.moveLeft, [True])
        self.app.accept("a-up", self.world.player.moveLeft, [False])

        self.app.accept("d", self.world.player.moveRight, [True])
        self.app.accept("d-up", self.world.player.moveRight, [False])

        self.app.accept("w", self.world.player.jump, [True])
        self.app.accept("w-up", self.world.player.jump, [False])

        self.app.accept("s", self.world.player.crouch, [True])
        self.app.accept("s-up", self.world.player.crouch, [False])

        self.app.accept("mouse1", self.world.player.activate, [])

        self.app.accept("q", self.world.player.scrollItem, [1])
        self.app.accept("1", self.world.player.selectItem, [1])
        self.app.accept("2", self.world.player.selectItem, [2])

        self.app.accept("escape", sys.exit, [])

        self.app.mousePos = Point2()
        self.app.disableMouse()

        self.app.rl = base.camLens.makeCopy()

        if utilities.debug:
          self.app.accept("h", self.showDBG, [True])
          self.app.accept("h-up", self.showDBG, [False])

          #bullet debug rendering 
          debugNode = BulletDebugNode('Debug')
          debugNode.showWireframe(True)
          debugNode.showConstraints(True)
          debugNode.showBoundingBoxes(False)
          debugNode.showNormals(False)
          self.debugNP = render.attachNewNode(debugNode)
          self.debugNP.show()
          self.world.bw.setDebugNode(self.debugNP.node())
コード例 #24
0
ファイル: physics.py プロジェクト: gamingrobot/second-sunrise
    def __init__(self, xml):
        globalClock.setMaxDt(0.1)
        #init pre and post callbacks
        self.prePhysics = {}
        self.postPhysics = {}

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

        #create bullet world
        self.bulletworld = BulletWorld()
        self.bulletworld.setDebugNode(debugNP.node())
        self.bulletworld.setGravity(Vec3(0, 0, 0))

        #start doing physics
        self.physicsTask = taskMgr.add(self.simulationTask, 'Physics Loop', sort=100)
コード例 #25
0
def invoke(scene, data, action):
    if action == 'LOAD':
        scene.phys_world = BulletWorld()
        scene.phys_world.setGravity(Vec3(0, 0, -data['phys_gravity']))

        if 'bullet_debug' in scene.flags and scene.flags['bullet_debug']:
            # --- debug ---
            debugNode = BulletDebugNode('PhysDebug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            debugNP = render.attachNewNode(debugNode)
            debugNP.show()
            scene.phys_world.setDebugNode(debugNode)
            # --- debug end ---

        #taskMgr.add(update, 'physics-update', extraArgs=[scene, data['phys_step_sub'], 1.0/data['phys_fps']])
        taskMgr.doMethodLater(
            2,
            update,
            'physics-update',
            extraArgs=[scene, data['phys_step_sub'], 1.0 / data['phys_fps']])
コード例 #26
0
    def initBullet(self):
        """Initializes the Bullet physics engine, also adds the updatePhysicsTask to the task manager."""
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, 0))

        # add ground
        node = BulletRigidBodyNode("Ground")  # derived from PandaNode
        node.addShape(BulletPlaneShape(Vec3(0, 0, 1), 0))
        np = self.render.attachNewNode(node)
        np.setPos(0, 0, 0)
        self.world.attachRigidBody(node)

        # add debug node
        debugNode = BulletDebugNode("Debug")
        debugNode.showWireframe(False)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(True)
        debugNP = self.render.attachNewNode(debugNode)
        debugNP.show()
        self.world.setDebugNode(debugNP.node())

        self.taskMgr.add(self.updatePhysicsTask, "UpdatePhysics")
コード例 #27
0
    def __init__(self, xml):
        globalClock.setMaxDt(0.1)
        #init pre and post callbacks
        self.prePhysics = {}
        self.postPhysics = {}

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

        #create bullet world
        self.bulletworld = BulletWorld()
        self.bulletworld.setDebugNode(debugNP.node())
        self.bulletworld.setGravity(Vec3(0, 0, 0))

        #start doing physics
        self.physicsTask = taskMgr.add(self.simulationTask,
                                       'Physics Loop',
                                       sort=100)
コード例 #28
0
    def __init__(self):
        ShowBase.__init__(self)

        # Load the environment model.
        self.scene = self.loader.loadModel("input.obj")
        self.setBackgroundColor(0.0, 0.0, 0.0)

        plight = PointLight('plight')
        plight.setColor(VBase4(0.7, 0.7, 0.7, 1))
        plnp = self.render.attachNewNode(plight)
        plnp.setPos(0, 20, 0)
        self.render.setLight(plnp)

        ambientLight = AmbientLight('ambientLight')
        ambientLight.setColor((0.1, 0.1, 0.1, 1))
        ambientLightNP = render.attachNewNode(ambientLight)
        self.render.setLight(ambientLightNP)

        dlight = DirectionalLight('dlight')
        dlight.setColor(VBase4(0.8, 0.8, 0.8, 1))
        dlnp = render.attachNewNode(dlight)
        dlnp.setHpr(0, 10, 0)
        self.render.setLight(dlnp)

        # Reparent the model to render.
        shape = BulletBoxShape(Vec3(0.06, 0.12, 0.04))
        node = BulletRigidBodyNode('Box')
        node.setMass(0.6)
        node.addShape(shape)
        boxnode = self.render.attachNewNode(node)
        #boxnode.setHpr(90,90,90)   #or whatever you want to rotate to
        #model = self.loader.loadModel('models/box.egg')
        customBox = BoxMaker(0.06, 0.12, 0.04).generate()
        customBox.setColor(0.97, 0.99, 0.75)
        #customBox.flattenLight()
        customBox.reparentTo(boxnode)

        #model.reparentTo(boxnode)
        boxnode.setPos(-0.1, 1.5, 0.65)
        boxnode.setHpr(90, 90, 90)
        #model.reparentTo(self.scene)
        #model.setPos(0, 0.0, 0.0)
        #boxnode.reparentTo(self.render)

        bin_node = build_bullet_from_model(self.scene)
        bin_shape_node = self.render.attachNewNode(bin_node)
        self.scene.reparentTo(bin_shape_node)
        bin_shape_node.setPos(0, 2.4, 0.2)
        bin_shape_node.setHpr(90, 90, 90)  #or whatever you want to rotate to

        #self.scene.setPos(0, 5.5, 0.2)
        #bin_node.setHpr(90,90,90)   #or whatever you want to rotate to
        world.attachRigidBody(bin_node)
        world.attachRigidBody(node)

        #shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        #node = BulletRigidBodyNode('Ground')
        #node.addShape(shape)
        #np = self.render.attachNewNode(node)
        #np.setPos(0, 7.0, 0.0)
        #np.setHpr(90,90,90)
        #world.attachRigidBody(node)

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

        #self.scene.reparentTo(self.render)
        self.taskMgr.add(update, 'update')
コード例 #29
0
ファイル: gameBase.py プロジェクト: monicagraciela/PPARPG
class GameBase(ShowBase):
    def __init__(self, KEY_LIST):
        ShowBase.__init__(self)

        #---------------------------------------------------------------
        # clock
        self.globalClock = ClockObject()

        #---------------------------------------------------------------
        # KeyHandler
        self.kh = KeyHandler(KEY_LIST)

        #---------------------------------------------------------------
        # Bullet
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -12.81))
        self.gravityUp = False

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

        #---------------------------------------------------------------
        # Player
        #---------------------------------------------------------------
        # CharacterController
        self.player = CharacterController(self)
        self.player.setActor('models/characters/female',
                             {'walk': 'models/characters/female-walk.egg'},
                             flip=True,
                             pos=(0, 0, -1),
                             scale=1.0)
        self.player.setPos(0, -5, 3)
        self.player.playerModel.loop("walk")
        self.playerNp = self.player.np

        #---------------------------------------------------------------
        # Camera
        self.camHandler = CamHandler(self)

        #---------------------------------------------------------------
        # task
        #self.taskMgr.add(self.update, "update")

    #---------------------------------------------------------------
    # FPS
    def toggleFPS(self):
        if self.frameRateMeter:
            self.setFrameRateMeter(False)
        else:
            self.setFrameRateMeter(True)

    #---------------------------------------------------------------
    # Mouse cursor
    def hideCursor(self):
        props = WindowProperties()
        props.setCursorHidden(True)
        self.win.requestProperties(props)

    def showCursor(self):
        props = WindowProperties()
        props.setCursorHidden(False)
        self.win.requestProperties(props)

    def getObjectHoverName(self):
        if not self.mouseWatcherNode.hasMouse():
            return None
        pMouse = self.mouseWatcherNode.getMouse()
        pFrom = Point3()
        pTo = Point3()
        self.camLens.extrude(pMouse, pFrom, pTo)
        # Transform to global coordinates
        pFrom = self.render.getRelativePoint(self.cam, pFrom)
        pTo = self.render.getRelativePoint(self.cam, pTo)
        result = self.world.rayTestClosest(pFrom, pTo)
        if result.hasHit():
            pos = result.getHitPos()
            name = result.getNode().getName()
            return name
        else:
            return None

    def getObjectCenterScreen(self):
        pFrom = Point3()
        pTo = Point3()
        self.camLens.extrude((0, 0), pFrom, pTo)
        # Transform to global coordinates
        pFrom = self.render.getRelativePoint(self.cam, pFrom)
        pTo = self.render.getRelativePoint(self.cam, pTo)
        result = self.world.rayTestClosest(pFrom, pTo)
        if result.hasHit():
            pos = result.getHitPos()
            name = result.getNode().getName()
            return name
        else:
            return None

    #---------------------------------------------------------------
    # Fog
    def setFog(self):
        myFog = Fog("Fog")
        myFog.setColor((0, 0, 0, 1))
        myFog.setExpDensity(0.025)
        self.render.setFog(myFog)
        self.fog = True

    def clearFog(self):
        self.render.clearFog()
        self.fog = False

    def toggleFog(self):
        if self.fog:
            self.clearFog()
        else:
            self.setFog()

    #---------------------------------------------------------------
    # Camera
    def setFov(self, x):
        self.camLens.setFov(x)

    def getFov(self):
        return self.camLens.getFov()[0]

    def setNear(self, n):
        self.camLens.setNear(n)

    def setFar(self, n):
        self.camLens.setFar(n)

    #---------------------------------------------------------------
    # Physics

    def toggleGravity(self):
        if self.gravityUp:
            self.gravityUp = False
            self.world.setGravity(Vec3(0, 0, -9.8))
        else:
            self.gravityUp = True
            self.world.setGravity(Vec3(0, 0, 9.8))

    def toggleDebug(self):
        #print "Toggle debug, extraArgs = %s" % (extraArgs)
        if self._debug:
            self._debug = False
            self.debugNP.hide()
        else:
            self._debug = True
            self.debugNP.show()

    def updatePhysics(self, dt):
        #self.world.doPhysics(dt, 20, 1.0/180)
        self.world.doPhysics(dt)
        #cnt = self.world.contactTest(self.ground.node)
        #for boxName in self.objects:
        #	self.objects[boxName].update(dt)
        '''
			cntTest = self.world.contactTest(self.objects[boxName].node)
			cnt = cntTest.getContacts()
			for c in cnt:
				node0 = c.getNode0().getName()
				node1 = c.getNode1().getName()
				#print node0, " in contact with ", node1
		'''

    def update(self, task):
        self.globalClock.tick()
        t = self.globalClock.getFrameTime()
        dt = self.globalClock.getDt()
        self.updatePhysics(dt)
        self.player.update(dt)
        return task.cont

    def quit(self):
        self.taskMgr.stop()

    def stop(self):
        self.taskMgr.stop()

    def start(self):
        self.taskMgr.run()
コード例 #30
0
ファイル: game.py プロジェクト: pradishb/Battlegrounds
class GameEngine:
    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()

    def initCam(self):
        base.cam.setHpr(0, -90, 0)
        base.cam.setPos(0, 0, 170)

    def deathCamTask(self, task):
        angleDegrees = task.time * 20.0
        angleRadians = angleDegrees * (math.pi / 180.0)
        player = self.players[self.myId].playerNP
        base.cam.setPos(player.getX() + 10 * math.sin(angleRadians),
                        player.getY() - 10.0 * math.cos(angleRadians),
                        player.getZ() + 5)
        base.cam.lookAt(player.getPos())
        return task.cont

    # Debug
    def toggleDebug(self):
        if self.debugNP.isHidden():
            self.debugNP.show()
        else:
            self.debugNP.hide()
コード例 #31
0
ファイル: main.py プロジェクト: thetestgame/wecs
def main():
    ECSShowBase()
    base.disable_mouse()
    base.accept('escape', sys.exit)
    base.cam.set_pos(4, -5, 2)
    base.cam.look_at(0, 0, 0)

    system_types = [
        prototype.ManageModels,
        clock.DetermineTimestep,
        prototype.DeterminePhysicsTimestep,
        prototype.DoPhysics,
    ]
    for sort, system_type in enumerate(system_types):
        base.add_system(system_type(), sort)

    # Bullet world
    bullet_world = BulletWorld()
    bullet_world.set_gravity(Vec3(0, 0, -9.81))

    if debug:
        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()
        bullet_world.setDebugNode(debugNP.node())

    world = base.ecs_world.create_entity(
        clock.Clock(clock=clock.panda3d_clock),
        prototype.PhysicsWorld(world=bullet_world, timestep=1 / 30),
    )
    base.ecs_world._flush_component_updates()

    # Something for the models to fall on
    bullet_body = BulletRigidBodyNode()
    bullet_body.set_mass(0.0)
    bullet_body.add_shape(
        BulletBoxShape(Vec3(base_size, base_size, 0.1)),
        TransformState.makePos(Point3(0, 0, 0)),
    )
    bullet_body.add_shape(
        BulletBoxShape(Vec3(base_size, 0.1, wall_height)),
        TransformState.makePos(Point3(0, -base_size, wall_height)),
    )
    bullet_body.add_shape(
        BulletBoxShape(Vec3(base_size, 0.1, wall_height)),
        TransformState.makePos(Point3(0, base_size, wall_height)),
    )
    bullet_body.add_shape(
        BulletBoxShape(Vec3(0.1, base_size, wall_height)),
        TransformState.makePos(Point3(-base_size, 0, wall_height)),
    )
    bullet_body.add_shape(
        BulletBoxShape(Vec3(0.1, base_size, wall_height)),
        TransformState.makePos(Point3(base_size, 0, wall_height)),
    )

    base.ecs_world.create_entity(
        prototype.Model(post_attach=prototype.transform(pos=Vec3(0, 0, -1)), ),
        prototype.PhysicsBody(
            body=bullet_body,
            world=world._uid,
        ),
    )

    # Regularly add a ball

    def add_ball(task):
        bullet_body = BulletRigidBodyNode()
        bullet_body.set_linear_sleep_threshold(0)
        bullet_body.set_angular_sleep_threshold(0)
        bullet_body.set_mass(1.0)

        bullet_body.add_shape(BulletSphereShape(ball_size))

        func = random.choice([
            add_smiley,
            add_panda,
            add_mr_man_static,
            add_mr_man_dynamic,
        ])
        func(world, bullet_body)

        return task.again

    base.do_method_later(creation_interval, add_ball, 'add ball')

    # Start
    base.run()
コード例 #32
0
ファイル: client.py プロジェクト: mizahnyx/panda3dplanetgen
class Mecha01Client(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
        self.plight = PointLight('plight')
        self.pnlp = self.camera.attachNewNode(self.plight)
        render.setLight(self.pnlp)

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

        self.world = BulletWorld()
        self.world.setDebugNode(self.debugNode)

        self.planet = Planet()
        self.planet.perlin_terrain(5, 0.5)
        self.planet.build_node_path(render, self.world)

        shape = BulletCapsuleShape(0.25, 0.5)
        node = BulletRigidBodyNode('Capsule')
        node.addShape(shape)
        np = render.attachNewNode(node)
        np.setPos(Vec3(0, 0.8, 0.8) * self.planet.get_radius())
        new_up_vector = Vec3(np.getPos() -
                             self.planet.get_node_path().getPos())
        old_up_vector = Vec3(0, 0, 1)
        q = self.__quatFromTo(old_up_vector, new_up_vector)
        np.setQuat(q)

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

        #node.applyCentralImpulse(Vec3(0.4, 0.6, 1.0))

        self.taskMgr.add(self.physicsUpdateTask, "PhysicsUpdateTask")

        self.accept('arrow_up', self.test01, ["shalala"])

    def test01(self, x):
        print(x)

    def gravity(self, position):
        down_vector = Vec3(0, 0, 0) - position
        down_vector.normalize()
        gravity = LVector3f(down_vector * 9.81)

    def physicsUpdateTask(self, task):
        dt = globalClock.getDt()

        # simulating spherical gravity
        node = self.np01.getNode(0)
        pos = self.np01.getPos()
        gravity = self.gravity(pos)
        #self.np01.setQuat(Quat(0, 1.1, 1.1, 0))

        self.world.doPhysics(dt)

        return Task.cont

    def spinCameraTask(self, task):
        # angleDegrees = task.time * 6.0
        # angleRadians = angleDegrees * (pi / 180.0)
        # self.camera.setPos(
        #     100.0 * sin(angleRadians),
        #     -100.0 * cos(angleRadians), 0.0)
        # self.camera.setHpr(angleDegrees, 0, 0)
        self.camera.setPos(self.np01.getPos() * 5.0)
        self.camera.lookAt(self.np01)
        return Task.cont

    def __quatFromTo(self, v0, v1):
        print(v0, v1)
        q = Quat(
            sqrt(v0.length()**2 * v1.length()**2) + v0.dot(v1), v0.cross(v1))
        q.normalize()
        return q
コード例 #33
0
ファイル: initGame.py プロジェクト: flips30240/VoxelDash
class initGame():

    def __init__(self, windowProps, user, connection):
        self.user = user
        self.connection = connection
        render.setShaderAuto()

        self.wp = windowProps
        # keeps the game running the same on all systems (kinda sorta barely)#
        FPS = 60
        globalClock = ClockObject.getGlobalClock()
        globalClock.setMode(ClockObject.MLimited)
        globalClock.setFrameRate(FPS)
        globalClock.setMaxDt(1)

        self.world = BulletWorld()
        self.fakeNode = render.attachNewNode("fakeNode")

        self.initFakeGui()
        self.playIntroLevelMusic()
        self.initBullet()
        self.initScore()
        self.initCollisions()
        self.loadPlayer()
        self.createCamera(self.player.np)
        self.parseLevelFile("Home")
        self.getLevelBounds()
        self.startTime()
        self.createLight()
        self.loadSkyBox()
        self.loadControls()
        #self.parseStory()

        colour = (0.5,0.8,0.8)
        expfog = Fog("Scene-wide exponential Fog object")
        expfog.setColor(*colour)
        expfog.setExpDensity(0.0005)
        render.setFog(expfog)
        base.setBackgroundColor(*colour)

        base.camLens.setFar(1000)

    def playIntroLevelMusic(self):
        self.music = Music("play","./sounds/batfeet.mp3", .1, True)

    def getLevelBounds(self):
        self.levelNodeBounds = render.find("renderDummy").getBounds()

    def parseStory(self):
        self.story = StoryParser("./stories/Story.txt")

    def searchDirectories(self):
        for root, dirs, files in os.walk("./"):
            for name in files:
                if name.endswith((".txt")):
                    print(name)
            for name in dirs:
                if name == "textures":
                    for root, dirs, files in os.walk(name):
                        for name in files:
                            if name.endswith(".jpg"):
                                print(name)
    def initFakeGui(self):
        self.menuBar = OnscreenImage(image = './graphics/MenuBar.png', pos = (0,0,-.94))
        self.userText = OnscreenText(text = self.user, pos = (-1.05, -.9625), scale = 0.1)
        self.menuBar.setScale(1.625, 1, .0625)

    def initScore(self):
        self.scoreHandler = ScoreHandler()

    def initCollisions(self):
        self.collisions = pCollisions(self.scoreHandler, self.music)

    def parseLevelFile(self, arg):
        if arg == "Home":
            self.parsedLevel = LevelParser("./levels/HomeLevel.txt", self.collisions, self.player.np, self.world, self.scoreHandler)

    def startTime(self):
        self.time = KeepTime()

    def initBullet(self):
        self.world.setGravity(Vec3(0, 0, -9.81))

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

        self.debugNP = render.attachNewNode(self.debugNode)
        self.world.setDebugNode(self.debugNP.node())

    def loadSkyBox(self):
        self.skyBox = SkyBox("Box")

    def createCamera(self, nodePath):
        self.camera = gameCamera(nodePath, self.world, self.collisions)

    def loadControls(self):
        #args order = bullet update loop, bullet debug node, camera, windowProps, player class, spotLightNode, windowProps, timerTask, bulletWorld, collisions#
        self.controlHandler = ControlHandler(self.update, self.debugNP, self.camera, self.wp, self.player, self.time.timerTask, self.world, self.collisions, self.music)

    def loadPlayer(self):
        self.player = Player(self.collisions, "sphere", self.world, self.music, self.scoreHandler)
        #self.player = Player("sphere", self.world, 0, 0, 16)

    def createLight(self):
        self.lightSource = GameLight(self.player.np)

    def update(self, task):
        ##############################################
        #              #BULLET UPDATE#               #
        ##############################################
        dt = globalClock.getDt()
        #self.dtTimer()
        self.world.doPhysics(dt*2, 7)

        #############################################
        #            #CAMERA UPDATE#                #
        #############################################
        self.camera.cn.setPos(self.player.np.getPos())
        #self.fakeNode.setPos(self.player.np.getPos())
        self.camera.hNode.setPos(self.player.np.getPos())
        self.camera.pNode.setPos(self.player.np.getPos())

        self.camera.cn.setP(self.camera.pNode.getP())
        self.camera.cn.setH(self.camera.hNode.getH())

        pointer = base.win.getPointer(0)
        pointerX = pointer.getX()
        pointerY = pointer.getY()

        if base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize ()/2):
            if self.camera.inverted == "yes":
                Pitch = -((pointerY - base.win.getYSize()/2)*.1)
            else:
                Pitch = ((pointerY - base.win.getYSize()/2)*.1)
            Heading = -((pointerX - base.win.getXSize()/2)*.1)

            #endValue = 0
            #endValue += Pitch

            self.camera.pNode.setP(self.camera.pNode, Pitch)
            self.camera.hNode.setH(self.camera.hNode, Heading)

            #self.fakeNode.setH(self.fakeNode, Heading)

        #############################################
        #             #PLAYER UPDATE#               #
        #############################################
        force = Vec3(0, 0, 0)

        if inputState.isSet('up'):
            force.setY(10.0)
        if inputState.isSet('down'):
            force.setY(-10.0)
        if inputState.isSet('left'):
            force.setX(-10.0)
        if inputState.isSet('right'):
            force.setX(10.0)

        #force *= 10
        force = render.getRelativeVector(self.camera.cn, force)

        self.player.np.node().setActive(True)
        self.player.np.node().applyCentralForce(force)
        #self.player.np.setColor(random.random(), random.random(), random.random(), random.random())

        if self.player.np.getZ() < 0 - (self.levelNodeBounds.getRadius() * 6):
            self.player.np.setPos(self.collisions.level.spawn)
            self.player.np.node().setLinearVelocity(Vec3(0,0,0))

        return task.cont
コード例 #34
0
    def __init__(self, screen_size=84, DEBUGGING=False):
        ShowBase.__init__(self)
        self.render_stuff = True
        self.actions = 3

        self.render.setShaderAuto()
        self.cam.setPos(0, 0, 7)
        self.cam.lookAt(0, 0, 0)

        wp = WindowProperties()
        window_size = screen_size
        wp.setSize(window_size, window_size)
        self.win.requestProperties(wp)

        # Create Ambient Light
        self.ambientLight = AmbientLight('ambientLight')
        self.ambientLight.setColor((0.2, 0.2, 0.2, 1))
        self.ambientLightNP = self.render.attachNewNode(self.ambientLight)
        self.render.setLight(self.ambientLightNP)

        # Spotlight
        self.light = Spotlight('light')
        self.light.setColor((0.9, 0.9, 0.9, 1))
        self.lightNP = self.render.attachNewNode(self.light)
        self.lightNP.setPos(0, 10, 10)
        self.lightNP.lookAt(0, 0, 0)
        self.lightNP.node().getLens().setFov(40)
        self.lightNP.node().getLens().setNearFar(10, 100)
        self.lightNP.node().setShadowCaster(True, 1024, 1024)
        self.render.setLight(self.lightNP)

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

        if DEBUGGING is True:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            debugNP = render.attachNewNode(debugNode)
            debugNP.show()
            self.world.setDebugNode(debugNP.node())

        # Reward zone
        self.rzone_shape = BulletBoxShape(Vec3(.8, 1, 0.5))
        self.rzone_ghost = BulletGhostNode('Reward Zone')
        self.rzone_ghost.addShape(self.rzone_shape)
        self.rzone_ghostNP = self.render.attachNewNode(self.rzone_ghost)
        self.rzone_ghostNP.setPos(2.2, 0.0, 0.86)
        self.rzone_ghostNP.setCollideMask(BitMask32(0x0f))
        self.world.attachGhost(self.rzone_ghost)

        # Needed for camera image
        self.dr = self.camNode.getDisplayRegion(0)

        # Needed for camera depth image
        winprops = WindowProperties.size(self.win.getXSize(),
                                         self.win.getYSize())
        fbprops = FrameBufferProperties()
        fbprops.setDepthBits(1)
        self.depthBuffer = self.graphicsEngine.makeOutput(
            self.pipe, "depth buffer", -2, fbprops, winprops,
            GraphicsPipe.BFRefuseWindow, self.win.getGsg(), self.win)
        self.depthTex = Texture()
        self.depthTex.setFormat(Texture.FDepthComponent)
        self.depthBuffer.addRenderTexture(self.depthTex,
                                          GraphicsOutput.RTMCopyRam,
                                          GraphicsOutput.RTPDepth)
        lens = self.cam.node().getLens()
        # the near and far clipping distances can be changed if desired
        # lens.setNear(5.0)
        # lens.setFar(500.0)
        self.depthCam = self.makeCamera(self.depthBuffer,
                                        lens=lens,
                                        scene=render)
        self.depthCam.reparentTo(self.cam)
コード例 #35
0
ファイル: client.py プロジェクト: mizahnyx/panda3dplanetgen
class Mecha01Client(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
        self.plight = PointLight('plight')
        self.pnlp = self.camera.attachNewNode(self.plight)
        render.setLight(self.pnlp)


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

        self.world = BulletWorld()
        self.world.setDebugNode(self.debugNode)

        self.planet = Planet()
        self.planet.perlin_terrain(5, 0.5)
        self.planet.build_node_path(render, self.world)

        shape = BulletCapsuleShape(0.25, 0.5)
        node = BulletRigidBodyNode('Capsule')
        node.addShape(shape)
        np = render.attachNewNode(node)
        np.setPos(Vec3(0, 0.8, 0.8)*self.planet.get_radius())
        new_up_vector = Vec3(
            np.getPos() - self.planet.get_node_path().getPos())
        old_up_vector = Vec3(0, 0, 1)
        q = self.__quatFromTo(old_up_vector, new_up_vector)
        np.setQuat(q)
    
        self.np01 = np
        self.world.attachRigidBody(node)

        #node.applyCentralImpulse(Vec3(0.4, 0.6, 1.0))

        self.taskMgr.add(self.physicsUpdateTask, "PhysicsUpdateTask")

        self.accept('arrow_up', self.test01, ["shalala"])

    def test01(self, x):
        print x

    def gravity(self, position):
        down_vector = Vec3(0, 0, 0) - position
        down_vector.normalize()
        gravity = LVector3f(down_vector*9.81)
        
    def physicsUpdateTask(self, task):
        dt = globalClock.getDt()

        # simulating spherical gravity
        node = self.np01.getNode(0)
        pos = self.np01.getPos()
        gravity = self.gravity(pos)
        #self.np01.setQuat(Quat(0, 1.1, 1.1, 0))

        self.world.doPhysics(dt)

        return Task.cont

    def spinCameraTask(self, task):
        # angleDegrees = task.time * 6.0
        # angleRadians = angleDegrees * (pi / 180.0)
        # self.camera.setPos(
        #     100.0 * sin(angleRadians),
        #     -100.0 * cos(angleRadians), 0.0)
        # self.camera.setHpr(angleDegrees, 0, 0)
        self.camera.setPos(self.np01.getPos()*5.0)
        self.camera.lookAt(self.np01)
        return Task.cont

    def __quatFromTo(self, v0, v1):
        print (v0, v1)
        q = Quat(
            sqrt(v0.length()**2 * v1.length()**2) + v0.dot(v1),
            v0.cross(v1))
        q.normalize()
        return q
コード例 #36
0
ファイル: world.py プロジェクト: hrhryusuke/wrs
 def __init__(self,
              cam_pos=np.array([2.0, 0.5, 2.0]),
              lookat_pos=np.array([0, 0, 0.25]),
              up=np.array([0, 0, 1]),
              fov=40,
              w=1920,
              h=1080,
              lens_type="perspective",
              toggle_debug=False,
              auto_cam_rotate=False):
     """
     :param cam_pos:
     :param lookat_pos:
     :param fov:
     :param w: width of window
     :param h: height of window
     author: weiwei
     date: 2015?, 20201115
     """
     # the taskMgr, loader, render2d, etc. are added to builtin after initializing the showbase parental class
     super().__init__()
     # set up window
     winprops = WindowProperties(base.win.getProperties())
     winprops.setTitle("WRS Robot Planning and Control System")
     base.win.requestProperties(winprops)
     self.disableAllAudio()
     self.setBackgroundColor(1, 1, 1)
     # set up lens
     lens = PerspectiveLens()
     lens.setFov(fov)
     lens.setNearFar(0.001, 5000.0)
     if lens_type == "orthographic":
         lens = OrthographicLens()
         lens.setFilmSize(640, 480)
     # disable the default mouse control
     self.disableMouse()
     self.cam.setPos(cam_pos[0], cam_pos[1], cam_pos[2])
     self.cam.lookAt(Point3(lookat_pos[0], lookat_pos[1], lookat_pos[2]),
                     Vec3(up[0], up[1], up[2]))
     self.cam.node().setLens(lens)
     # set up slight
     ## ambient light
     ablight = AmbientLight("ambientlight")
     ablight.setColor(Vec4(0.2, 0.2, 0.2, 1))
     self.ablightnode = self.cam.attachNewNode(ablight)
     self.render.setLight(self.ablightnode)
     ## point light 1
     ptlight0 = PointLight("pointlight0")
     ptlight0.setColor(Vec4(1, 1, 1, 1))
     self._ptlightnode0 = self.cam.attachNewNode(ptlight0)
     self._ptlightnode0.setPos(0, 0, 0)
     self.render.setLight(self._ptlightnode0)
     ## point light 2
     ptlight1 = PointLight("pointlight1")
     ptlight1.setColor(Vec4(.4, .4, .4, 1))
     self._ptlightnode1 = self.cam.attachNewNode(ptlight1)
     self._ptlightnode1.setPos(self.cam.getPos().length(), 0,
                               self.cam.getPos().length())
     self.render.setLight(self._ptlightnode1)
     ## point light 3
     ptlight2 = PointLight("pointlight2")
     ptlight2.setColor(Vec4(.3, .3, .3, 1))
     self._ptlightnode2 = self.cam.attachNewNode(ptlight2)
     self._ptlightnode2.setPos(-self.cam.getPos().length(), 0,
                               self.cam.getPos().length())
     self.render.setLight(self._ptlightnode2)
     # helpers
     self.p3dh = p3dh
     # self.o3dh = o3dh
     self.rbtmath = rm
     # set up inputmanager
     self.lookatpos = lookat_pos
     self.inputmgr = im.InputManager(self, self.lookatpos)
     taskMgr.add(self._interaction_update, "interaction", appendTask=True)
     # set up rotational cam
     if auto_cam_rotate:
         taskMgr.doMethodLater(.1, self._rotatecam_update, "rotate cam")
     # set window size
     props = WindowProperties()
     props.setSize(w, h)
     self.win.requestProperties(props)
     # outline edge shader
     # self.set_outlineshader()
     # set up cartoon effect
     self._separation = 1
     self.filter = flt.Filter(self.win, self.cam)
     self.filter.setCartoonInk(separation=self._separation)
     # self.filter.setViewGlow()
     # set up physics world
     self.physics_scale = 1e3
     self.physicsworld = BulletWorld()
     self.physicsworld.setGravity(Vec3(0, 0, -9.81 * self.physics_scale))
     taskMgr.add(self._physics_update, "physics", appendTask=True)
     globalbprrender = base.render.attachNewNode("globalbpcollider")
     debugNode = BulletDebugNode('Debug')
     debugNode.showWireframe(True)
     debugNode.showConstraints(True)
     debugNode.showBoundingBoxes(False)
     debugNode.showNormals(True)
     self._debugNP = globalbprrender.attachNewNode(debugNode)
     self._debugNP.show()
     self.toggledebug = toggle_debug
     if toggle_debug:
         self.physicsworld.setDebugNode(self._debugNP.node())
     self.physicsbodylist = []
     # set up render update (TODO, only for dynamics?)
     self._internal_update_obj_list = [
     ]  # the nodepath, collision model, or bullet dynamics model to be drawn
     self._internal_update_robot_list = []
     taskMgr.add(self._internal_update, "internal_update", appendTask=True)
     # for remote visualization
     self._external_update_objinfo_list = []  # see anime_info.py
     self._external_update_robotinfo_list = []
     taskMgr.add(self._external_update, "external_update", appendTask=True)
     # for stationary models
     self._noupdate_model_list = []
コード例 #37
0
ファイル: gameBase.py プロジェクト: arikel/PPARPG
class GameBase(ShowBase):
	def __init__(self, KEY_LIST):
		ShowBase.__init__(self)
		
		#---------------------------------------------------------------
		# clock
		self.globalClock = ClockObject()
		
		#---------------------------------------------------------------
		# KeyHandler
		self.kh = KeyHandler(KEY_LIST)
		
		#---------------------------------------------------------------
		# Bullet
		self.world = BulletWorld()
		self.world.setGravity(Vec3(0, 0, -12.81))
		self.gravityUp = False
		
		self.debugNode = BulletDebugNode('Debug')
		self.debugNode.showWireframe(True)
		self.debugNode.showConstraints(True)
		self.debugNode.showBoundingBoxes(True)
		self.debugNode.showNormals(True)
		self.debugNP = self.render.attachNewNode(self.debugNode)
		#self.debugNP.show()
		self.world.setDebugNode(self.debugNode)
		self._debug = False
		
		#---------------------------------------------------------------
		# Player
		#---------------------------------------------------------------
		# CharacterController
		self.player = CharacterController(self)
		self.player.setActor('models/characters/female', {
				'walk' : 'models/characters/female-walk.egg'
			},
			flip = True,
			pos = (0,0,-1),
			scale = 1.0)
		self.player.setPos(0, -5, 3)
		self.player.playerModel.loop("walk")
		self.playerNp = self.player.np
		
		#---------------------------------------------------------------
		# Camera
		self.camHandler = CamHandler(self)
		
		#---------------------------------------------------------------
		# task
		#self.taskMgr.add(self.update, "update")
	
	#---------------------------------------------------------------
	# FPS
	def toggleFPS(self):
		if self.frameRateMeter:
			self.setFrameRateMeter(False)
		else:
			self.setFrameRateMeter(True)
	
	#---------------------------------------------------------------
	# Mouse cursor
	def hideCursor(self):
		props = WindowProperties()
		props.setCursorHidden(True) 
		self.win.requestProperties(props)
	def showCursor(self):
		props = WindowProperties()
		props.setCursorHidden(False)
		self.win.requestProperties(props)
	
	def getObjectHoverName(self):
		if not self.mouseWatcherNode.hasMouse():
			return None
		pMouse = self.mouseWatcherNode.getMouse()
		pFrom = Point3()
		pTo = Point3()
		self.camLens.extrude(pMouse, pFrom, pTo)
		# Transform to global coordinates
		pFrom = self.render.getRelativePoint(self.cam, pFrom)
		pTo = self.render.getRelativePoint(self.cam, pTo)
		result = self.world.rayTestClosest(pFrom, pTo)
		if result.hasHit():
			pos = result.getHitPos()
			name = result.getNode().getName()
			return name
		else:
			return None
		
	def getObjectCenterScreen(self):
		pFrom = Point3()
		pTo = Point3()
		self.camLens.extrude((0,0), pFrom, pTo)
		# Transform to global coordinates
		pFrom = self.render.getRelativePoint(self.cam, pFrom)
		pTo = self.render.getRelativePoint(self.cam, pTo)
		result = self.world.rayTestClosest(pFrom, pTo)
		if result.hasHit():
			pos = result.getHitPos()
			name = result.getNode().getName()
			return name
		else:
			return None
	
	#---------------------------------------------------------------
	# Fog
	def setFog(self):
		myFog = Fog("Fog")
		myFog.setColor((0,0,0,1))
		myFog.setExpDensity(0.025)
		self.render.setFog(myFog)
		self.fog = True
		
	def clearFog(self):
		self.render.clearFog()
		self.fog = False
		
	def toggleFog(self):
		if self.fog:
			self.clearFog()
		else:
			self.setFog()
	
	
	#---------------------------------------------------------------
	# Camera	
	def setFov(self, x):
		self.camLens.setFov(x)
	
	def getFov(self):
		return self.camLens.getFov()[0]
	
	def setNear(self, n):
		self.camLens.setNear(n)
		
	def setFar(self, n):
		self.camLens.setFar(n)
	
	#---------------------------------------------------------------	
	# Physics
	
	def toggleGravity(self):
		if self.gravityUp:
			self.gravityUp = False
			self.world.setGravity(Vec3(0,0,-9.8))
		else:
			self.gravityUp = True
			self.world.setGravity(Vec3(0,0,9.8))
		
	def toggleDebug(self):
		#print "Toggle debug, extraArgs = %s" % (extraArgs)
		if self._debug:
			self._debug = False
			self.debugNP.hide()
		else:
			self._debug = True
			self.debugNP.show()

	def updatePhysics(self, dt):
		#self.world.doPhysics(dt, 20, 1.0/180)
		self.world.doPhysics(dt)
		#cnt = self.world.contactTest(self.ground.node)
		#for boxName in self.objects:
		#	self.objects[boxName].update(dt)
		'''
			cntTest = self.world.contactTest(self.objects[boxName].node)
			cnt = cntTest.getContacts()
			for c in cnt:
				node0 = c.getNode0().getName()
				node1 = c.getNode1().getName()
				#print node0, " in contact with ", node1
		'''
		
	def update(self, task):
		self.globalClock.tick()
		t = self.globalClock.getFrameTime()
		dt = self.globalClock.getDt()
		self.updatePhysics(dt)
		self.player.update(dt)
		return task.cont
	
	def quit(self):
		self.taskMgr.stop()
	
	def stop(self):
		self.taskMgr.stop()
		
	def start(self):
		self.taskMgr.run()
コード例 #38
0
    def __init__(self, character_list):
        super().__init__(self)

        self.clock = 0

        for character in character_list:
            character.HP = character.BaseHP
            # displayHP(Character)
        self.characterList = character_list
        self.buttons = []
        self.index = 0

        # Set up the World
        # The World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -gravity))

        # Camera
        self.cam.setPos(0, -15, 2)
        self.cam.lookAt(0, 0, 0)

        # The Ground
        np = self.render.attachNewNode(BulletRigidBodyNode('Ground'))
        np.node().addShape(BulletPlaneShape(Vec3(0, 0, 1), 1))
        np.setPos(0, 0, -2)
        self.world.attachRigidBody(np.node())

        # Characters
        character_list[0].insert(self.world, self.render, -1, (-2, 0))
        character_list[1].insert(self.world, self.render, 1, (2, 0))

        # Debug
        debug_node = BulletDebugNode('Debug')
        debug_node.showWireframe(True)
        debug_node.showConstraints(False)
        debug_node.showBoundingBoxes(False)
        debug_node.showNormals(False)
        self.debugNP = self.render.attachNewNode(debug_node)
        self.debugNP.show()
        self.world.setDebugNode(self.debugNP.node())
        debug_object = DirectObject()
        debug_object.accept('f1', self.toggle_debug)

        # Testing Controls
        shoulder_moving_object = ShoulderMovingObject(character_list)
        target_moving_object = TargetMovingObject()
        self.targets = target_moving_object.set_targets(*DefaultTargetPos)
        for i in range(3):
            shoulder_moving_object.move_arms(i, 0)

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

        # Set up GUI
        self.sharedInfo = OnscreenText(text="No information to display yet.",
                                       pos=(0, 0.5),
                                       scale=0.07,
                                       align=TextNode.ACenter,
                                       mayChange=1)
        self.actionBoxes, self.infoBoxes, self.useButtons, self.healthBars = [], [], [], []
        self.selectedAction, self.selection = None, None
        for side in (LEFT, RIGHT):
            action_box = DirectFrame(frameColor=(0, 0, 0, 1),
                                     frameSize=(-frame_width, frame_width,
                                                -frame_height, frame_height),
                                     pos=(side * (window_width - frame_width),
                                          0, -(window_height - frame_height)))
            info_box = OnscreenText(text="No info available",
                                    scale=0.07,
                                    align=TextNode.ACenter,
                                    mayChange=1)
            info_box.reparentTo(action_box)
            info_box.setPos(0, frame_height + 0.25)
            use_button = DirectButton(frameSize=(-button_width, button_width,
                                                 -button_height,
                                                 button_height),
                                      text="N/A",
                                      text_scale=0.1,
                                      borderWidth=(0.025, 0.025),
                                      command=self.use_action,
                                      state=DGG.DISABLED)
            use_button.reparentTo(action_box)
            use_button.setPos(frame_width - button_width, 0, 0)
            hp = self.characterList[0 if side < 0 else side].HP
            bar = DirectWaitBar(text="",
                                range=hp,
                                value=hp,
                                pos=(side * 0.5, 0, 0.75),
                                frameSize=(side * -0.4, side * 0.5, 0, -0.05))
            self.actionBoxes.append(action_box)
            self.infoBoxes.append(info_box)
            self.useButtons.append(use_button)
            self.healthBars.append(bar)

        self.query_action()
コード例 #39
0
ファイル: conv_env.py プロジェクト: Shirnia/l_sim
    def __init__(self, screen_size=84, DEBUGGING=False, human_playable=False):
        ShowBase.__init__(self)
        self.forward_button = KeyboardButton.ascii_key(b'w')
        self.backward_button = KeyboardButton.ascii_key(b's')

        self.fps = 20
        self.human_playable = human_playable
        self.actions = 3
        self.last_frame_start_time = time.time()
        self.action_buffer = [1, 1, 1]
        self.last_teleport_time = 0.0
        self.time_to_teleport = False

        if self.human_playable is False:
            winprops = WindowProperties.size(screen_size, screen_size)
            fbprops = FrameBufferProperties()
            fbprops.set_rgba_bits(8, 8, 8, 0)
            fbprops.set_depth_bits(24)
            self.pipe = GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl')
            self.imageBuffer = self.graphicsEngine.makeOutput(
                self.pipe,
                "image buffer",
                1,
                fbprops,
                winprops,
                GraphicsPipe.BFRefuseWindow)


            self.camera = Camera('cam')
            self.cam = NodePath(self.camera)
            self.cam.reparentTo(self.render)

            self.dr = self.imageBuffer.makeDisplayRegion()
            self.dr.setCamera(self.cam)

        self.render.setShaderAuto()
        self.cam.setPos(0.5, 0, 6)
        self.cam.lookAt(0.5, 0, 0)

        # Create Ambient Light
        self.ambientLight = AmbientLight('ambientLight')
        self.ambientLight.setColor((0.2, 0.2, 0.2, 1))
        self.ambientLightNP = self.render.attachNewNode(self.ambientLight)
        self.render.setLight(self.ambientLightNP)

        # Spotlight
        self.light = Spotlight('light')
        self.light.setColor((0.9, 0.9, 0.9, 1))
        self.lightNP = self.render.attachNewNode(self.light)
        self.lightNP.setPos(0, 10, 10)
        self.lightNP.lookAt(0, 0, 0)
        self.lightNP.node().getLens().setFov(40)
        self.lightNP.node().getLens().setNearFar(10, 100)
        self.lightNP.node().setShadowCaster(True, 1024, 1024)
        self.render.setLight(self.lightNP)

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

        if DEBUGGING is True:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            debugNP = render.attachNewNode(debugNode)
            debugNP.show()
            self.world.setDebugNode(debugNP.node())

        self.finger_speed_mps = 0.0
        self.penalty_applied = False
        self.teleport_cooled_down = True
        self.fps = 20
        self.framecount = 0
        self.reset()
コード例 #40
0
    def __init__(self):
        """
		Creates the window, loads the scene and models and sets everything up.
		"""
        # Initialise panda window
        ShowBase.__init__(self)
        self.setBackgroundColor(.1, .1, .1)

        # Setup window
        wp = WindowProperties()
        wp.setOrigin(0, 0)
        wp.setSize(self.PANDA_WINDOW_WIDTH, self.PANDA_WINDOW_HEIGHT)

        # Get drawing area and set its size
        panda_drawing_area = builder.get_object("pandaDrawingArea")
        panda_drawing_area.set_size_request(self.PANDA_WINDOW_WIDTH,
                                            self.PANDA_WINDOW_HEIGHT)

        # Panda should not open own top level window but use the window of the drawing area in GTK
        handle = NativeWindowHandle.makeInt(
            panda_drawing_area.get_property('window').get_xid())
        wp.setParentWindow(handle)

        # Open panda window
        self.openDefaultWindow(props=wp)

        def gtk_iteration(task):
            """
			Handles the gtk events and lets as many GUI iterations run as needed.
			"""
            while Gtk.events_pending():
                Gtk.main_iteration_do(False)
            return task.cont

        # Create task to update GUI
        self.taskMgr.add(gtk_iteration, "gtk")

        # Activate antialiasing (MAuto for automatic selection of AA form)
        self.render.setAntialias(AntialiasAttrib.MAuto)

        # Deactivate default mouse control of the camera as they are not very helpful
        self.disableMouse()

        # Set camera to default position and orientation
        self.camera.setPos(0, -4, 2)
        self.camera.lookAt(0, 0, 1)
        self.camLens.setFov(90)

        # Load the camera control events to control camera by keyboard
        self.cam_control = CameraControl(self, handler)
        # Store it as a class variable of the Handler so the controller can be called by it
        Handler.cam_control = self.cam_control

        # Load scene
        self.scene = self.loader.loadModel("models/rooms/room_neu.egg")
        self.scene.reparentTo(
            self.render
        )  # Panda3D makes use of a scene graph, where "render" is the parent of the
        # tree containing all objects to be rendered

        # Add lights
        # TODO: Make the lighting somewhat nicer (maybe with some ambient lights?)
        for i in range(0, 3):
            dlight = DirectionalLight("light")
            dlnp = self.render.attachNewNode(dlight)
            dlnp.setHpr((120 * i) + 1, -30, 0)
            self.render.setLight(dlnp)

        # Create a bullet world (physics engine)
        self.world = BulletWorld()
        # self.world.setGravity(LVector3f(0, 0, -9.81))
        self.world.setGravity(LVector3f(
            0, 0, 0))  # No gravity for now (makes forces easier to calculate)

        def update_bullet(task):
            """
			Invokes the physics engine to update and simulate the next step.
			"""
            dt = globalClock.getDt()  # get elapsed time
            self.world.doPhysics(dt)  # actually update
            return task.cont

        # Create task to update physics
        self.taskMgr.add(update_bullet, 'update_bullet')

        # Set up the ground for the physics engine
        ground_shape = BulletPlaneShape(LVector3f(0, 0, 1),
                                        0)  # create a collision shape
        ground_node_bullet = BulletRigidBodyNode('Ground')  # create rigid body
        ground_node_bullet.addShape(ground_shape)  # add shape to it

        ground_node_panda = self.render.attachNewNode(
            ground_node_bullet)  # attach to panda scene graph
        ground_node_panda.setPos(0, 0, 0)  # set position

        self.world.attachRigidBody(
            ground_node_bullet)  # attach to physics world

        # Create and activate a debug node for bullet and attach it to the panda scene graph
        debug_node_bullet = BulletDebugNode('Debug')
        debug_node_bullet.showWireframe(True)
        debug_node_bullet.showConstraints(True)
        debug_node_bullet.showBoundingBoxes(True)
        debug_node_bullet.showNormals(True)
        debug_node_panda = self.render.attachNewNode(debug_node_bullet)
        # debug_node_panda.show()
        self.world.setDebugNode(debug_node_panda.node())
        # Store it as a class variable of the Handler so the debug mode can be switched by it
        Handler.bullet_debug_node = debug_node_panda

        # Load the class to manage the drones
        self.drone_manager = DroneManager(self)
        # Store it as a class variable of the Handler changes can be invoked
        Handler.drone_manager = self.drone_manager
コード例 #41
0
ファイル: main.py プロジェクト: monicagraciela/PPARPG
class Game(GameBase, FSM):
	def __init__(self):
		GameBase.__init__(self, KEY_LIST)
		
		FSM.__init__(self, 'Game')
		self.setBackgroundColor(0,0,0)
		
		self.accept("space", self.toggleFPS)
		self.accept("escape", self.taskMgr.stop)
		
		
		'''
		self.shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
 
		self.node = BulletRigidBodyNode('Ground')
		self.node.addShape(self.shape)
		 
		self.np = self.render.attachNewNode(self.node)
		self.np.setPos(0, 0, 0)
		
		self.world.attachRigidBody(self.node)
		'''
		
		self.debugNode = BulletDebugNode('Debug')
		self.debugNode.showWireframe(True)
		self.debugNode.showConstraints(True)
		self.debugNode.showBoundingBoxes(True)
		self.debugNode.showNormals(True)
		self.debugNP = self.render.attachNewNode(self.debugNode)
		self.debugNP.show()
		
		
		self.bulletbox = BulletBoxShape(Vec3(0.5, 0.5, 0.5))

		self.bulletboxnode = BulletRigidBodyNode('Box')
		self.bulletboxnode.setMass(1.0)
		self.bulletboxnode.addShape(self.bulletbox)
		 
		self.bulletboxnp = self.render.attachNewNode(self.bulletboxnode)
		#self.bulletboxnp = NodePath(self.bulletboxnode)
		#self.bulletboxnp.reparentTo(self.render)
		self.bulletboxnp.setPos(0, 0, 15)
		self.bulletboxnp.setScale(5,3,0.5)
		self.world.attachRigidBody(self.bulletboxnode)
		self.model = self.loader.loadModel("models/props/crate.egg")
		self.model.reparentTo(self.bulletboxnp)
		
		
		#---------------------------------------------------------------
		# Ground (StaticTerrain)
		self.ground = StaticTerrain(self, 'models/terrain.jpg', 50)
		self.ground.setTexture(self.loader.loadTexture("models/ground.jpg"))
		
		self.sky = SkyBox(self)
		self.sky.set("teal1")
		
		self.cursor = MouseCursor(self)
		self.cursor.addCursor("cursor2")
		
		self.hideCursor()
		self.lightManager = LightManager(self)
		self.lightManager.addAmbientLight(Vec4(.5,.5,.5,1))
		self.lightManager.addPointLight(Vec4(1.0,1.0,1.0,1.0), Point3(2,-4,5))
		self.taskMgr.add(self.update, "update")
		
		print self.getAspectRatio()
		
		self.camHandler = CamHandler(self)
		self.accept(K_DRAG, self.camHandler.startDrag)
		self.accept(K_DRAG+"-up", self.camHandler.stopDrag)
		
	def update(self, task):
		self.globalClock.tick()
		t = self.globalClock.getFrameTime()
		dt = self.globalClock.getDt()
		
		self.updatePhysics(dt)
		
		self.player.update(dt,
			self.kh.getKey(K_RIGHT) - self.kh.getKey(K_LEFT),
			self.kh.getKey(K_FORWARD) - self.kh.getKey(K_BACKWARD),
			self.kh.getKey(K_JUMP),
			self.kh.getKey(K_CROUCH),
			self.kh.getKey(K_TURN_LEFT) - self.kh.getKey(K_TURN_RIGHT))
		
		self.camHandler.update()
		
		return task.cont
コード例 #42
0
ファイル: physics.py プロジェクト: MJ-meo-dmt/Ecliptic
class Physics(DirectObject):

    """
    Physics Class:
    
    Handles the all Physics
    """

    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()
        # taskMgr.add(self.checkGhost, 'checkGhost')

    def setup_world(self):

        #############################################
        ##
        ##  GROUND FOR TESTING
        #############################################
        pass
        # 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.allOn())

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

        ##############################################
        ##############################################

        ########################
        # FIXED :D  - Still simple atm.
        ########################

    def playerPickup(self):

        # Write a class for pick able objects so that we instance the object in the world and if picked up we change that instance or del it then create new one, then same again when dropped

        bodyA = base.camera

        # Will have to make a pick up mask so that it collides with walls and floors and w/e else.. except with the player
        if self.pickTest == False:
            self.test.bodyNP.wrtReparentTo(PLAYER["CLASS"].picker)
            # self.test.bodyNP.copyTo(bodyA)
            # self.test.worldNP
            # bodyB.setPos(0, 2, 0)
            self.test.bodyNP.node().setMass(1.0)
            # self.test.bodyNP.setScale(1)
            # self.test.bodyNP.setCollideMask(BitMask32.allOn())
            self.pickTest = True

        elif self.pickTest == True:
            self.test.bodyNP.wrtReparentTo(GAMEPLAY_NODES["ITEM"])
            self.test.bodyNP.node().setMass(1.0)
            # self.test.bodyNP.setCollideMask(BitMask32.allOn())
            # bodyB.setPos(bodyPos)
            self.pickTest = False

        # Simulate Physics

    def update(self, task):

        dt = globalClock.getDt()
        self.world.doPhysics(dt, 4, 1.0 / 270.0)

        return task.cont

        # Enable/Disable debug

    def showDebug(self):

        # To enable debug
        self.debugNode = BulletDebugNode("Debug")
        self.debugNode.showBoundingBoxes(True)
        self.debugNode.showNormals(False)
        self.debugNode.showWireframe(True)
        self.debugNode.showConstraints(True)
        self.debugNP = render.attachNewNode(self.debugNode)
        self.debugNP.show()

        # Add the debug node to the physics world
        self.world.setDebugNode(self.debugNP.node())
コード例 #43
0
    # robotplot = nxtplot

    # robot.goinitpose()
    # robot.movearmfk([0.0,-20.0,-60.0,-70.0,-100.0,-30.0,0.0,0.0,0.0])
    # robot.movearmfk([0.0,-20.0,60.0,70.0,-100.0,30.0,0.0,0.0,0.0], armid = 'lft')
    # robotmnp = robotmesh.genmnp(robot)
    # robotmnp.reparentTo(base.render)

    # ur5dualmnp = ur5dualplot.genUr5dualmnp(robot, handpkg)
    # ur5dualmnp.reparentTo(base.render)
    pg.plotAxisSelf(base.render, Vec3(0,0,0))

    cdchecker = CollisionChecker(robotmesh)
    print cdchecker.isSelfCollided(robot)

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

    cdchecker.bulletworld.setDebugNode(debugNP.node())

    def updateworld(world, task):
        world.doPhysics(globalClock.getDt())
        return task.cont
    base.taskMgr.add(updateworld, "updateworld", extraArgs=[cdchecker.bulletworld], appendTask=True)
    base.run()
コード例 #44
0
ファイル: pandactrl.py プロジェクト: wangyan-hlab/pydmps
    def __init__(self,
                 camp=[2000, 500, 2000],
                 lookatpos=[0, 0, 250],
                 up=[0, 0, 1],
                 fov=40,
                 w=2000,
                 h=1500,
                 toggledebug=False,
                 autocamrotate=False):
        """

        :param camp:
        :param lookatpos:
        :param fov:
        :param w: width of window
        :param h: height of window
        """

        # the taskMgr, loader, render2d, etc. are added to builtin after initializing the showbase parental class
        super().__init__()

        self.setBackgroundColor(1, 1, 1)

        # set up lens
        lens = PerspectiveLens()
        lens.setFov(fov)
        lens.setNearFar(1, 50000)
        # disable the default mouse control
        self.disableMouse()
        self.cam.setPos(camp[0], camp[1], camp[2])
        self.cam.lookAt(Point3(lookatpos[0], lookatpos[1], lookatpos[2]),
                        Vec3(up[0], up[1], up[2]))
        self.cam.node().setLens(lens)

        # set up slight
        ablight = AmbientLight("ambientlight")
        ablight.setColor(Vec4(0.2, 0.2, 0.2, 1))
        self.__ablightnode = self.cam.attachNewNode(ablight)
        self.render.setLight(self.__ablightnode)

        ptlight0 = PointLight("pointlight1")
        ptlight0.setColor(Vec4(1, 1, 1, 1))
        self.__ptlightnode0 = self.cam.attachNewNode(ptlight0)
        self.__ptlightnode0.setPos(0, 0, 0)
        self.render.setLight(self.__ptlightnode0)

        ptlight1 = PointLight("pointlight1")
        ptlight1.setColor(Vec4(.4, .4, .4, 1))
        self.__ptlightnode1 = self.cam.attachNewNode(ptlight1)
        self.__ptlightnode1.setPos(self.cam.getPos().length(), 0,
                                   self.cam.getPos().length())
        self.render.setLight(self.__ptlightnode1)

        ptlight2 = PointLight("pointlight2")
        ptlight2.setColor(Vec4(.3, .3, .3, 1))
        self.__ptlightnode2 = self.cam.attachNewNode(ptlight2)
        self.__ptlightnode2.setPos(-self.cam.getPos().length(), 0,
                                   base.cam.getPos().length())
        self.render.setLight(self.__ptlightnode2)

        # helpers
        # use pg to access the util functions; use pggen to generate the geometries for decoration
        # for back-compatibility purpose
        self.pg = pg
        self.pggen = pg.PandaDecorator()
        self.p3dh = p3dhelper
        self.o3dh = o3dhelper
        self.rm = rm

        # set up inputmanager
        self.inputmgr = im.InputManager(self, lookatpos, self.pggen)
        taskMgr.add(self.__interactionUpdate, "interaction", appendTask=True)

        # set up rotational cam
        self.lookatp = lookatpos
        if autocamrotate:
            taskMgr.doMethodLater(.1, self.__rotatecamUpdate, "rotate cam")

        # set window size
        props = WindowProperties()
        props.setSize(w, h)
        self.win.requestProperties(props)

        # set up cartoon effect
        self.__separation = 1
        self.filters = CommonFilters(self.win, self.cam)
        self.filters.setCartoonInk(separation=self.__separation)
        # self.setCartoonShader(False)

        # set up physics world
        self.physicsworld = BulletWorld()
        self.physicsworld.setGravity(Vec3(0, 0, -981))
        taskMgr.add(self.__physicsUpdate, "physics", appendTask=True)
        if toggledebug:
            globalbprrender = base.render.attachNewNode("globalbpcollider")
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(True)
            self._debugNP = globalbprrender.attachNewNode(debugNode)
            self._debugNP.show()
            self.physicsworld.setDebugNode(self._debugNP.node())

        # set up render update
        self.__objtodraw = [
        ]  # the nodepath, collision model, or bullet dynamics model to be drawn
        taskMgr.add(self.__renderUpdate, "render", appendTask=True)