def vec_to_hpr (v): q = Quat () q.setX (v.getX ()) q.setY (v.getY ()) q.setZ (v.getZ ()) q.setW (v.getW ()) return q.getHpr ()
def OnUpdate(self, task): # Position axes 30 pixels from top left corner self.axes.setPos(Vec3(30, 0, -30)) # Set rotation to inverse of camera rotation cameraQuat = Quat(self.getQuat()) cameraQuat.invertInPlace() self.axes.setQuat(cameraQuat)
def synchronize(self, _pandaCJoint, _smrJoint): smrQuaternion = _smrJoint.getRot() pandaQuaternion = Quat() pandaQuaternion.setI(smrQuaternion.getX()) pandaQuaternion.setJ(smrQuaternion.getY()) pandaQuaternion.setK(smrQuaternion.getZ()) pandaQuaternion.setR(smrQuaternion.getW()) if not (pandaQuaternion.isNan()): _pandaCJoint.setQuat(pandaQuaternion)
def synchronize(self, _pandaCJoint, _smrJoint): #_smrJoint.setRot(3.14/20.0,0,0); smrQuaternion = _smrJoint.getRot() pandaQuaternion = Quat() pandaQuaternion.setI(smrQuaternion.getX()) pandaQuaternion.setJ(smrQuaternion.getY()) pandaQuaternion.setK(smrQuaternion.getZ()) pandaQuaternion.setR(smrQuaternion.getW()) _pandaCJoint.setQuat(pandaQuaternion)
def AxesTask( self, task ): # Position axes 30 pixels from bottom left corner #posY = 100# self.GetSize()[1] self.axes.setPos( Vec3( 30, 0, -30 ) ) # Set rotation to inverse of camera rotation cameraQuat = Quat( self.getQuat() ) cameraQuat.invertInPlace() self.axes.setQuat( cameraQuat ) return Task.cont
def OnUpdate( self, task ): # Position axes 30 pixels from top left corner self.axes.setPos( Vec3( 30, 0, -30 ) ) # Set rotation to inverse of camera rotation cameraQuat = Quat( self.getQuat() ) cameraQuat.invertInPlace() self.axes.setQuat( cameraQuat )
def RotatePoint3(p, v1, v2): v1.normalize() v2.normalize() cross = v1.cross(v2) cross.normalize() if cross.length(): a = v1.angleDeg(v2) quat = Quat() quat.setFromAxisAngle(a, cross) p = quat.xform(p) return p
def updateStars(self, newCameraPos): # TODO: Add unit tests! self.stars.setPos(newCameraPos) cameraDeltaPos = tupleSegment(self.lastCameraPos, vec3ToTuple(newCameraPos)) xRotation = Quat() xRotation.setFromAxisAngle(cameraDeltaPos[0] * .1, Vec3(0, 1, 0)) yRotation = Quat() yRotation.setFromAxisAngle(-cameraDeltaPos[1] * .1, Vec3(1, 0, 0)) newRotation = xRotation.multiply(yRotation) self.starsRotation *= newRotation self.stars.setQuat(self.starsRotation)
def simulationTask(task): if vehicle != None and vehicle.chassiM != None: base.cam.lookAt(vehicle.chassiM.model) global text text.destroy() text = OnscreenText(text=('fps = ' + str(globalClock.getAverageFrameRate())), pos=(0, 0.9), scale=0.07) if (keylistener.space): vehicle.goUp() if (keylistener.i): vehicle.goForward() if (keylistener.k): vehicle.goBackwards() if (keylistener.j): vehicle.turnLeft() if (keylistener.l): vehicle.turnRight() space.autoCollide() world.quickStep(globalClock.getDt()) for np, body in objects: np.setPosQuat(render, body.getPosition(), Quat(body.getQuaternion())) contactgroup.empty() return task.cont
def placeBodies(self): for pair in self.odePandaRelationList: pandaNodePathGeom = pair[0] odeBody = pair[1] if pandaNodePathGeom: pandaNodePathGeom.setPos(odeBody.getPosition()) pandaNodePathGeom.setQuat(Quat(odeBody.getQuaternion()[0], odeBody.getQuaternion()[1], odeBody.getQuaternion()[2], odeBody.getQuaternion()[3]))
def updatePlayer(self): ''' Needs to get executed every Ode-Step ''' self._vehicle.model.setPosQuat( render, self._vehicle.physics_model.getPosition(), Quat(self._vehicle.physics_model.getQuaternion() )) #set new position self._camera.updateCam()
def _move (self, dt, rd): if self._at_rest: return pos = self._pos quat = self._quat vel = self._vel angvel = self._angvel gracc = self.world.gravacc pos1 = pos + vel * dt + gracc * (0.5 * dt**2) vel1 = vel + gracc * dt touch = self.world.below_surface(pos, elev=self._fix_elev) if touch: gpos = self.world.intersect_surface(pos, pos1, elev=self._fix_elev) gnorm = vtof(self.world.elevation(gpos, wnorm=True)[1]) pos1 -= gnorm * (pos1 - gpos).dot(gnorm) * 2 vel1_el = unitv(pos1 - pos) * vel1.length() vel1_el_n = gnorm * vel1_el.dot(gnorm) vel1_el_t = vel1_el - vel1_el_n vel1 = vel1_el_n * self._norm_rest_fac + vel1_el_t * self._tang_rest_fac self._at_rest = (vel1.length() < 0.5) if self._at_rest: pos1 = gpos vel1 = Vec3(0.0, 0.0, 0.0) self.node.setPos(pos1) raxis = unitv(self._angvel) if raxis.length() == 0.0: raxis = Vec3(0.0, 0.0, 1.0) absangvel1 = self._angvel.length() if touch: absangvel1 *= self._tumble_rest_fac dquat = Quat() dquat.setFromAxisAngleRad(absangvel1 * dt, raxis) quat1 = quat * dquat angvel1 = raxis * absangvel1 self.node.setQuat(quat1) self._pos = pos1 self._quat = quat1 self._vel = vel1 self._angvel = angvel1
def jump_to (self, pos=None, hpr=None, speed=None): if pos is None: pos = self.pos(refbody=self.parent) if hpr is None: hpr = self.hpr(refbody=self.parent) if speed is None: speed = self.speed(refbody=self.parent) self.node.setPos(pos) self.node.setHpr(hpr) q = Quat() q.setHpr(hpr) self._vel = Vec3(q.xform(Vec3(0, speed, 0))) self._acc = Vec3() self._angvel = Vec3() self._angacc = Vec3() self._prev_vel = Vec3(self._vel) self._prev_angvel = Vec3(self._angvel)
def __call__(self, task): for moment in self.dataStream: for prevSegment, segment, controlJoint, jointName, endJointName in zip(self.prevFobSegments, segmentsFromMoment(moment), self.controlJoints[:-1], self.joints[:-1], self.joints[1:]): while self.paused: return Task.cont self.prevFobSegments.pop(0) exposedJoint = self.actor.exposeJoint(None, "modelRoot", jointName) exposedEndJoint = self.actor.exposeJoint(None, "modelRoot", endJointName) prevJointSegment = Vec3(exposedEndJoint.getNetTransform().getPos()) - Vec3(exposedJoint.getNetTransform().getPos()) prevSegment.normalize() segment.normalize() prevJointSegment.normalize() axis = prevJointSegment.cross(segment) axis.normalize() import logging # logging.debug("moment: %s" % (moment,)) # logging.debug("segment: %s, prevSegment: %s, prevJointSegment: %s" % (segment, prevSegment, prevJointSegment)) # logging.debug("prevJointSegment: %s" % (prevJointSegment,)) # logging.debug("axis: %s" % (axis,)) angle = prevSegment.angleRad(segment) quat = Quat() quat.setFromAxisAngleRad(angle, axis) controlJoint.setQuat(controlJoint, quat) self.prevFobSegments.append(segment) if not self.stopped: return Task.cont else: return Task.done return Task.done
def constrainQuat(self): """keep the object rotating in the correct plane""" #FIXME is there a better way than fixing at every instant? if not self.rot: self.body.setQuaternion(Quat.identQuat()) return q = self.body.getQuaternion() q[1] = 0 q[2] = 0 q.normalize() self.body.setQuaternion(Quat(q))
def simulationTask(task): global groundImgChanged space.autoCollide() # Setup the contact joints # Step the simulation and set the new positions world.quickStep(globalClock.getDt()) for np, geom, sound in balls: if not np.isEmpty(): np.setPosQuat(render, geom.getBody().getPosition(), Quat(geom.getBody().getQuaternion())) contactgroup.empty() # Clear the contact joints # Load the image into the texture if groundImgChanged: groundTexture.load(groundImage) groundImgChanged = False return task.cont
class EntitySnapshot(net.Object): def __init__(self): self.pos = Vec3() self.quat = Quat() self.time = 0 self.empty = True def takeSnapshot(self, entity): self.pos = entity.getPosition() self.quat = Quat(entity.getQuaternion()) self.time = engine.clock.time self.empty = False def addTo(self, datagram): pos = HighResVec3(self.pos) quat = StandardQuat(self.quat) pos.addTo(datagram) quat.addTo(datagram) @staticmethod def getFrom(iterator): es = EntitySnapshot() es.pos = HighResVec3.getFrom(iterator) es.quat = StandardQuat.getFrom(iterator) es.time = engine.clock.time es.empty = False return es def commitTo(self, entity): entity.setQuaternion(self.quat) entity.setPosition(self.pos) def lerp(self, snapshot, scale): result = EntitySnapshot() result.pos = self.pos + ((snapshot.pos - self.pos) * scale) result.quat = self.quat + ((snapshot.quat - self.quat) * scale) result.empty = False return result def setFrom(self, snapshot): self.pos = Vec3(snapshot.pos) self.quat = Quat(snapshot.quat) self.time = engine.clock.time self.empty = snapshot.empty def almostEquals(self, snapshot): return self.quat.almostEqual(snapshot.quat, 2) and self.pos.almostEqual(snapshot.pos, 0.2)
def placeBodies(self): """Make the nodePaths match up to the physics bodies.""" # lets see if a sphere can simulate a tire by just taking out P and R for pair in self.odePandaRelationList: pandaNodePathGeom = pair[0] odeBody = pair[1] if pandaNodePathGeom: pandaNodePathGeom.setPos(odeBody.getPosition()) # rotation = (odeBody.getRotation() * (180.0/math.pi)) pandaNodePathGeom.setQuat( Quat(odeBody.getQuaternion()[0], odeBody.getQuaternion()[1], odeBody.getQuaternion()[2], odeBody.getQuaternion()[3])) pandaNodePathGeom.setP(0) pandaNodePathGeom.setR(0) newQuat = pandaNodePathGeom.getQuat() odeBody.setQuaternion(newQuat)
def alignBodyTo2d(self): body = self.ballBody # Constrain position of the body oldPos = body.getPosition() newPos = oldPos newPos[0] = 0 newPos[1] = oldPos[1] newPos[2] = oldPos[2] # Constrain quaternion of the body oldQuat = body.getQuaternion() newQuat = oldQuat newQuat[0] = oldQuat[0] newQuat[1] = oldQuat[1] newQuat[2] = 0 newQuat[3] = 0 # Set new position and quaternion of the body body.setPosition(newPos) body.setQuaternion(Quat(newQuat))
def updateStars(self, newCameraPos): # TODO: Add unit tests! self.stars.setPos(newCameraPos) cameraDeltaPos = tupleSegment( self.lastCameraPos, vec3ToTuple( newCameraPos ) ) xRotation = Quat() xRotation.setFromAxisAngle( cameraDeltaPos[0] * .1, Vec3( 0, 1, 0 ) ) yRotation = Quat() yRotation.setFromAxisAngle( -cameraDeltaPos[1] * .1, Vec3( 1, 0, 0 ) ) newRotation = xRotation.multiply( yRotation ) self.starsRotation *= newRotation self.stars.setQuat( self.starsRotation )
def __init__ (self, world, name, side, texture=None, pos=None, hpr=None, speed=None, sink=None, damage=None): if pos is None: pos = Point3() if hpr is None: hpr = Vec3() if sink is None: sink = 0.0 if speed is None: speed = 0.0 pos = Point3(pos[0], pos[1], 0.0) self.texture = texture if isinstance(self.modelpath, basestring): shdmodind = 0 elif self.modelpath: shdmodind = min(len(self.modelpath) - 1, 1) else: shdmodind = None Body.__init__(self, world=world, family=self.family, species=self.species, hitforce=(self.strength * 0.1), name=name, side=side, modeldata=AutoProps( path=self.modelpath, shadowpath=self.shdmodelpath, texture=texture, normalmap=self.normalmap, glowmap=self.glowmap, glossmap=self.glossmap, scale=self.modelscale, offset=self.modeloffset, rot=self.modelrot), hitboxdata=self.hitboxdata, hitlight=AutoProps(), hitdebris=self.hitdebris, hitflash=self.hitflash, amblit=True, dirlit=True, pntlit=2, fogblend=True, obright=True, shdshow=True, shdmodind=shdmodind, ltrefl=(self.glossmap is not None), pos=pos, hpr=hpr, vel=speed) self.maxbracc = self.maxspeed / 4.0 # Detect shotdown maps. self._shotdown_texture = self.texture self._shotdown_normalmap = self.normalmap self._shotdown_glowmap = self.glowmap if not isinstance(self.glowmap, Vec4) else None self._shotdown_glossmap = self.glossmap self._shotdown_change_maps = False if isinstance(self.modelpath, basestring): ref_modelpath = self.modelpath elif isinstance(self.modelpath, (tuple, list)): ref_modelpath = self.modelpath[0] else: ref_modelpath = None if ref_modelpath: ref_modeldir = path_dirname(ref_modelpath) ref_modelname = path_basename(ref_modeldir) if self.texture: test_path = self.texture.replace("_tex.", "_burn.") if path_exists("data", test_path): self._shotdown_texture = test_path self._shotdown_change_maps = True if self.normalmap: test_path = join_path(ref_modeldir, ref_modelname + "_burn_nm.png") if path_exists("data", test_path): self._shotdown_normalmap = test_path self._shotdown_change_maps = True if self.glowmap and not isinstance(self.glowmap, Vec4): test_path = join_path(ref_modeldir, ref_modelname + "_burn_gw.png") if path_exists("data", test_path): self._shotdown_glowmap = test_path self._shotdown_change_maps = True if self.glossmap: test_path = join_path(ref_modeldir, ref_modelname + "_burn_gls.png") if path_exists("data", test_path): self._shotdown_glossmap = test_path self._shotdown_change_maps = True # Prepare shotdown model. self._shotdown_modelnode = None if self.sdmodelpath: modelchain = self.sdmodelpath if isinstance(modelchain, basestring): modelchain = [modelchain] ret = load_model_lod_chain( world.vfov, modelchain, texture=self._shotdown_texture, normalmap=self._shotdown_normalmap, glowmap=self._shotdown_glowmap, glossmap=self._shotdown_glossmap, shadowmap=self.world.shadow_texture, scale=self.modelscale, pos=self.modeloffset, hpr=self.modelrot) lnode, models, fardists = ret[:3] lnode.setShader(self.shader) self._shotdown_modelnode = lnode self._shotdown_models = models self._shotdown_fardists = fardists for mlevel, model in enumerate(models): model.setTwoSided(True) # Locally reposition and reorient vehicle such as that # all ground contact points have local z-coordinates zero. # Do this by first rotating ground contact plane around axis # normal to z-axis and to initial ground contact plane normal, # until the ground contact plane normal becomes the z-axis, # then shift ground contact plane along z-axis to become xy-plane. if len(self.groundcontact) != 3: raise StandardError( "There must be exactly 3 ground contact points.") self._platform = self.node.attachNewNode("vehicle-platform") gcf, gcl, gcr = self.groundcontact gcn = unitv((gcl - gcf).cross(gcr - gcf)) zdir = Vec3(0, 0, 1) graxis = gcn.cross(zdir) if graxis.normalize(): gang = gcn.signedAngleRad(zdir, graxis) q = Quat() q.setFromAxisAngleRad(gang, graxis) self._platform.setQuat(q) self._modgndcnts = [] for rgcp in self.groundcontact: rgcp1 = self.node.getRelativePoint(self._platform, rgcp) goffz = rgcp1[2] # equal by construction for all points rgcp1[2] = 0.0 self._modgndcnts.append(rgcp1) self._platform.setPos(gcn * -goffz) self.modelnode.reparentTo(self._platform) # Fix vehicle to the ground, according to contact points. self.sink = sink self._gyro = world.node.attachNewNode("vehicle-gyro-%s" % name) gfix = Vehicle._fix_to_ground(self.world, self._gyro, self._modgndcnts, self.sink, ptod(pos), vtod(hpr)) pos1, hpr1 = gfix[:2] self.node.setPos(ptof(pos1)) self.node.setHpr(vtof(hpr1)) self._prev_gfix = gfix tvelg = speed self._prev_dyn = (tvelg,) width, length, height = self.bbox self.size = (length + width + height) / 3 self._length = length self._size_xy = min(width, length) # Models for detecting moving parts. mvpt_models = list(self.models) if base.with_world_shadows and self.shadow_node is not None: mvpt_models += [self.shadow_node] if self.sdmodelpath: mvpt_models += self._shotdown_models # Detect turning axles. self._axles = [] for model in mvpt_models: axlends = model.findAllMatches("**/axle*") for axlend in axlends: c1, c2 = axlend.getTightBounds() dx, dy, dz = c2 - c1 wheelrad = 0.5 * (abs(dy) + abs(dz)) / 2 self._axles.append((axlend, wheelrad)) # Detect turning tracks. # Use ambient light as shader input for uv-scroll. self._tracks = [] for model in mvpt_models: tracknds = model.findAllMatches("**/track*") for it, tracknd in enumerate(tracknds): spdfac = self.trkspdfac[it] kwargs = dict(self.shader_kwargs) kwargs["uvscrn"] = "INuvscr" shader = make_shader(**kwargs) tracknd.setShader(shader) uvscr = AmbientLight(name=("uvscr-track-%d" % it)) tracknd.setShaderInput(kwargs["uvscrn"], NodePath(uvscr)) uvoff = Vec4() uvscr.setColor(uvoff) self._tracks.append((tracknd, spdfac, uvoff, uvscr)) # Detect lights. # Set up turning on/off through glow factor. self._lights = [] for model in mvpt_models: for lnd in model.findAllMatches("**/lights"): kwargs = dict(self.shader_kwargs) kwargs["glow"] = rgba(255, 255, 255, 1.0) kwargs["glowfacn"] = self.world.shdinp.glowfacn shader = make_shader(**kwargs) lnd.setShader(shader) self._lights.append(lnd) self.set_lights(on=False) if self.engsoundname: self.engine_sound = Sound3D( path=("audio/sounds/%s.ogg" % self.engsoundname), parent=self, maxdist=3000, limnum="hum", volume=self.engmaxvol, loop=True, fadetime=2.5) self.engine_sound.play() else: self.engine_sound = None self.damage = damage or 0.0 self.damage_trails = [] self.launchers = [] self.turrets = [] self.decoys = [] self._prev_path = None self._path_pos = 0.0 self._throttle = 0.0 # Control inputs. self.zero_inputs() # Autopilot constants. self._ap_adjperiod = 1.03 self._ap_adjpfloat = 0.2 # Autopilot state. self.zero_ap() # Route settings. self._route_current_point = None self._route_points = [] self._route_point_inc = 1 self._route_patrol = False self._route_circle = False self._state_info_text = None self._wait_time_state_info = 0.0 base.taskMgr.add(self._loop, "vehicle-loop-%s" % self.name)
def _move (self, dt, rd): pos = self._pos quat = self._quat fvel = self._fvel tvel = self._tvel termspeed = self._termspeed gracc = self.world.gravacc fspeed = fvel.length() fdir = unitv(fvel) absdracc = self.world.absgravacc * (fspeed**2 / termspeed**2) if fspeed - absdracc * dt < 0.0: absdracc = (fspeed / dt) * 0.5 dracc = fdir * -absdracc facc = gracc + dracc #facc = Vec3() dfpos = fvel * dt + facc * (0.5 * dt**2) fvel1 = fvel + facc * dt rollspeed = self._rollspeed rollrad = self._rollrad if rollspeed != 0.0 and rollrad != 0.0: rollspeed1 = rollspeed * (1.0 - rd)**2 rollrad1 = rollrad * (1.0 - rd)**2 tdir = unitv(tvel) * (sign(rollspeed * rollrad) or 1) fdir1 = unitv(fvel1) dsroll = rollspeed1 * dt dtquat = Quat() dtquat.setFromAxisAngleRad(dsroll, fdir) tdir1p = Vec3(dtquat.xform(tdir)) tdir1 = unitv(fdir1.cross(tdir1p).cross(fdir1)) tspeed1 = rollspeed1 * rollrad1 dtpos = tvel * dt tvel1 = tdir1 * tspeed1 else: dtpos = Vec3() dtquat = Quat() tvel1 = Vec3() pos1 = pos + dfpos + dtpos self.node.setPos(pos1) fdir1 = unitv(fvel1) paxis = fdir.cross(fdir1) if paxis.length() > 1e-5: paxis.normalize() dspitch = fdir.signedAngleRad(fdir1, paxis) else: paxis = quat.getRight() paxis.normalize() dspitch = 0.0 dfquat = Quat() dfquat.setFromAxisAngleRad(dspitch, paxis) quat1 = quat * dfquat * dtquat self.node.setQuat(quat1) self._pos = pos1 self._quat = quat1 self._fvel = fvel1 self._tvel = tvel1
def __init__ (self, body, handle, duration, offpos=None, offdir=None, offspeed=0.0, traildurfac=1.0, traillifespan=0.0, trailthickness=0.0, trailendthfac=4.0, trailspacing=1.0, trailtcol=0.0, trailfire=False, keeptogether=False, texture=None): if isinstance(body, tuple): model, world = body models = [model] shadow_model = None body = None self.world = world else: self.world = body.world models = list(body.models) if base.with_world_shadows and body.shadow_node is not None: shadow_model = body.shadow_node else: shadow_model = None self.node = self.world.node.attachNewNode("breakup-part") if not keeptogether: shader = make_shader(ambln=self.world.shdinp.ambln, dirlns=self.world.shdinp.dirlns) self.node.setShader(shader) if texture is not None: set_texture(self.node, texture) if isinstance(handle, basestring): handles = [handle] else: handles = handle offset = offpos pos = None quat = None self._together_nodes = [] for model in models: if model is None: continue for handle in handles: nd = model.find("**/%s" % handle) if not nd.isEmpty(): if offset is None: if body is not None: offset = nd.getPos(body.node) else: offset = nd.getPos(self.world.node) if pos is None: # Must be done here because of wrtReparentTo below. if body is not None: pos = body.pos(offset=offset) quat = body.quat() else: pos = self.world.node.getRelativePoint(model, offset) quat = model.getQuat(self.world.node) self.node.setPos(pos) self.node.setQuat(quat) if offdir is None: offdir = unitv(offset) if not keeptogether: nd.wrtReparentTo(self.node) else: offset2 = nd.getPos(self.node) self._together_nodes.append((nd, offset2)) if pos is None: if offpos is not None: pos = offpos self.node.setPos(pos) else: raise StandardError( "No subnodes found for given handle, " "and no initial position given.") if shadow_model is not None: for handle in handles: nd = shadow_model.find("**/%s" % handle) if not nd.isEmpty(): nd.removeNode() if body is not None: odir = self.world.node.getRelativeVector(body.node, offdir) bvel = body.vel() elif models[0] is not None: odir = self.world.node.getRelativeVector(models[0], offdir) bvel = Vec3(0.0, 0.0, 0.0) else: odir = offdir bvel = Vec3(0.0, 0.0, 0.0) vel = bvel + odir * offspeed if quat is None: quat = Quat() quat.setHpr(vectohpr(vel)) self._pos0 = pos self._vel0 = vel self._quat0 = quat self._duration = duration self._time = 0.0 self._trails = [] if traildurfac > 0.0 and traillifespan > 0.0 and trailthickness > 0.0: self._start_trail(traildurfac, traillifespan, trailthickness, trailendthfac, trailspacing, trailtcol, trailfire) self.alive = True # Before general loops, e.g. to have updated position in effect loops. base.taskMgr.add(self._loop, "breakup-part-loop", sort=-1)
def quat(self): """ return the current quaternion representation of the attitude """ return Quat(self.ode_body.getQuaternion())
def updatePosFromPhysics(self): if self.body != None: self.node.setPosQuat(render, self.body.getPosition(), Quat(self.body.getQuaternion()))
def vec_to_hpr(v): q = Quat() q.setX(v.getX()) q.setY(v.getY()) q.setZ(v.getZ()) q.setW(v.getW()) return q.getHpr()
def hpr2quat(h,p,r): q = Quat() q.setHpr((h,p,r)) return q
def takeSnapshot(self, entity): self.pos = entity.getPosition() self.quat = Quat(entity.getQuaternion()) self.time = engine.clock.time self.empty = False
def __init__(self): self.pos = Vec3() self.quat = Quat() self.time = 0 self.empty = True
def getFrom(iterator): return Quat(net.StandardFloat.getFrom(iterator), net.StandardFloat.getFrom(iterator), net.StandardFloat.getFrom(iterator), net.StandardFloat.getFrom(iterator))
def updateModelNode(self): ''' Update objects after one physics iteration ''' now = globalClock.getLongTime() body = self.ballBody g = self.world.getGravity() if self.limitedYMovement: if body.getPosition().getY() > self.limitedYCoords[1]: self.ballBody.setLinearVel(Vec3(0, -10, 0)) if body.getPosition().getY() < self.limitedYCoords[0]: self.ballBody.setLinearVel(Vec3(0, 10, 0)) if self.limitedZMovement: if body.getPosition().getZ() > self.limitedZCoords[1]: messenger.send(EventType.RESTART) return if body.getPosition().getZ() < self.limitedZCoords[0]: messenger.send(EventType.RESTART) return if Ball.MOVEMENT_DEBUG and now - self.lastDrawTime2 > 0.2: v = body.getLinearVel() v2 = self.perpendicularUnitVec3WithFixedX(v) self.lines.reset() self.lines3.reset() x = body.getPosition().getX( ) + 1.2 # This will bring the line in front of the ball y = body.getPosition().getY() z = body.getPosition().getZ() self.lines.drawLines([((x, y, z), (x + v.getX(), y + v.getY(), z + v.getZ()))]) self.lines3.drawLines([((x, y, z), (x + v2.getX(), y + v2.getY(), z + v2.getZ()))]) self.lines.create() self.lines3.create() self.lastDrawTime2 = 0.0 ''' Can move better when on (touching) something, moving in the air is harder ''' divisor = 3.5 if self.isColliding() and self.lastCollisionIsGround: divisor = 1.0 if self.moveLeft or self.moveRight: factor = 1.0 if self.moveLeft: factor = -1.0 # Limit speed to some constant v3 = self.perpendicularUnitVec3WithFixedX(g) v3 *= factor * Ball.FORCE / divisor lv = self.ballBody.getLinearVel() lv.setX(0.0) lv.setZ(0.0) if self.haveRoughlySameDirection( lv, v3) and abs(lv.length()) > self.MAX_MOVEMENT_SPEED: factor = 0.0 v3 = self.perpendicularUnitVec3WithFixedX(g) v3 *= factor * Ball.FORCE / divisor self.ballBody.setForce(y=v3.getY(), x=v3.getX(), z=v3.getZ()) v3 = self.perpendicularUnitVec3WithFixedX(g) v3 *= factor * Ball.TORQUE / divisor self.ballBody.setTorque(y=v3.getY(), x=v3.getX(), z=v3.getX()) ''' This is still really crappy, will revise later ''' if self.jumping == True: g = -g g /= g.length() if Ball.STATIC_JUMP: g *= Ball.STATIC_JUMP_FORCE self.ballBody.setForce(y=g.getY(), x=g.getX(), z=g.getZ()) self.jumping = False else: elapsed = now - self.jumpStarted if elapsed > 0.0 and elapsed < Ball.MAX_JUMP_REACH_TIME: g *= Ball.JUMP_FORCE self.ballBody.setForce(y=g.getY(), x=g.getX(), z=g.getZ()) elif elapsed > Ball.MAX_JUMP_REACH_TIME: self.jumping = False # Keep the body in 2d position self.alignBodyTo2d() # Set the new position self.modelNode.setPos(render, self.ballBody.getPosition()) self.modelNode.setQuat(render, Quat(self.ballBody.getQuaternion()))
def hpr_to_quat(hpr): q = Quat() q.setHpr(hpr) return q
def __init__ (self, world, family, species, hitforce, name, side, mass=None, pos=Point3(), hpr=Vec3(), vel=Vec3(), angvel=Vec3(), acc=Vec3(), angacc=Vec3(), modeldata=None, hitboxdata=[], hitboxcritdata=[], hitinto=True, hitfrom=True, sensordata=None, center=None, bbox=None, bboxcenter=None, hitlight=None, hitdebris=None, hitflash=None, passhitfx=False, amblit=False, dirlit=False, pntlit=0, fogblend=False, obright=False, ltrefl=False, shdshow=False, shdmodind=None, parent=None): self.alive = True self.world = world self.family = family self.species = species self.name = name self.side = side self.parent = parent or world self.mass = mass self.hitforce = hitforce self.hitlight = hitlight self.hitdebris = hitdebris self.hitflash = hitflash self.passhitfx = passhitfx self.racc = Vec3() self.aacc = Vec3() self.rangacc = Vec3() self.aangacc = Vec3() if isinstance(vel, (float, int)): q = Quat() q.setHpr(hpr) vel = q.xform(Vec3(0, vel, 0)) self._acc = Vec3(acc) self._angacc = Vec3(angacc) self._vel = Vec3(vel) self._prev_vel = Vec3(vel) self._angvel = Vec3(angvel) self._prev_angvel = Vec3(angvel) self.birth_time = world.time self.initiator = None arg_bbox = bbox arg_bboxcenter = bboxcenter self.node = self.parent.node.attachNewNode(self.name) if modeldata and modeldata.path: if ltrefl: glossmap = modeldata.glossmap if not glossmap: glossmap = "images/_glossmap_none.png" else: glossmap = None if isinstance(modeldata.glowmap, Vec4): glowcol = modeldata.glowmap glowmap = None else: glowcol = None glowmap = modeldata.glowmap if modeldata.clamp is not None: clamp = modeldata.clamp else: clamp = True shadowmap = base.world_shadow_texture if shdshow else None if isinstance(modeldata.path, (tuple, list)): if (len(modeldata.path) == 2 and isinstance(modeldata.path[0], NodePath) and isinstance(modeldata.path[1], str)): pnode, tname = modeldata.path ret = extract_model_lod_chain(pnode, tname, texture=modeldata.texture, normalmap=modeldata.normalmap, glowmap=glowmap, glossmap=glossmap, shadowmap=shadowmap, clamp=clamp) lnode, models, fardists, bbox, bcen, ppos, phpr = ret if pos is None: pos = ppos if hpr is None: hpr = phpr for model in models: model.setPos(Point3()) model.setHpr(Vec3()) else: ret = load_model_lod_chain( world.vfov, modeldata.path, texture=modeldata.texture, normalmap=modeldata.normalmap, glowmap=glowmap, glossmap=glossmap, shadowmap=shadowmap, clamp=clamp, scale=modeldata.scale, pos=modeldata.offset, hpr=modeldata.rot) lnode, models, fardists, bbox, bcen = ret self.modelnode = lnode self.models = models self.fardists = fardists self.bbox = bbox self.bboxcenter = bcen lnode.reparentTo(self.node) else: model = load_model( modeldata.path, texture=modeldata.texture, normalmap=modeldata.normalmap, glowmap=glowmap, glossmap=glossmap, shadowmap=shadowmap, clamp=clamp, scale=modeldata.scale, pos=modeldata.offset, hpr=modeldata.rot) self.modelnode = model self.models = [model] self.fardists = [-1.0] model.reparentTo(self.node) if not modeldata.nobbox: bmin, bmax = model.getTightBounds() self.bbox = bmax - bmin self.bboxcenter = (bmin + bmax) * 0.5 else: self.bbox = Vec3() self.bboxcenter = Vec3() else: self.modelnode = None self.models = [] self.fardists = [] self.bbox = Vec3() self.bboxcenter = Vec3() if arg_bbox is not None: self.bbox = arg_bbox if arg_bboxcenter is not None: self.bboxcenter = arg_bboxcenter else: self.bboxcenter = Vec3() elif arg_bboxcenter is not None: self.bboxcenter = arg_bboxcenter self.update_bbox(bbox=self.bbox, bboxcenter=self.bboxcenter) self.node.setPos(pos) self.node.setHpr(hpr) self.hitboxes = [] self.set_hitboxes(hitboxdata, hitboxcritdata, hitinto, hitfrom) #for hbx in self.hitboxes: #hbx.cnode.show() self.inert_collide = False self.hits_critical = True if center is not None: self.center = center elif self.hitboxes: self.center = Point3() volume = 0.0 for hbx in self.hitboxes: self.center += hbx.center * hbx.volume volume += hbx.volume self.center /= volume else: self.center = self.bboxcenter if self.hitlight: self._init_hitlight() if self.hitdebris: self._init_hitdebris() if self.hitflash: self._init_hitflash() # Before shader is set. if base.with_world_shadows: if modeldata and modeldata.shadowpath: model = load_model( modeldata.shadowpath, scale=modeldata.scale, pos=modeldata.offset, hpr=modeldata.rot) model.reparentTo(world.shadow_node) self.shadow_node = model elif self.models and shdmodind is not None: model = self.models[shdmodind] self.shadow_node = model.copyTo(world.shadow_node) else: self.shadow_node = None if self.models: shdinp = world.shdinp ambln = shdinp.ambln if amblit else None dirlns = shdinp.dirlns if dirlit else [] #pntlit = 0 pntlns = shdinp.pntlns[:pntlit] fogn = shdinp.fogn if fogblend else None camn = shdinp.camn pntobrn = shdinp.pntobrn if obright else None normal = modeldata.normalmap is not None gloss = ltrefl glow = glowcol if glowcol is not None else (glowmap is not None) shadowrefn = shdinp.shadowrefn if shdshow else None shadowdirlin = shdinp.shadowdirlin if shdshow else None shadowblendn = shdinp.shadowblendn if shdshow else None shadowpush = 0.003 if shdshow else None shadowblur = SHADOWBLUR.NONE if shdshow else None showas = False #showas = "%s-shader" % (self.family) ret = make_shader( ambln=ambln, dirlns=dirlns, pntlns=pntlns, fogn=fogn, camn=camn, pntobrn=pntobrn, normal=normal, gloss=gloss, glow=glow, shadowrefn=shadowrefn, shadowdirlin=shadowdirlin, shadowblendn=shadowblendn, shadowpush=shadowpush, shadowblur=shadowblur, showas=showas, getargs=True) self.shader, self.shader_kwargs = ret self.modelnode.setShader(self.shader) self.pntlit = pntlit if sensordata is not None: self.sensorpack = SensorPack(parent=self, scanperiod=sensordata.scanperiod, relspfluct=sensordata.relspfluct, maxtracked=sensordata.maxtracked) else: self.sensorpack = None self.shotdown = False self.retreating = False self.outofbattle = False self.controlout = False self._last_collide_body = None self._recorded_as_kill = False if not base.with_sound_doppler: self.ignore_flyby = 0 world.register_body(self) base.taskMgr.add(self._loop_fx, "body-effects-%s" % self.name)
def hpr_to_quat (hpr): q = Quat () q.setHpr (hpr) return q
def move (self, dt): # Base override. # Called by world at end of frame. # Store or pop the turret. pos = self.node.getPos() pos1 = pos vel = Vec3() if self._storepos is not None: speed = self._storespeed tpos = self._storepos if self._stored else self._pos dpos = tpos - pos tdist = dpos.length() if tdist > 1e-3: if speed * dt > tdist: speed = tdist / dt tdir = unitv(dpos) vel = tdir * speed pos1 = pos + vel * dt stfac = ((pos1 - self._storepos).length() / (self._pos - self._storepos).length()) stfac = clamp(stfac, 0.0, 1.0) if self._storedecof: self._storedecof(stfac) # Rotate towards the target intercept direction. idir = self._target_intdir quat = self._aimref_sviw.getQuat() # to self._aimref_base if idir is not None: tdir = self._aimref_base.getRelativeVector(self.world.node, idir) else: tdir = hprtovec(Vec3(self.hcenter, self.pcenter, 0.0)) fdir = quat.getForward() zdir = Vec3(0, 0, 1) rdir = unitv(fdir.cross(zdir)) cturn = atan2(tdir[1], -tdir[0]) tturn = atan2(fdir[1], -fdir[0]) dturn = norm_ang_delta(cturn, tturn) celev = atan2(fdir[2], fdir.getXy().length()) telev = atan2(tdir[2], tdir.getXy().length()) delev = norm_ang_delta(celev, telev) turnrate = self.turnrate if turnrate * dt > abs(dturn): turnrate = abs(dturn) / dt turnrate *= sign(dturn) elevrate = self.elevrate if elevrate * dt > abs(delev): elevrate = abs(delev) / dt elevrate *= sign(delev) angvel = zdir * turnrate + rdir * elevrate # Compute new rotation unconstrained. angspeed = angvel.length() if angspeed > 1e-5: adir = unitv(angvel) dquat = Quat() dquat.setFromAxisAngleRad(angspeed * dt, adir) quat1 = quat * dquat # Limit to movement arc. h, p, r = quat1.getHpr() if isinstance(self.harc, tuple): harc1, harc2 = self.harc else: harc1 = self.hcenter - 0.5 * self.harc harc2 = self.hcenter + 0.5 * self.harc h = pclamp(h, harc1, harc2, -180, 180) if isinstance(self.parc, tuple): parc1, parc2 = self.parc else: parc1 = self.pcenter - 0.5 * self.parc parc2 = self.pcenter + 0.5 * self.parc p = pclamp(p, parc1, parc2, -90, 90, mirror=True) hpr1 = Vec3(h, p, r) else: hpr1 = quat.getHpr() self._update_pos_hpr(pos1, hpr1) # Needed in base class. self._prev_vel = self._vel self._vel = vel self._acc = (self._vel - self._prev_vel) / dt self._prev_angvel = self._angvel self._angvel = angvel self._angacc = (self._angvel - self._prev_angvel) / dt
def setFrom(self, snapshot): self.pos = Vec3(snapshot.pos) self.quat = Quat(snapshot.quat) self.time = engine.clock.time self.empty = snapshot.empty