axis.setPos(hndpos) axis.setScale(50) axis.lookAt(hndpos+ydirect) bullcldrnp = base.render.attachNewNode("bulletcollider") base.world = BulletWorld() # hand base # rtq85hnd.rtq85np.find("**/rtq85base").showTightBounds() gbnp = rtq85hnd.rtq85np.find("**/rtq85base").find("**/+GeomNode") gb = gbnp.node().getGeom(0) gbts = gbnp.getTransform(base.render) gbmesh = BulletTriangleMesh() gbmesh.addGeom(gb) bbullnode = BulletRigidBodyNode('gb') bbullnode.addShape(BulletTriangleMeshShape(gbmesh, dynamic=True), gbts) bcollidernp=bullcldrnp.attachNewNode(bbullnode) base.world.attachRigidBody(bbullnode) bcollidernp.setCollideMask(BitMask32.allOn()) # rtq85hnd.rtq85np.find("**/rtq85lfgrtip").showTightBounds() glftnp = rtq85hnd.rtq85np.find("**/rtq85lfgrtip").find("**/+GeomNode") glft = glftnp.node().getGeom(0) glftts = glftnp.getTransform(base.render) glftmesh = BulletTriangleMesh() glftmesh.addGeom(glft) # lftbullnode = BulletRigidBodyNode('glft') # lftbullnode.addShape(BulletTriangleMeshShape(glftmesh, dynamic=True), glftts) # lftcollidernp=bullcldrnp.attachNewNode(lftbullnode) # base.world.attachRigidBody(lftbullnode) # lftcollidernp.setCollideMask(BitMask32.allOn())
def setup(self): #World self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) #Ground shape = BulletPlaneShape(Vec3(0, 0, 1), 1) self.ground = BulletRigidBodyNode('Ground') self.ground.addShape(shape) self.groundNp = render.attachNewNode(self.ground) self.groundNp.setPos(0, 0, 0) self.groundNp.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.ground) #BoxPyramid1 self.pyramid1 = loader.loadModel("models/pyramid/Pyramid") self.pyramid1.reparentTo(render) self.pyramid1.setScale(.5) self.pyramid1.setPos(0,-400,0) mesh = BulletTriangleMesh() for geomNP in self.pyramid1.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.pyramid1) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape2 = BulletTriangleMeshShape(mesh, dynamic=False) self.node = BulletRigidBodyNode('BoxPyramid1') self.node.setMass(0) self.node.addShape(shape2) self.np = render.attachNewNode(self.node) self.np.setPos(0, -400, 0) self.np.setScale(1.65) self.np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node) #BoxPyramid2 self.pyramid2 = loader.loadModel("models/pyramid/Pyramid") self.pyramid2.reparentTo(render) self.pyramid2.setScale(.25) self.pyramid2.setPos(180,-400,0) mesh2 = BulletTriangleMesh() for geomNP in self.pyramid2.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.pyramid2) for geom in geomNode.getGeoms(): mesh2.addGeom(geom, ts) shape3 = BulletTriangleMeshShape(mesh2, dynamic=False) self.node3 = BulletRigidBodyNode('BoxPyramid2') self.node3.setMass(0) self.node3.addShape(shape3) self.np3 = render.attachNewNode(self.node3) self.np3.setPos(180, -400, 0) self.np3.setScale(0.85) self.np3.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node3) #BoxPyramid3 self.pyramid3 = loader.loadModel("models/pyramid/Pyramid") self.pyramid3.reparentTo(render) self.pyramid3.setScale(.25) self.pyramid3.setPos(-180,-400,0) mesh3 = BulletTriangleMesh() for geomNP in self.pyramid3.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.pyramid3) for geom in geomNode.getGeoms(): mesh3.addGeom(geom, ts) shape4 = BulletTriangleMeshShape(mesh2, dynamic=False) self.node4 = BulletRigidBodyNode('BoxPyramid3') self.node4.setMass(0) self.node4.addShape(shape4) self.np4 = render.attachNewNode(self.node4) self.np4.setPos(-180, -400, 0) self.np4.setScale(0.85) self.np4.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node4) #BoxSphinx self.sphinx = loader.loadModel("models/sphinx/Sphinx") self.sphinx.reparentTo(render) self.sphinx.setScale(.08) self.sphinx.setPos(100,-50,20) shape5 = BulletBoxShape(Vec3(18, 55, 30)) self.node5 = BulletRigidBodyNode('BoxSphinx') self.node5.setMass(0) self.node5.addShape(shape5) self.np5 = render.attachNewNode(self.node5) self.np5.setPos(100, -50, 10) self.np5.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node5) #start blocks_tex6 = loader.loadTexture("models/blocks_tex6.jpg") self.box1= loader.loadModel("models/box/box3") self.box1.reparentTo(render) self.box1.setScale(10,400,10) self.box1.setPos(-300,850,0) shape8 = BulletBoxShape(Vec3(8, 315, 13.5)) self.node8 = BulletRigidBodyNode('Box1') self.node8.setMass(0) self.node8.addShape(shape8) self.np8 = render.attachNewNode(self.node8) self.np8.setPos(-300, 850, 10) self.np8.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node8) self.box2= loader.loadModel("models/box/box3") self.box2.reparentTo(render) self.box2.setScale(10,400,10) self.box2.setPos(-350,850,0) shape9 = BulletBoxShape(Vec3(8, 315, 13.5)) self.node9 = BulletRigidBodyNode('Box2') self.node9.setMass(0) self.node9.addShape(shape9) self.np9 = render.attachNewNode(self.node9) self.np9.setPos(-350, 850, 10) self.np9.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node9) self.box3= loader.loadModel("models/box/box4") self.box3.reparentTo(render) self.box3.setScale(40,10,10) self.box3.setPos(-325,543,0) shape10 = BulletBoxShape(Vec3(30, 8, 13.5)) self.node10 = BulletRigidBodyNode('Box3') self.node10.setMass(0) self.node10.addShape(shape10) self.np10 = render.attachNewNode(self.node10) self.np10.setPos(-325, 543, 10) self.np10.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node10) self.box4= loader.loadModel("models/box/box4") self.box4.reparentTo(render) self.box4.setScale(40,10,10) self.box4.setPos(-325,1157,0) shape11 = BulletBoxShape(Vec3(30, 8, 13.5)) self.node11 = BulletRigidBodyNode('Box4') self.node11.setMass(0) self.node11.addShape(shape11) self.np11 = render.attachNewNode(self.node11) self.np11.setPos(-325, 1157, 10) self.np11.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node11) #Stars 1 self.stairsList = [0] * 10 self.stairsListNp = [0] * 10 n5 = 0 for i in range(10): n5 += 2 self.stairsList[i]= loader.loadModel("models/box/box1") self.stairsList[i].reparentTo(render) self.stairsList[i].setScale(1.3) self.stairsList[i].setPos(-325,925-(n5*1.2),n5) self.stairsList[i].setHpr(0,0,90) shape6 = BulletBoxShape(Vec3(3.2, 1.1, 1.1)) node6 = BulletRigidBodyNode('Box5 '+str(i)) node6.setMass(0) node6.addShape(shape6) self.stairsListNp[i] = render.attachNewNode(node6) self.stairsListNp[i].setPos(-325, 925-(n5*1.2), n5) self.stairsListNp[i].setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(node6) self.n5Upstairs = n5 self.box6= loader.loadModel("models/box/box1") self.box6.reparentTo(render) self.box6.setScale(10,87,0.2) self.box6.setPos(-325,829,n5) self.shape12 = BulletBoxShape(Vec3(8, 70, 0.75)) self.node12 = BulletRigidBodyNode('Box6') self.node12.setMass(0) self.node12.addShape(self.shape12) self.np12 = render.attachNewNode(self.node12) self.np12.setPos(-325, 829, n5) self.np12.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node12) self.box7= loader.loadModel("models/box/box2") self.box7.reparentTo(render) self.box7.setScale(5,12,0.25) self.box7.setPos(-325,749,n5) shape13 = BulletBoxShape(Vec3(4, 10, 0.8)) self.node13 = BulletRigidBodyNode('Box7') self.node13.setMass(0) self.node13.addShape(shape13) self.np13 = render.attachNewNode(self.node13) self.np13.setPos(-325, 749, n5) self.np13.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node13) box7Interval1 = self.box7.posInterval(3.3, Point3(-325, 749, n5+5), startPos=Point3(-325, 749, n5-5)) np13Interval1 = self.np13.posInterval(3, Point3(-325, 749, n5+5), startPos=Point3(-325, 749, n5-5)) box7Interval2 = self.box7.posInterval(3.3, Point3(-325, 749, n5-5), startPos=Point3(-325, 749, n5+5)) np13Interval2 = self.np13.posInterval(3, Point3(-325, 749, n5-5), startPos=Point3(-325, 749, n5+5)) self.box7Pace = Sequence(Parallel(box7Interval1,np13Interval1), Parallel(box7Interval2,np13Interval2), name="box7Pace") self.box7Pace.loop() self.box8= loader.loadModel("models/box/box2") self.box8.reparentTo(render) self.box8.setScale(5,12,0.25) self.box8.setPos(-325,725,n5) shape14 = BulletBoxShape(Vec3(4, 10, 0.8)) node14 = BulletRigidBodyNode('Box8') node14.setMass(0) node14.addShape(shape14) self.np14 = render.attachNewNode(node14) self.np14.setPos(-325, 725, n5) self.np14.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(node14) box8Interval1 = self.box8.posInterval(3.3, Point3(-325, 725, n5-5), startPos=Point3(-325, 725, n5+5)) np14Interval1 = self.np14.posInterval(3, Point3(-325, 725, n5-5), startPos=Point3(-325, 725, n5+5)) box8Interval2 = self.box8.posInterval(3.3, Point3(-325, 725, n5+5), startPos=Point3(-325, 725, n5-5)) np14Interval2 = self.np14.posInterval(3, Point3(-325, 725, n5+5), startPos=Point3(-325, 725, n5-5)) self.box8Pace = Sequence(Parallel(box8Interval1,np14Interval1), Parallel(box8Interval2,np14Interval2), name="box8Pace") self.box8Pace.loop() self.Cylinder1= loader.loadModel("models/Cylinder/Cylinder") self.Cylinder1.reparentTo(render) self.Cylinder1.setScale(8,8,0.2) self.Cylinder1.setPos(-322,700,n5) self.Cylinder1.setTexture(blocks_tex6, 1) radius = 8 height = 1 shape16 = BulletCylinderShape(radius, height, ZUp) self.node16 = BulletRigidBodyNode('Cylinder1') self.node16.setMass(0) self.node16.addShape(shape16) self.np16 = render.attachNewNode(self.node16) self.np16.setPos(-322, 700, n5) self.np16.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node16) self.Cylinder2= loader.loadModel("models/Cylinder/Cylinder") self.Cylinder2.reparentTo(render) self.Cylinder2.setScale(8,8,0.2) self.Cylinder2.setPos(-327,680,n5) self.Cylinder2.setTexture(blocks_tex6, 1) radius = 8 height = 1 shape17 = BulletCylinderShape(radius, height, ZUp) self.node17 = BulletRigidBodyNode('Cylinder2') self.node17.setMass(0) self.node17.addShape(shape17) self.np17 = render.attachNewNode(self.node17) self.np17.setPos(-327, 680, n5) self.np17.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node17) self.Cylinder3= loader.loadModel("models/Cylinder/Cylinder") self.Cylinder3.reparentTo(render) self.Cylinder3.setScale(8,8,0.2) self.Cylinder3.setPos(-322,660,n5) self.Cylinder3.setTexture(blocks_tex6, 1) radius = 8 height = 1 shape18 = BulletCylinderShape(radius, height, ZUp) self.node18 = BulletRigidBodyNode('Cylinder3') self.node18.setMass(0) self.node18.addShape(shape18) self.np18 = render.attachNewNode(self.node18) self.np18.setPos(-322, 660, n5) self.np18.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node18) self.Cylinder4= loader.loadModel("models/Cylinder/Cylinder") self.Cylinder4.reparentTo(render) self.Cylinder4.setScale(8,8,0.2) self.Cylinder4.setPos(-327,640,n5) self.Cylinder4.setTexture(blocks_tex6, 1) radius = 8 height = 1 shape19 = BulletCylinderShape(radius, height, ZUp) self.node19 = BulletRigidBodyNode('Cylinder4') self.node19.setMass(0) self.node19.addShape(shape19) self.np19 = render.attachNewNode(self.node19) self.np19.setPos(-327, 640, n5) self.np19.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.node19) self.fire= loader.loadModel("models/stop_sign/stop_sign") self.fire.setScale(0.01) self.fire.reparentTo(render) self.fire.setPos(-327,640,n5+5) #setup the items to be collected self.setupItems() self.setupEndPoint()
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, 0) np.setCollideMask(BitMask32.allOn()) 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.node().addShape(shape, TransformState.makePos(Point3(0, 1, 0))) # np.node().setDeactivationEnabled(False) # np.setPos(2, 0, 4) # np.setCollideMask(BitMask32.allOn()) # # self.world.attachRigidBody(np.node()) visualNP = loader.loadModel('models/box.egg') visualNP.reparentTo(np) vnpgeom = visualNP.find("**/+GeomNode").node().getGeom(0) vnpxform = visualNP.getTransform(base.render) gbmesh = BulletTriangleMesh() gbmesh.addGeom(vnpgeom) bbullnode = BulletRigidBodyNode('gb') bbullnode.addShape(BulletTriangleMeshShape(gbmesh, dynamic=True), vnpxform) self.worldNP.attachNewNode(bbullnode) self.world.attachRigidBody(bbullnode) # bcollidernp.setPos(0,1,0) # self.box = np.node() self.box = bbullnode # Sphere # shape = BulletSphereShape(0.6) # # np = self.worldNP.attachNewNode(BulletRigidBodyNode('Sphere')) # # np.node().setMass(1.0) # np.node().addShape(shape) # np.node().addShape(shape, TransformState.makePos(Point3(0, 1, 0))) # np.setPos(0, 0, 0) # np.setCollideMask(BitMask32.allOn()) # # self.world.attachRigidBody(np.node()) # # self.sphere = np.node() visualNP2 = loader.loadModel('models/box.egg') visualNP2.setPos(0, 0.5, 0) visualNP2.reparentTo(np) vnpgeom2 = visualNP2.find("**/+GeomNode").node().getGeom(0) vnpxform2 = visualNP2.getTransform(base.render) gbmesh2 = BulletTriangleMesh() gbmesh2.addGeom(vnpgeom2) bbullnode2 = BulletRigidBodyNode('gb') bbullnode2.addShape(BulletTriangleMeshShape(gbmesh2, dynamic=True), vnpxform2) self.worldNP.attachNewNode(bbullnode2) self.world.attachRigidBody(bbullnode2) self.sphere = bbullnode2
def planContactpairs(self, torqueresist = 50, fgrtipdist = 82, dotnormpara = -0.75): """ find the grasps using parallel pairs :param: torqueresist the maximum allowable distance to com :param: fgrtipdist the maximum dist between finger tips :param: dotnormpara parallelity :return: author: weiwei date: 20161130, harada office @ osaka university """ # note that pairnormals and pairfacets are duplicated for each contactpair # the duplication is performed on purpose for convenient access # also, each contactpair"s" corresponds to a facetpair # it is empty when no contactpair is available self.gripcontactpairs = [] # gripcontactpairnormals and gripcontactpairfacets are not helpful # they are kept for convenience (they could be accessed using facetnormals and facetpairs) self.gripcontactpairnormals = [] self.gripcontactpairfacets = [] # for precollision detection # bulletworldprecc = BulletWorld() # # build the collision shape of objtrimesh # geomobj = pandageom.packpandageom(self.objtrimesh.vertices, self.objtrimesh.face_normals, # self.objtrimesh.faces) # objmesh = BulletTriangleMesh() # objmesh.addGeom(geomobj) # objmeshnode = BulletRigidBodyNode('objmesh') # objmeshnode.addShape(BulletTriangleMeshShape(objmesh, dynamic=True)) # bulletworldprecc.attachRigidBody(objmeshnode) # for raytracing bulletworldray = BulletWorld() nfacets = self.facets.shape[0] self.facetpairs = list(itertools.combinations(range(nfacets), 2)) for facetpair in self.facetpairs: # print("facetpair") # print(facetpair, len(self.facetpairs)) self.gripcontactpairs.append([]) self.gripcontactpairnormals.append([]) self.gripcontactpairfacets.append([]) # if one of the facet doesnt have samples, jump to next if self.objsamplepnts_refcls[facetpair[0]].shape[0] is 0 or \ self.objsamplepnts_refcls[facetpair[1]].shape[0] is 0: # print("no sampled points") continue # check if the faces are opposite and parallel dotnorm = np.dot(self.facetnormals[facetpair[0]], self.facetnormals[facetpair[1]]) if dotnorm < dotnormpara: # check if any samplepnts's projection from facetpairs[i][0] falls in the polygon of facetpairs[i][1] facet0pnts = self.objsamplepnts_refcls[facetpair[0]] facet0normal = self.facetnormals[facetpair[0]] facet1normal = self.facetnormals[facetpair[1]] # generate collision mesh facetmesh = BulletTriangleMesh() faceidsonfacet = self.facets[facetpair[1]] geom = pandageom.packpandageom_fn(self.objtrimesh.vertices, self.objtrimesh.face_normals[faceidsonfacet], self.objtrimesh.faces[faceidsonfacet]) facetmesh.addGeom(geom) facetmeshbullnode = BulletRigidBodyNode('facet') facetmeshbullnode.addShape(BulletTriangleMeshShape(facetmesh, dynamic=True)) bulletworldray.attachRigidBody(facetmeshbullnode) # check the projection of a ray for facet0pnt in facet0pnts: pFrom = Point3(facet0pnt[0], facet0pnt[1], facet0pnt[2]) pTo = pFrom + Vec3(facet1normal[0], facet1normal[1], facet1normal[2])*9999 result = bulletworldray.rayTestClosest(pFrom, pTo) if result.hasHit(): hitpos = result.getHitPos() if np.linalg.norm(np.array(facet0pnt.tolist())-np.array([hitpos[0], hitpos[1], hitpos[2]])) < fgrtipdist: fgrcenter = (np.array(facet0pnt.tolist())+np.array([hitpos[0], hitpos[1], hitpos[2]]))/2.0 # avoid large torque if np.linalg.norm(self.objtrimesh.center_mass - fgrcenter) < torqueresist: self.gripcontactpairs[-1].append([facet0pnt.tolist(), [hitpos[0], hitpos[1], hitpos[2]]]) self.gripcontactpairnormals[-1].append([[facet0normal[0], facet0normal[1], facet0normal[2]], [facet1normal[0], facet1normal[1], facet1normal[2]]]) self.gripcontactpairfacets[-1].append(facetpair) # pre collision checking: it takes one finger as a cylinder and # computes its collision with the object ## first finger # cylindernode0 = BulletRigidBodyNode('cylindernode0') # cylinder0height = 50 # cylinder0normal = Vec3(facet0normal[0], facet0normal[1], facet0normal[2]) # cylindernode0.addShape(BulletCylinderShape(radius=self.preccradius, # height=cylinder0height, # up=cylinder0normal), # TransformState.makePos(pFrom+cylinder0normal*cylinder0height*.6)) # bulletworldprecc.attachRigidBody(cylindernode0) # ## second finger # cylindernode1 = BulletRigidBodyNode('cylindernode1') # cylinder1height = cylinder1height # # use the inverse of facet0normal instead of facet1normal to follow hand orientation # cylinder1normal = Vec3(-facet0normal[0], -facet0normal[1], -facet0normal[2]) # cylindernode1.addShape(BulletCylinderShape(radius=self.preccradius, # height=cylinder1height, # up=cylinder1normal), # TransformState.makePos(pFrom+cylinder1normal*cylinder1height*.6)) # bulletworldprecc.attachRigidBody(cylindernode1) # if bulletworldprecc.contactTestPair(cylindernode0, objmeshnode) and \ # bulletworldprecc.contactTestPair(cylindernode1, objmeshnode): bulletworldray.removeRigidBody(facetmeshbullnode) # update the pairs availablepairids = np.where(self.gripcontactpairs)[0] self.facetpairs = np.array(self.facetpairs)[availablepairids] self.gripcontactpairs = np.array(self.gripcontactpairs)[availablepairids] self.gripcontactpairnormals = np.array(self.gripcontactpairnormals)[availablepairids] self.gripcontactpairfacets = np.array(self.gripcontactpairfacets)[availablepairids]
# axis = loader.loadModel('zup-axis.egg') # axis.reparentTo(base.render) bullcldrnp = base.render.attachNewNode("bulletcollider") base.world = BulletWorld() # hand base # rtq85hnd.rtq85np.find("**/rtq85base").showTightBounds() gbnp = rtq85hnd.rtq85np.find("**/rtq85base").find("**/+GeomNode") gb = gbnp.node().getGeom(0) gbts = gbnp.getTransform(base.render) gbmesh = BulletTriangleMesh() gbmesh.addGeom(gb) bbullnode = BulletRigidBodyNode('gb') bbullnode.addShape(BulletTriangleMeshShape(gbmesh, dynamic=True), gbts) bcollidernp = bullcldrnp.attachNewNode(bbullnode) base.world.attachRigidBody(bbullnode) bcollidernp.setCollideMask(BitMask32.allOn()) # rtq85hnd.rtq85np.find("**/rtq85base").showTightBounds() # rtq85hnd.rtq85np.find("**/rtq85lfgrtip").showTightBounds() glftnp = rtq85hnd.rtq85np.find("**/rtq85lfgrtip").find("**/+GeomNode") glft = glftnp.node().getGeom(0) glftts = glftnp.getTransform(base.render) glftmesh = BulletTriangleMesh() glftmesh.addGeom(glft) lftbullnode = BulletRigidBodyNode('glft') lftbullnode.addShape(BulletTriangleMeshShape(glftmesh, dynamic=True), glftts) lftcollidernp = bullcldrnp.attachNewNode(lftbullnode)
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()) # Plane (static) 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()) # Box (dynamic) 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.allOn()) self.world.attachRigidBody(np.node()) self.boxNP = np # For applying force & torque #np.node().notifyCollisions(True) #self.accept('bullet-contact-added', self.doAdded) #self.accept('bullet-contact-destroyed', self.doRemoved) # Sphere (dynamic) shape = BulletSphereShape(0.6) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Sphere')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(-4, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Cone (dynamic) shape = BulletConeShape(0.6, 1.2, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cone')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(4, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Capsule (dynamic) shape = BulletCapsuleShape(0.5, 1.0, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Capsule')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(0, 4, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Cyliner (dynamic) shape = BulletCylinderShape(0.7, 1.5, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Cylinder')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(4, 4, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Convex (dynamic) shape = BulletConvexHullShape() shape.addPoint(Point3(1, 1, 2)) shape.addPoint(Point3(0, 0, 0)) shape.addPoint(Point3(2, 0, 0)) shape.addPoint(Point3(0, 2, 0)) shape.addPoint(Point3(2, 2, 0)) # Another way to create the convex hull shape: #shape = BulletConvexHullShape() #shape.addArray([ # Point3(1, 1, 2), # Point3(0, 0, 0), # Point3(2, 0, 0), # Point3(0, 2, 0), # Point3(2, 2, 0), #]) # Yet another way to create the convex hull shape: #geom = loader.loadModel('models/box.egg')\ # .findAllMatches('**/+GeomNode')\ # .getPath(0)\ # .node()\ # .getGeom(0) #shape = BulletConvexHullShape() #shape.addGeom(geom) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Convex')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(-4, 4, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Mesh (static) p0 = Point3(-10, -10, 0) p1 = Point3(-10, 10, 0) p2 = Point3(10, -10, 0) p3 = Point3(10, 10, 0) mesh = BulletTriangleMesh() mesh.addTriangle(p0, p1, p2) mesh.addTriangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) # Another way to create the triangle mesh shape: #geom = loader.loadModel('models/box.egg')\ # .findAllMatches('**/+GeomNode')\ # .getPath(0)\ # .node()\ # .getGeom(0) #mesh = BulletTriangleMesh() #mesh.addGeom(geom) #shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Mesh')) np.node().addShape(shape) np.setPos(0, 0, 0.1) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # MutiSphere points = [Point3(-1, 0, 0), Point3(0, 0, 0), Point3(1, 0, 0)] radii = [.4, .8, .6] shape = BulletMultiSphereShape(points, radii) np = self.worldNP.attachNewNode(BulletRigidBodyNode('MultiSphere')) np.node().setMass(1.0) np.node().addShape(shape) np.setPos(8, 0, 4) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node())
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, -4) 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 - From points/indices #import cube #points = [Point3(x,y,z) * 3 for x,y,z in cube.nodes] #indices = sum([list(x) for x in cube.elements], []) #node = BulletSoftBodyNode.makeTetMesh(info, points, indices, True) #node.setVolumeMass(300); #node.getShape(0).setMargin(0.01) #node.getMaterial(0).setLinearStiffness(0.8) #node.getCfg().setPositionsSolverIterations(1) #node.getCfg().clearAllCollisionFlags() #node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterSoftSoft, True) #node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterRigidSoft, True) #node.generateClusters(16) #softNP = self.worldNP.attachNewNode(node) #softNP.setPos(0, 0, 8) #softNP.setHpr(0, 0, 45) #self.world.attachSoftBody(node) # Softbody - From tetgen data ele = open('models/cube/cube.1.ele', 'r').read() face = open('models/cube/cube.1.face', 'r').read() node = open('models/cube/cube.1.node', 'r').read() node = BulletSoftBodyNode.makeTetMesh(info, ele, face, node) node.setName('Tetra') node.setVolumeMass(300) node.getShape(0).setMargin(0.01) node.getMaterial(0).setLinearStiffness(0.1) node.getCfg().setPositionsSolverIterations(1) node.getCfg().clearAllCollisionFlags() node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterSoftSoft, True) node.getCfg().setCollisionFlag(BulletSoftBodyConfig.CFClusterRigidSoft, True) node.generateClusters(6) softNP = self.worldNP.attachNewNode(node) softNP.setPos(0, 0, 8) softNP.setHpr(45, 0, 0) self.world.attachSoftBody(node) # Option 1: visNP = loader.loadModel('models/cube/cube.egg') visNP.reparentTo(softNP) geom = visNP \ .findAllMatches('**/+GeomNode').getPath(0).node() \ .modifyGeom(0) node.linkGeom(geom)
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 p0 = LPoint3(-20, -20, 0) p1 = LPoint3(-20, 20, 0) p2 = LPoint3(20, -20, 0) p3 = LPoint3(20, 20, 0) mesh = BulletTriangleMesh() mesh.add_triangle(p0, p1, p2) mesh.add_triangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Mesh')) np.node().add_shape(shape) np.set_pos(0, 0, -2) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Soft body world information info = self.world.get_world_info() info.set_air_density(1.2) info.set_water_density(0) info.set_water_offset(0) info.set_water_normal(LVector3(0, 0, 0)) # Softbody for i in range(50): p00 = LPoint3(-2, -2, 0) p10 = LPoint3(2, -2, 0) p01 = LPoint3(-2, 2, 0) p11 = LPoint3(2, 2, 0) node = BulletSoftBodyNode.make_patch(info, p00, p10, p01, p11, 6, 6, 0, True) node.generate_bending_constraints(2) node.get_cfg().set_lift_coefficient(0.004) node.get_cfg().set_dynamic_friction_coefficient(0.0003) node.get_cfg().set_aero_model( BulletSoftBodyConfig.AM_vertex_two_sided) node.set_total_mass(0.1) node.add_force(LVector3(0, 2, 0), 0) np = self.worldNP.attach_new_node(node) np.set_pos(self.LVector3_rand() * 10 + LVector3(0, 0, 20)) np.set_hpr(self.LVector3_rand() * 16) self.world.attach(node) fmt = GeomVertexFormat.get_v3n3t2() geom = BulletHelper.make_geom_from_faces(node, fmt, True) node.link_geom(geom) nodeV = GeomNode('') nodeV.add_geom(geom) npV = np.attach_new_node(nodeV) tex = loader.load_texture('models/panda.jpg') npV.set_texture(tex) BulletHelper.make_texcoords_for_patch(geom, 6, 6)
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 def makeSB(pos, hpr): import torus geom = torus.makeGeom() #geom = loader.loadModel('models/torus.egg') \ # .findAllMatches('**/+GeomNode').getPath(0).node() \ # .modifyGeom(0) geomNode = GeomNode('') geomNode.addGeom(geom) node = BulletSoftBodyNode.makeTriMesh(info, geom) node.linkGeom(geomNode.modifyGeom(0)) node.generateBendingConstraints(2) node.getCfg().setPositionsSolverIterations(2) node.getCfg().setCollisionFlag( BulletSoftBodyConfig.CFVertexFaceSoftSoft, True) node.randomizeConstraints() node.setTotalMass(50, True) softNP = self.worldNP.attachNewNode(node) softNP.setPos(pos) softNP.setHpr(hpr) self.world.attachSoftBody(node) geomNP = softNP.attachNewNode(geomNode) makeSB(Point3(-3, 0, 4), (0, 0, 0)) makeSB(Point3(0, 0, 4), (0, 90, 90)) makeSB(Point3(3, 0, 4), (0, 0, 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)
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()) # Ground shape = BulletPlaneShape(LVector3(0, 0, 1), 0) body = BulletRigidBodyNode('Ground') bodyNP = self.worldNP.attach_new_node(body) bodyNP.node().add_shape(shape) bodyNP.set_pos(0, 0, 0) bodyNP.set_collide_mask(BitMask32.all_on()) self.world.attach(bodyNP.node()) # Bowl visNP = loader.load_model('models/bowl.egg') geom = (visNP.findAllMatches('**/+GeomNode').get_path( 0).node().get_geom(0)) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=True) body = BulletRigidBodyNode('Bowl') bodyNP = self.worldNP.attach_new_node(body) bodyNP.node().add_shape(shape) bodyNP.node().set_mass(10.0) bodyNP.set_pos(0, 0, 0) bodyNP.set_collide_mask(BitMask32.all_on()) self.world.attach(bodyNP.node()) visNP.reparent_to(bodyNP) self.bowlNP = bodyNP self.bowlNP.set_scale(2) # Eggs self.eggNPs = [] for i in range(5): x = random.gauss(0, 0.1) y = random.gauss(0, 0.1) z = random.gauss(0, 0.1) + 1 h = random.random() * 360 p = random.random() * 360 r = random.random() * 360 visNP = loader.load_model('models/egg.egg') geom = (visNP.find_all_matches('**/+GeomNode').get_path( 0).node().get_geom(0)) shape = BulletConvexHullShape() shape.addGeom(geom) body = BulletRigidBodyNode('Egg-%i' % i) bodyNP = self.worldNP.attach_new_node(body) bodyNP.node().set_mass(1.0) bodyNP.node().add_shape(shape) bodyNP.node().set_deactivation_enabled(False) bodyNP.set_collide_mask(BitMask32.all_on()) bodyNP.set_pos_hpr(x, y, z, h, p, r) #bodyNP.set_scale(1.5) self.world.attach(bodyNP.node()) visNP.reparent_to(bodyNP) self.eggNPs.append(bodyNP)
def makeBulletCollFromGeoms(rootNode, exclusions=[], enableNow=True, world=None): """ Creates and attaches bullet triangle mesh nodes underneath each GeomNode of `rootNode`, which contains the same mesh as the Geoms. This can be expensive if the geometry contains lots of triangles or GeomNodes. """ if not world: world = base.physicsWorld # BulletRigidBodyNode -> triangle index -> surfaceprop # (it's so we know which surface we are walking on) result = {} for faceNp in rootNode.findAllMatches("**"): if faceNp.getName() in exclusions: continue if faceNp.node().getType() != GeomNode.getClassType(): continue # Create a separate list of geoms for each possible face type # ( a wall or floor ) type2geoms = {} for i in xrange(faceNp.node().getNumGeoms()): geom = faceNp.node().getGeom(i) state = faceNp.node().getGeomState(i) if not geom.getPrimitive(0).isIndexed(): continue if state.hasAttrib(BSPFaceAttrib.getClassSlot()): bca = state.getAttrib(BSPFaceAttrib.getClassSlot()) facetype = bca.getFaceType() else: facetype = BSPFaceAttrib.FACETYPE_WALL if not type2geoms.has_key(facetype): type2geoms[facetype] = [(geom, state)] else: type2geoms[facetype].append((geom, state)) # Now create a separate body node to group each face type, # and assign the correct bit for facetype, geoms in type2geoms.items(): data = {} numGeoms = 0 mesh = BulletTriangleMesh() for i in xrange(len(geoms)): geom, state = geoms[i] mesh.addGeom(geom, True) surfaceprop = "default" if state.hasAttrib(BSPMaterialAttrib.getClassSlot()): mat = state.getAttrib( BSPMaterialAttrib.getClassSlot()).getMaterial() if mat: surfaceprop = mat.getSurfaceProp() for j in xrange(geom.getNumPrimitives()): prim = geom.getPrimitive(j) prim = prim.decompose() tris = prim.getNumVertices() / 3 for tidx in xrange(tris): data[numGeoms] = surfaceprop numGeoms += 1 shape = BulletTriangleMeshShape(mesh, False) rbnode = BulletRigidBodyNode(faceNp.getName() + "_bullet_type" + str(facetype)) rbnode.setKinematic(True) rbnode.addShape(shape) rbnodeNp = NodePath(rbnode) rbnodeNp.reparentTo(faceNp) if facetype == BSPFaceAttrib.FACETYPE_WALL: rbnodeNp.setCollideMask(CIGlobals.WallGroup) elif facetype == BSPFaceAttrib.FACETYPE_FLOOR: rbnodeNp.setCollideMask(CIGlobals.FloorGroup) if enableNow: world.attachRigidBody(rbnode) result[rbnode] = data return result
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() ####### MV self.environ = loader.loadModel("world/world") self.environ.reparentTo(render) 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) #actor = Actor('world/world') mesh = BulletTriangleMesh() ###### create terrein colligion shape geomNodeCollection = self.environ.findAllMatches('**/+GeomNode') for nodePath in geomNodeCollection: #.asList(): geomNode = nodePath.node() print("here1") for i in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(i) print("here2") print(geom) mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=False) shape.set_margin(0.0) #print(geomNodeCollection) # for geom in actor.getGeomNode().get_geoms(): # mesh.addGeom(geom) # shape = BulletTriangleMeshShape(mesh, dynamic=False) #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, 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(50.0) np.node().addShape(shape) np.setPos(3, 0, 7) np.setH(0) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Character h = 1.75 w = 0.4 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.player = BulletCharacterControllerNode( shape, 0.4, 'Player') #MV was: BulletCharacterNode(shape, 0.4, 'Player') #self.player.setMass(20.0) self.player.setMaxSlope(70.0) self.player.setGravity(9.81) #self.player.setFrictionSlip(100.0) self.playerNP = self.worldNP.attachNewNode(self.player) #self.playerNP.setMass(20.0) self.playerNP.setPos(-2, 0, 10) self.playerNP.setH(-90) self.playerNP.setCollideMask(BitMask32.allOn()) #self.playerNP.flattenLight() self.world.attachCharacter(self.player) self.ralph = Actor("ralph/ralph", { "run": "ralph/ralph-run", "walk": "ralph/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(0.3048) self.ralph.setPos(0, 0, -1) self.ralph.setH(180) self.ralph.reparentTo(self.playerNP) ## Camera self.camera = base.cam base.disableMouse() self.camera.setPos(self.playerNP.getX(), self.playerNP.getY() + 10, 2) self.camera.lookAt(self.playerNP)
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.show_tight_bounds() #self.debugNP.show_bounds() self.world = BulletWorld() self.world.set_gravity(LVector3(0, 0, -9.81)) self.world.set_debug_node(self.debugNP.node()) # Ground p0 = LPoint3(-20, -20, 0) p1 = LPoint3(-20, 20, 0) p2 = LPoint3(20, -20, 0) p3 = LPoint3(20, 20, 0) mesh = BulletTriangleMesh() mesh.add_triangle(p0, p1, p2) mesh.add_triangle(p1, p2, p3) shape = BulletTriangleMeshShape(mesh, dynamic=False) np = self.worldNP.attach_new_node(BulletRigidBodyNode('Mesh')) np.node().add_shape(shape) np.set_pos(0, 0, -2) np.set_collide_mask(BitMask32.all_on()) self.world.attach(np.node()) # Stair origin = LPoint3(0, 0, 0) size = LVector3(2, 10, 1) shape = BulletBoxShape(size * 0.5) for i in range(10): pos = origin + size * i pos.setY(0) np = self.worldNP.attach_new_node( BulletRigidBodyNode('Stair{}'.format(i))) np.node().add_shape(shape) np.set_pos(pos) np.set_collide_mask(BitMask32.all_on()) npV = loader.load_model('models/box.egg') npV.reparent_to(np) npV.set_scale(size) self.world.attach(np.node()) # Soft body world information info = self.world.get_world_info() info.set_air_density(1.2) info.set_water_density(0) info.set_water_offset(0) info.set_water_normal(LVector3(0, 0, 0)) # Softbody center = LPoint3(0, 0, 0) radius = LVector3(1, 1, 1) * 1.5 node = BulletSoftBodyNode.make_ellipsoid(info, center, radius, 128) node.set_name('Ellipsoid') node.get_material(0).set_linear_stiffness(0.1) node.get_cfg().set_dynamic_friction_coefficient(1) node.get_cfg().set_damping_coefficient(0.001) node.get_cfg().set_pressure_coefficient(1500) node.set_total_mass(30, True) node.set_pose(True, False) np = self.worldNP.attach_new_node(node) np.set_pos(15, 0, 12) #np.setH(90.0) #np.show_bounds() #np.show_tight_bounds() self.world.attach(np.node()) geom = BulletHelper.make_geom_from_faces(node) node.link_geom(geom) nodeV = GeomNode('EllipsoidVisual') nodeV.add_geom(geom) npV = np.attach_new_node(nodeV)
def __addTriangleMesh(self, body, geom, pos=(0,0,0), hpr=(0,0,0), scale=(1,1,1), dynamic=True): mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=dynamic ) body.addShape( shape, TransformState.makePosHprScale(pos,hpr,scale) )
def __init__(self, objinit, cdtype="triangle", mass=.3, restitution=0, allowdeactivation=False, allowccd=True, friction=.2, dynamic=True, name="rbd"): """ :param objinit: could be itself (copy), or an instance of collision model :param type: triangle or convex :param mass: :param restitution: bounce parameter :param friction: :param dynamic: only applicable to triangle type, if an object does not move with force, it is not dynamic :param name: author: weiwei date: 20190626, 20201119 """ super().__init__(name) if isinstance(objinit, gm.GeometricModel): if objinit._objtrm is None: raise ValueError("Only applicable to models with a trimesh!") self.com = objinit.objtrm.center_mass self.setMass(mass) self.setRestitution(restitution) self.setFriction(friction) self.setLinearDamping(.3) self.setAngularDamping(.3) if allowdeactivation: self.setDeactivationEnabled(True) self.setLinearSleepThreshold(0.001) self.setAngularSleepThreshold(0.001) else: self.setDeactivationEnabled(False) if allowccd: # continuous collision detection self.setCcdMotionThreshold(1e-6) self.setCcdSweptSphereRadius(0.0005) gnd = objinit.objpdnp.getChild(0).find("+GeomNode") geom = copy.deepcopy(gnd.node().getGeom(0)) vdata = geom.modifyVertexData() vertrewritter = GeomVertexRewriter(vdata, 'vertex') while not vertrewritter.isAtEnd(): # shift local coordinate to geom to correctly update dynamic changes v = vertrewritter.getData3f() vertrewritter.setData3f(v[0] - self.com[0], v[1] - self.com[1], v[2] - self.com[2]) geomtf = gnd.getTransform() if cdtype is "triangle": geombmesh = BulletTriangleMesh() geombmesh.addGeom(geom) bulletshape = BulletTriangleMeshShape(geombmesh, dynamic=dynamic) bulletshape.setMargin(1e-6) self.addShape(bulletshape, geomtf) elif cdtype is "convex": bulletshape = BulletConvexHullShape() # TODO: compute a convex hull? bulletshape.addGeom(geom, geomtf) bulletshape.setMargin(1e-6) self.addShape(bulletshape, geomtf) else: raise NotImplementedError pdmat4 = geomtf.getMat() pdv3 = pdmat4.xformPoint(Vec3(self.com[0], self.com[1], self.com[2])) homomat = dh.pdmat4_to_npmat4(pdmat4) pos = dh.pdv3_to_npv3(pdv3) homomat[:3, 3] = pos # update center to com self.setTransform(TransformState.makeMat(dh.npmat4_to_pdmat4(homomat))) elif isinstance(objinit, BDBody): self.com = objinit.com.copy() self.setMass(objinit.getMass()) self.setRestitution(objinit.restitution) self.setFriction(objinit.friction) self.setLinearDamping(.3) self.setAngularDamping(.3) if allowdeactivation: self.setDeactivationEnabled(True) self.setLinearSleepThreshold(0.001) self.setAngularSleepThreshold(0.001) else: self.setDeactivationEnabled(False) if allowccd: self.setCcdMotionThreshold(1e-6) self.setCcdSweptSphereRadius(0.0005) self.setTransform(TransformState.makeMat(dh.npmat4_to_pdmat4(objinit.gethomomat()))) self.addShape(objinit.getShape(0), objinit.getShapeTransform(0))
def setup(self): self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() #self.debugNP.showTightBounds() #self.debugNP.showBounds() 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()) # Stair origin = Point3(0, 0, 0) size = Vec3(2, 10, 1) shape = BulletBoxShape(size * 0.5) for i in range(10): pos = origin + size * i pos.setY(0) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Stair%i' % i)) np.node().addShape(shape) np.setPos(pos) np.setCollideMask(BitMask32.allOn()) npV = loader.loadModel('models/box.egg') npV.reparentTo(np) npV.setScale(size) 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 center = Point3(0, 0, 0) radius = Vec3(1, 1, 1) * 1.5 node = BulletSoftBodyNode.makeEllipsoid(info, center, radius, 128) node.setName('Ellipsoid') node.getMaterial(0).setLinearStiffness(0.1) node.getCfg().setDynamicFrictionCoefficient(1) node.getCfg().setDampingCoefficient(0.001) node.getCfg().setPressureCoefficient(1500) node.setTotalMass(30, True) node.setPose(True, False) np = self.worldNP.attachNewNode(node) np.setPos(15, 0, 12) #np.setH(90.0) #np.showBounds() #np.showTightBounds() self.world.attachSoftBody(np.node()) geom = BulletHelper.makeGeomFromFaces(node) node.linkGeom(geom) nodeV = GeomNode('EllipsoidVisual') nodeV.addGeom(geom) npV = np.attachNewNode(nodeV)
def addQuad(self, p1, p2, p3, p4): mesh = BulletTriangleMesh() mesh.addTriangle(p1, p2, p3) mesh.addTriangle(p1, p3, p4) shape = BulletTriangleMeshShape(mesh, dynamic=False) self.node.addShape(shape)
def build_world(self, task): x = self.app.ref_node.getX() y = self.app.ref_node.getY() # TODO: Make it so we iterate over only a list of known grid coords to save computation # convert the players x and y coords so that we only consider chunks nearby # rel_x = int(x / self.cell_size) # rel_y = int(y / self.cell_size) # # self.nearby_cells = [ # [n_x, n_y] # for n_x in range(rel_x - self.view_distance_chunks, rel_x + self.view_distance_chunks) # for n_y in range(rel_y - self.view_distance_chunks, rel_y + self.view_distance_chunks) # if n_x >= 0 # if n_y >= 0 # ] # # if (rel_x, rel_y) not in self.seen_cells: # self.seen_cells.add((rel_x, rel_y)) # # for cell in self.nearby_cells: # # if cell not in list(self.cells.keys()): # self.cells[tuple(cell)] = {'visible': False, # 'node_path': None, # 'chunk_data': None, # 'bullet_mesh': None} # # for k in self.cells.keys(): # if k in self.nearby_cells: # self.cells[k]['visible'] = True # else: # self.cells[k]['visible'] = False for k, v in self.cells.items(): # k = tuple(cell_ind) # v = self.cells[k] min_px, min_py = k min_px, min_py = min_px * self.cell_size, min_py * self.cell_size max_px, max_py = min_px + self.cell_size, min_py + self.cell_size middle_x, middle_y = min_px + ((max_px - min_px) / 2), min_py + ( (max_py - min_py) / 2) if self.pythag((x, y), (middle_x, middle_y)) < self.view_distance: if v['visible']: # if we can already see it, do not do anything pass elif v['chunk_data'] is None: # if we've never seen this chunk before, then generate it for the first time chunk = Chunk(name=k, x_range=(min_px, max_px), y_range=(min_py, max_py), octaves=self.map_octaves, map_variation=self.map_height_variation, total_world_size=self.world_size, loader=self.app.loader) # attach all nodes for all different materials for material_id in v['node_path'].keys(): v['node_path'][ material_id] = self.app.render.attachNewNode( chunk.material_nodes[material_id]) v['node_path'][3].setTransparency( True) # make water transparent # v['node_path'] = self.app.render.attachNewNode(chunk.chunk_node) v['chunk_data'] = chunk v['bullet_mesh'] = self.app.render.attachNewNode( BulletRigidBodyNode('bullet-' + str(k))) v['bullet_mesh'].node().addShape( BulletTriangleMeshShape(chunk.bullet_mesh, dynamic=False)) self.app.bullet_world.attach(v['bullet_mesh'].node()) # v['node_path'].setTexture(self.test_texture) self.texture_materials(k) else: # if we already have chunk data, then re-attach the nodes to render for material_id in v['node_path'].keys(): if v['node_path'][material_id] is not None: v['node_path'][material_id].reparentTo( self.app.render) self.texture_materials(k) v['bullet_mesh'].reparentTo(self.app.render) self.app.bullet_world.attach(v['bullet_mesh'].node()) v['visible'] = True else: # if the cell if currently visible, rm from render graph if v['visible']: if v['node_path'] is not None: for material_id in block_id_mapping.keys(): v['node_path'][material_id].detachNode() v['bullet_mesh'].detachNode() self.app.bullet_world.remove(v['bullet_mesh'].node()) # set the flag to false so that we do not try to generate the mesh v['visible'] = False return task.cont
def setup(self): # Debug (useful to turn on for physics) self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug')) self.debugNP.hide() # Physics World self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Main Character self.player = Player() self.player.createPlayer(render, self.world) # Enemies self.createEnemies() # Music self.backgroundMusic = loader.loadSfx( '../sounds/elfman-piano-solo.ogg') self.backgroundMusic.setLoop(True) self.backgroundMusic.stop() self.backgroundMusic.setVolume( 0.9) # lower this when I add sound effects # Sound Effects self.collect = base.loader.loadSfx("../sounds/collect-sound.wav") self.collect.setVolume(1) self.damage = base.loader.loadSfx("../sounds/damage.wav") self.damage.setVolume(0.5) self.winner = base.loader.loadSfx("../sounds/win-yay.wav") self.winner.setVolume(1) self.dead = base.loader.loadSfx("../sounds/severe-damage.wav") self.dead.setVolume(1) # Level 1 Skybox self.skybox = loader.loadModel('../models/skybox_galaxy.egg') self.skybox.setScale(1000) # make big enough to cover whole terrain self.skybox.setBin('background', 1) self.skybox.setDepthWrite(0) self.skybox.setLightOff() self.skybox.reparentTo(render) # Lighting dLight = DirectionalLight("dLight") dLight.setColor(Vec4(0.8, 0.8, 0.5, 1)) dLight.setDirection(Vec3(-5, -5, -5)) dlnp = render.attachNewNode(dLight) dlnp.setHpr(0, 60, 0) render.setLight(dlnp) aLight = AmbientLight("aLight") aLight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(aLight) render.setLight(alnp) # Fog colour = (0.2, 0.2, 0.3) genfog = Fog("general fog") genfog.setColor(*colour) genfog.setExpDensity(0.003) render.setFog(genfog) base.setBackgroundColor(*colour) # Create wall (x, y, z, h) self.createWall(-30.2215, -6.2, -2, 45) self.createWall(-203, 555.8, -2, 70) #-----Level 1 Platforms----- # Platform to collect B self.createPlatform(72, 70.2927, -1) # Platforms to collect R self.createPlatform(211, 210, -1) self.createPlatform(225, 223, 2.7) # Platforms to collect E and A self.createPlatform(330, 462, -0.4) self.createPlatform(340, 471, 2.1) self.createPlatform(350, 480, 4) self.createPlatform(335, 483, 5) # Platforms to collect K self.createPlatform(184, 712, -1) self.createPlatform(208, 730, -1) self.createPlatform(207, 711, -1) self.createPlatform(186, 731, -1) #-----Level 2 Platforms----- # Moving platforms if self.movingPlatforms > 0: del self.movingPlatforms[:] self.createMovingPlatforms() # Create complex mesh for Track using BulletTriangleMeshShape mesh = BulletTriangleMesh() self.track = loader.loadModel("../models/mountain_valley_track.egg") self.track.flattenStrong() for geomNP in self.track.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.track) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) node = BulletRigidBodyNode('Track') node.setMass(0) node.addShape(shape) tracknn = render.attachNewNode(node) self.world.attachRigidBody(tracknn.node()) tracknn.setPos(27, -5, -2) self.track.reparentTo(tracknn)
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()) # Ground shape = BulletPlaneShape(Vec3(0, 0, 1), 0) body = BulletRigidBodyNode('Ground') bodyNP = self.worldNP.attachNewNode(body) bodyNP.node().addShape(shape) bodyNP.setPos(0, 0, 0) bodyNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(bodyNP.node()) # Bowl visNP = loader.loadModel('models/bowl.egg') geom = visNP.findAllMatches('**/+GeomNode').getPath(0).node().getGeom( 0) mesh = BulletTriangleMesh() mesh.addGeom(geom) shape = BulletTriangleMeshShape(mesh, dynamic=True) body = BulletRigidBodyNode('Bowl') bodyNP = self.worldNP.attachNewNode(body) bodyNP.node().addShape(shape) bodyNP.node().setMass(10.0) bodyNP.setPos(0, 0, 0) bodyNP.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(bodyNP.node()) visNP.reparentTo(bodyNP) self.bowlNP = bodyNP self.bowlNP.setScale(2) # Eggs self.eggNPs = [] for i in range(5): x = random.gauss(0, 0.1) y = random.gauss(0, 0.1) z = random.gauss(0, 0.1) + 1 h = random.random() * 360 p = random.random() * 360 r = random.random() * 360 visNP = loader.loadModel('models/egg.egg') geom = visNP.findAllMatches('**/+GeomNode').getPath( 0).node().getGeom(0) shape = BulletConvexHullShape() shape.addGeom(geom) body = BulletRigidBodyNode('Egg-%i' % i) bodyNP = self.worldNP.attachNewNode(body) bodyNP.node().setMass(1.0) bodyNP.node().addShape(shape) bodyNP.node().setDeactivationEnabled(False) bodyNP.setCollideMask(BitMask32.allOn()) bodyNP.setPosHpr(x, y, z, h, p, r) #bodyNP.setScale(1.5) self.world.attachRigidBody(bodyNP.node()) visNP.reparentTo(bodyNP) self.eggNPs.append(bodyNP)