def Torus(mNumSegSection=64, mNumSegCircle=64, mRadius=1.0, mSectionRadius=0.2): (gvw, prim, geom, path) = empty('t') deltaSection = (pi * 2 / mNumSegSection) deltaCircle = (pi * 2 / mNumSegCircle) offset = 0 for i in range(0, mNumSegCircle + 1): for j in range(0, mNumSegSection + 1): v0 = Vec3(mRadius + mSectionRadius * cos(j * deltaSection), mSectionRadius * sin(j * deltaSection), 0.0) q = Quat() q.setFromAxisAngleRad(i * deltaCircle, Vec3(0, 1, 0)) v = q.xform(v0) gvw.addData3f(v) if i != mNumSegCircle: prim.addVertices(offset + mNumSegSection + 1, offset, offset + mNumSegSection) prim.addVertices(offset + mNumSegSection + 1, offset + 1, offset) offset += 1 prim.closePrimitive() geom.addPrimitive(prim) return path
def drawItem(self, drawResourcesFactories, x, y, tileCenter, collision, seed=True, scale=1.0): v = drawResourcesFactories.values() if len(v) < 1: return tile = v[0].getTile() if seed: random.seed((x, y)) exists = random.random() if exists < 0.9: return quat = Quat() quat.setHpr((random.random() * 360, 0, 0)) height = tile.height(x, y) if height is None: return heightOffset = -0.4 # make sure whole bottom of tree is in ground pos = Vec3(x, y, height + heightOffset) - tileCenter self.drawTree( (pos, quat, 0, list(0 for x in drawResourcesFactories.iterkeys()), 0), drawResourcesFactories, collision, scale=scale, )
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
def _randomBend(inQuat, maxAngle=20): q=Quat() angle=random.random()*2*math.pi #power of 1/2 here makes distrobution even withint a circle # (makes larger bends are more likley as they are further spread) ammount=(math.sqrt(random.random()))*maxAngle q.setHpr((math.sin(angle)*ammount,math.cos(angle)*ammount,0)) return inQuat*q
def _angleRandomAxis(inQuat, angle, maxAngle): q=Quat() angleRange=0.125 nangle = angle + math.pi * (angleRange * random.random() - angleRange/2) #power of 1/2 here makes distrobution even withint a circle # (makes larger bends are more likley as they are further spread) ammount=(random.random()**(1.0/2))*maxAngle q.setHpr((math.sin(nangle)*ammount,math.cos(nangle)*ammount,0)) return inQuat*q
def create_colliders(root, pose_rig, joints_config): for node, parent in pose_rig.exposed_joints: if node.getName() not in joints_config: continue joint_config = joints_config[node.getName()] if "joints" not in joint_config: continue joints = joint_config["joints"] if len(joints) == 0: continue mass = joint_config["mass"] if "mass" in joint_config else 1 box_rb = BulletRigidBodyNode(node.getName()) box_rb.setMass(1.0) # box_rb.setLinearDamping(0.2) # box_rb.setAngularDamping(0.9) # box_rb.setFriction(1.0) # box_rb.setAnisotropicFriction(1.0) # box_rb.setRestitution(0.0) for joint in joints: child_node, child_parent = next( (child_node, child_parent) for child_node, child_parent in pose_rig.exposed_joints if child_node.getName() == joint ) pos = child_node.getPos(child_parent) width = pos.length() / 2.0 scale = Vec3(3, width, 3) shape = BulletBoxShape(scale) quat = Quat() lookAt(quat, child_node.getPos(child_parent), Vec3.up()) if len(joints) > 1: transform = TransformState.makePosHpr(child_node.getPos(child_parent) / 2.0, quat.getHpr()) else: transform = TransformState.makeHpr(quat.getHpr()) box_rb.addShape(shape, transform) box_np = root.attachNewNode(box_rb) if len(joints) > 1: pos = node.getPos(pose_rig.actor) hpr = node.getHpr(pose_rig.actor) box_np.setPosHpr(root, pos, hpr) else: box_np.setPos(child_parent, child_node.getPos(child_parent) / 2.0) box_np.lookAt(child_parent, child_node.getPos(child_parent)) yield box_np
def rotateAround(self, node, point, axis, angle, relative): quat = Quat() quat.setFromAxisAngle(angle, render.getRelativeVector(relative, axis)) relativePos = node.getPos(render) - point relativePosRotated = quat.xform(relativePos) absolutePosRotated = relativePosRotated + point node.setPos(render, absolutePosRotated) node.setQuat(render, node.getQuat(render) * quat)
def checkSocket(self, task): r_read, r_write, r_error = select.select([self.udpSocket],[],[],0) while r_read: msg = self.udpSocket.recv(1024) #print msg msg_list = msg.split(',') node_id = int(msg_list[0]) [w, x, y, z] = [float(val) for val in msg_list[1:5]] seqNum = int(msg_list[5]) #print seqNum q = Quat() q.setR(w) q.setI(x) q.setJ(y) q.setK(z) self.jointCur[mapping[node_id]] = q # update root root = jointNames[0] self.joints[root].setQuat(self.modelQ[root]*(self.jointCal[root]*self.jointCur[root])) #other joints for name in jointNames[1:]: parentName = parents[name] _q = self.jointCal[parentName]*self.jointCur[parentName] _q = _q.conjugate() self.joints[name].setQuat((self.jointCal[name]*self.jointCur[name])*_q*self.modelQ[name]) r_read, r_write, r_error = select.select([self.udpSocket],[],[],0) return Task.cont
def guide_missile(self, task): try: quat = Quat() lookAt(quat, self.target.np.getPos() - self.missile.anp.getPos(), Vec3.up()) self.missile.anp.setQuat(quat) fwd = quat.getForward() fwd.normalize() mvel = self.missile.anpo.getVelocity().length() self.missile.anpo.setVelocity(fwd*mvel) except: return task.done 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 drawItem(self, LOD, x, y, drawResourcesFactory, tile, tileCenter, collision, seed=True, scale=1.0): if seed: random.seed((x, y)) exists = random.random() if exists < .6: return quat = Quat() height = tile.height(x, y) if height is None: return pos = Vec3(x, y, height) - tileCenter self.drawFern(LOD, pos, quat, drawResourcesFactory, scale=scale)
def drag(self, task): if not base.mouseWatcherNode.hasMouse(): return Task.cont curMouseCoord = (base.mouseWatcherNode.getMouseX(), base.mouseWatcherNode.getMouseY()) delta = (curMouseCoord[0] - self.initialMouseCoord[0], curMouseCoord[1] - self.initialMouseCoord[1]) xQuat = Quat() xQuat.setFromAxisAngle(delta[0] * self.SCALE, Vec3(0,0,1)) yQuat = Quat() yQuat.setFromAxisAngle(delta[1] * self.SCALE * -1, Vec3(1,0,0)) self.node.setQuat(base.cam, self.initialQuat * xQuat * yQuat) return Task.cont
def solve(self, task): self.H_base = self.objH_base.H_abs # based on current calue of H_body, calculate the homogeneous coordinates in the next step # via the 4x4 exponential map. self.H_body = Lib.expm.SE3_TO_SE3(self.H_body, Lib.adjoint.ad_mul(self.H_body, self.Twist), self.timestep) #self.H_body = Lib.expm.SE3_TO_SE3(self.H_body, self.Twist, self.timestep) #calculate the h-matrix as a product of its internal mapping and the base coordinat frame self.H_abs = self.H_body * self.H_base # ToDo: implement with inverse hom. coordinates? mapping back to world observer????? if self.initialize: print("Name: ", self.name) print("\tH_base: from '{}' to '{}'".format(self.H_base.low, self.H_base.upp)) print("\tH_body: from '{}' to '{}'".format(self.H_body.low, self.H_body.upp)) print("\tH_abs: from '{}' to '{}'".format(self.H_abs.low, self.H_abs.upp)) self.initialize = False RotMat, p = Lib.h2rp(self.H_abs.mat) R = Rot.from_matrix(RotMat) quat = R.as_quat() self.body.setQuat(Quat(quat[3], quat[0], quat[1], quat[2])) self.body.setPos(p[0], p[1], p[2]) return Task.cont
def SetCamera(self, pos, targ=chrono.ChVectorD()): delta = targ - pos q0 = chrono.ChQuaternionD() q0.Q_from_AngAxis(-math.pi/2, chrono.VECT_X) alpha = 0 if (delta.z <= 0 and delta.x != 0): alpha = -math.asin(delta.x/math.hypot(delta.x, delta.z)) if (delta.z > 0): alpha = math.asin(delta.x/math.hypot(delta.x, delta.z)) + math.pi q1 = chrono.ChQuaternionD() q1.Q_from_AngAxis(alpha, q0.GetZaxis()) q2 = chrono.ChQuaternionD() q2 = q1*q0 beta = math.asin(delta.y/delta.Length()) q3 = chrono.ChQuaternionD() q3.Q_from_AngAxis(beta, q2.GetXaxis()) qc = chrono.ChQuaternionD() qc = q3*q2 q = Quat(qc.e0, qc.e1, qc.e2, qc.e3) camera.setQuat(q) camera.setPos(pos.x, pos.y, pos.z)
def update_scene(self, scene_graph, materials_only): """Update a scene using scene_graph description Arguments: scene_graph {SceneGraph} -- scene description materials_only {bool} -- update only shape materials """ for k, v in scene_graph.nodes.items(): node = self.render.attachNewNode(f'node_{k:02d}') self.nodes[k] = node for j, shape in enumerate(v.shapes): if shape.type == ShapeType.Mesh: filename = shape.mesh.filename elif shape.type == ShapeType.Cube: filename = 'cube.obj' else: print('Unknown shape type: {}'.format(shape.type)) continue # load model model = self.loader.load_model(filename) if shape.material is not None: # set material material = Material() material.setAmbient(Vec4(*shape.material.diffuse_color)) material.setDiffuse(Vec4(*shape.material.diffuse_color)) material.setSpecular(Vec3(*shape.material.specular_color)) material.setShininess(5.0) model.setMaterial(material, 1) # set relative position model.reparentTo(node) model.setPos(*shape.pose.origin) model.setQuat(Quat(*shape.pose.quat)) model.setScale(*shape.pose.scale)
def make_fixed(np0, np1, type_=BulletGenericConstraint, cfm=0.01, erp=.99): """ Make a joint and return it.""" t0 = np0.getTop() t1 = np1.getTop() p0 = np0.getPos(t0) p1 = np1.getPos(t1) q0 = np0.getQuat(t0) q1 = np1.getQuat(t1) pivot = Point3((p0 + p1) / 2.) disp = Point3((p1 - p0) / 2.) pivot_np = t0.attachNewNode("pivot-node") pivot_np.setPos(pivot) s = Vec3(1, 1, 1) q = Quat.identQuat() # pivot_np.getQuat(t0) # #BP() # q0 = pivot_np.getQuat(np0) # q1 = pivot_np.getQuat(np1) q0i = Quat(q0) q1i = Quat(q1) #BP() q0i.invertInPlace() q1i.invertInPlace() q0i *= q q1i *= q #BP() ts0 = TransformState.makePosQuatScale(disp, q0i, s) ts1 = TransformState.makePosQuatScale(-disp, q1i, s) pivot_np.removeNode() # Create the joint. joint = type_(np0.node(), np1.node(), ts0, ts1, False) for ax in xrange(4): joint.setAngularLimit(ax, 0, 0) joint.setLinearLimit(ax, 0, 0) joint.setParam(type_.CPErp, erp) joint.setParam(type_.CPCfm, cfm) joint.setDebugDrawSize(2) return joint
def getUnitCircle(): global UnitCircle if not UnitCircle: segs = LineSegs('unitCircle') vertices = LEUtils.circle(0, 0, 1, 64) angles = [Vec3(0, 0, 0), Vec3(90, 0, 0), Vec3(0, 90, 0)] for angle in angles: quat = Quat() quat.setHpr(angle) for i in range(len(vertices)): x1, y1 = vertices[i] x2, y2 = vertices[(i + 1) % len(vertices)] pFrom = quat.xform(Vec3(x1, 0, y1)) pTo = quat.xform(Vec3(x2, 0, y2)) segs.moveTo(pFrom) segs.drawTo(pTo) UnitCircle = NodePath(segs.create()) UnitCircle.setAntialias(AntialiasAttrib.MLine) UnitCircle.setLightOff(1) UnitCircle.setFogOff(1) UnitCircle.hide(DirectRender.ShadowCameraBitmask | DirectRender.ReflectionCameraBitmask) return UnitCircle
def drawFern(self, LOD, pos, quat, drawResourcesFactory, scale=1.0): scalar = random.random() scale *= scalar if scale < .3: return count = int((scalar**.7) * 12) if scale < .8: if LOD == self.lowLOD: return else: if LOD == self.midLOD: return leafResources = drawResourcesFactory.getDrawResources( self.leafDataIndex[LOD]) leafTri = leafResources.getGeomTriangles() vertexWriter = leafResources.getWriter("vertex") normalWriter = leafResources.getWriter("normal") if self.leafTexture: texcoordWriter = leafResources.getWriter("texcoord") scale *= self.scalar * 3 q2 = Quat() q3 = Quat() for i in xrange(count): p = (random.random()**2) * 60 + 20 h = random.random() * 360 q2.setHpr((h, p, 0)) q3.setHpr((h, p - 20 - p / 4, 0)) length1 = scale * 4 length2 = scale * 3 f = q2.getForward() * length1 r = q2.getRight() * scale * .5 f2 = q3.getForward() * length2 + f norm0 = q2.getUp() norm2 = q3.getUp() norm1 = norm0 + norm2 norm1.normalize() for x in range(2): leafRow = vertexWriter.getWriteRow() vertexWriter.addData3f(pos) vertexWriter.addData3f(pos + f + r) vertexWriter.addData3f(pos + f - r) vertexWriter.addData3f(pos + f2) if self.leafTexture: texcoordWriter.addData2f(0, 0) texcoordWriter.addData2f(0, 1) texcoordWriter.addData2f(1, 0) texcoordWriter.addData2f(1, 1) if x == 1: # back sides norm0 = -norm0 norm1 = -norm1 norm2 = -norm2 leafTri.addVertices(leafRow + 1, leafRow, leafRow + 2) leafTri.addVertices(leafRow + 3, leafRow + 1, leafRow + 2) else: leafTri.addVertices(leafRow, leafRow + 1, leafRow + 2) leafTri.addVertices(leafRow + 1, leafRow + 3, leafRow + 2) normalWriter.addData3f(norm0) normalWriter.addData3f(norm1) normalWriter.addData3f(norm1) normalWriter.addData3f(norm2)
def getRotationTo(src, dest, fallbackAxis=Vec3_ZERO): # Quaternion q; # Vector3 v0 = *this; # Vector3 v1 = dest; # v0.normalise(); # v1.normalise(); q = Quat() v0 = Vec3(src) v1 = Vec3(dest) v0.normalize() v1.normalize() # Real d = v0.dotProduct(v1); d = v0.dot(v1) # if (d >= 1.0f) # { # return Quaternion::IDENTITY; # } if d >= 1.0: return Quat(1, 0, 0, 0) # if (d < (1e-6f - 1.0f)) if d < (1.0e-6 - 1.0): # if (fallbackAxis != Vector3::ZERO) # { # // rotate 180 degrees about the fallback axis # q.FromAngleAxis(Radian(Math::PI), fallbackAxis); # } if fallbackAxis != Vec3_ZERO: q.setFromAxisAngleRad(pi, fallbackAxis) # else # { # // Generate an axis # Vector3 axis = Vector3::UNIT_X.crossProduct(*this); # if (axis.isZeroLength()) // pick another if colinear # axis = Vector3::UNIT_Y.crossProduct(*this); # axis.normalise(); # q.FromAngleAxis(Radian(Math::PI), axis); # } else: axis = Vec3(1, 0, 0).cross(src) if axis.almostEqual(Vec3.zero()): axis = Vec3(0, 1, 0).cross(src) axis.normalize() q.setFromAxisAngleRad(pi, axis) # else # { # Real s = Math::Sqrt( (1+d)*2 ); # Real invs = 1 / s; # Vector3 c = v0.crossProduct(v1); # q.x = c.x * invs; # q.y = c.y * invs; # q.z = c.z * invs; # q.w = s * 0.5f; # q.normalise(); # } else: s = sqrt((1 + d) * 2) invs = 1 / s c = v0.cross(v1) q.setI(c.x * invs) q.setJ(c.y * invs) q.setK(c.z * invs) q.setR(s * .5) q.normalize() return q
def alignCarTowardsForceField(self, dt, p0, p1): modelPos = self.model.getPos() path = self.pointSegmentShortestPath(modelPos, p1, p0, bounds=True, boundsNone=True) if path is None: return None Len = path.length() if Len < 0.2: Len = 0.2 delta = 100.0 vec = (p1 - p0).normalized() vec *= delta originalQuat = self.model.getQuat() quat = Quat(originalQuat) other_quat = Quat(originalQuat) lookAt(quat, vec, Vec3().up()) lookAt(other_quat, -vec, Vec3().up()) if not quat.almostSameDirection(originalQuat, 0.5): [p0, p1] = [p1, p0] vec = (p0 - p1).normalized() * delta quat = other_quat if not quat.almostSameDirection(originalQuat, 0.5): return None # Make car go more towards the selected path at intersection angleSimilarityFactor = abs( self.direction.normalized().dot(vec.normalized()) + path.length()) # Go closer to road pos_strength = dt * angleSimilarityFactor pos_strength /= (Len * Len) if Len > 1.0 else 1.0 pos_strength *= ROAD_POS_STRENGTH pos_strength = sorted([0, pos_strength, 1])[1] position = modelPos - path * pos_strength strength = ALIGN_STRENGTH * dt / ((Len * Len) if Len > 1 else 1) strength = sorted([0, strength, 1])[1] self.car_shadow.setPos(self.model.getPos()) self.car_shadow.setHpr(self.model.getHpr()) self.model.setQuat(quat) targetHpr = self.model.getHpr(self.car_shadow) self.model.setQuat(originalQuat) currentHpr = self.model.getHpr(self.car_shadow) self.model.setHpr(self.car_shadow, targetHpr * strength + currentHpr * (1.0 - strength)) quat = self.model.getQuat() # Put velocity in direction of road blend_velocity = BLEND_VELOCITY_FAC_TOWARDS_ROAD * dt velocity = self.velocity.project(vec) * ( blend_velocity) + self.velocity * (1.0 - blend_velocity) self.model.setPos(position) self.model.setQuat(quat) self.velocity = velocity
def fixQuat(quat): quat = (-quat[0], quat[1], quat[2], quat[3]) return Quat(*quat)
def takeSnapshot(self, entity): self.pos = entity.getPosition() self.quat = Quat(entity.getQuaternion()) self.time = engine.clock.time self.empty = False
def getFrom(iterator): return Quat(net.StandardFloat.getFrom(iterator), net.StandardFloat.getFrom(iterator), net.StandardFloat.getFrom(iterator), net.StandardFloat.getFrom(iterator))
def __init__(self): DirectObject.__init__(self) self.mouseEnabled = False self.lastCamRoot2Quat = Quat(Quat.identQuat()) self.punchAngleVel = Vec3(0) self.punchAngle = Vec3(0) self.lastFacing = Vec3(0) self.lastMousePos = Point2(0) self.currMousePos = Point2(0) self.bobTime = 0 self.lastBobTime = 0 self.lastVMPos = Point3(0) self.camRoot = NodePath("camRoot") self.camRoot2 = self.camRoot.attachNewNode("camRoot2") self.lastPitch = 0 self.lastEyeHeight = 0.0 # Updates to the transform of camRoot self.vmRender = NodePath( BSPRender('vmRender', BSPLoader.getGlobalPtr())) self.vmRender.setShaderAuto() self.vmRoot = self.vmRender.attachNewNode('vmRoot') self.vmRoot2 = self.vmRoot.attachNewNode(ModelRoot('vmRoot2')) self.viewModel = Actor( "phase_14/models/char/v_toon_arms.bam", { "zero": "phase_14/models/char/v_toon_arms.egg", # Squirt gun viewmodel animations "sg_draw": "phase_14/models/char/v_toon_arms-draw.egg", "sg_idle": "phase_14/models/char/v_toon_arms-idle.egg", "sg_inspect": "phase_14/models/char/v_toon_arms-inspect.egg", "sg_shoot_begin": "phase_14/models/char/v_toon_arms-shoot_begin.egg", "sg_shoot_loop": "phase_14/models/char/v_toon_arms-shoot_loop.egg", "sg_shoot_end": "phase_14/models/char/v_toon_arms-shoot_end.egg", "pie_draw": "phase_14/models/char/v_toon_arms-pie_draw.egg", "pie_idle": "phase_14/models/char/v_toon_arms-pie_idle.egg", "button_draw": "phase_14/models/char/v_toon_arms-button_draw.egg", "button_idle": "phase_14/models/char/v_toon_arms-button_idle.egg", "button_press": "phase_14/models/char/v_toon_arms-button_press.egg", "gumball_draw": "phase_14/models/char/v_toon_arms-gumball_draw.egg", "gumball_idle": "phase_14/models/char/v_toon_arms-gumball_idle.egg", "gumball_fire": "phase_14/models/char/v_toon_arms-gumball_fire.egg", "hose_draw": "phase_14/models/char/v_toon_arms-hose_draw.egg", "hose_idle": "phase_14/models/char/v_toon_arms-hose_idle.egg", "hose_shoot_begin": "phase_14/models/char/v_toon_arms-hose_shoot_begin.egg", "hose_shoot_loop": "phase_14/models/char/v_toon_arms-hose_shoot_loop.egg", "hose_shoot_end": "phase_14/models/char/v_toon_arms-hose_shoot_end.egg", "tnt_draw": "phase_14/models/char/v_toon_arms-tnt_draw.egg", "tnt_idle": "phase_14/models/char/v_toon_arms-tnt_idle.egg", "tnt_throw": "phase_14/models/char/v_toon_arms-tnt_throw.egg", "slap_idle": "phase_14/models/char/v_toon_arms-slap_idle.egg", "slap_hit": "phase_14/models/char/v_toon_arms-slap_hit.egg", "sound": "phase_14/models/char/v_toon_arms-sound.egg" }) self.viewModel.setBlend( frameBlend=base.config.GetBool("interpolate-frames", False)) self.viewModel.reparentTo(self.vmRoot2) self.viewModel.find("**/hands").setTwoSided(True) self.viewModel.hide() self.defaultViewModel = self.viewModel self.idealFov = self.ViewModelFOV precacheActor(self.viewModel) #self.viewModel.clearMaterial() #self.viewModel.setMaterial(CIGlobals.getCharacterMaterial(specular = (0, 0, 0, 1)), 1) self.viewportLens = PerspectiveLens() self.viewportLens.setMinFov(self.ViewModelFOV / (4. / 3.)) self.viewportLens.setNear(0.3) # Updates to the transform of base.camera self.viewportCam = base.makeCamera(base.win, clearDepth=True, camName='fpsViewport', mask=CIGlobals.ViewModelCamMask, lens=self.viewportLens) # Pretend to be the main camera so the viewmodel gets ambient probes updated self.viewportCam.node().setTag("__mainpass__", "1") self.viewportCam.reparentTo(self.vmRoot) self.vmGag = None self.vmAnimTrack = None self.dmgFade = OnscreenImage(image="phase_14/maps/damage_effect.png", parent=render2d) self.dmgFade.setBin('gui-popup', 100) self.dmgFade.setTransparency(1) self.dmgFade.setColorScale(1, 1, 1, 0) self.dmgFadeIval = None #self.accept('v', self.vmRender.ls) #base.bspLoader.addDynamicNode(self.vmRoot) if self.PrintAnimLengths: print "v_toon_arms animation lengths:" for anim in self.viewModel.getAnimNames(): print "\t{0}\t:\t{1}".format(anim, self.viewModel.getDuration(anim)) taskMgr.add(self.__vpDebugTask, "vpdebutask", sort=-100)
def getUpHPR(hpr): q = Quat() q.setHpr(VBase3(math.degrees(hpr.h), math.degrees(hpr.p), math.degrees(hpr.r))) v = q.getUp() return SP3(v.x, v.y, v.z)
def maj_physique(self): self.modele.setPosQuat(self.app.render, self.corps.getPosition(), Quat(self.corps.getQuaternion()))
def update(self, keys, dt): GameObject.update(self, dt) self.updateSpeedometer() self.walking = False quat = self.root.getQuat(Common.framework.showBase.render) forward = quat.getForward() right = quat.getRight() up = quat.getUp() if keys["up"]: self.walking = True self.velocity += forward * self.acceleration * dt if keys["down"]: self.walking = True self.velocity -= forward * self.acceleration * dt if keys["left"]: self.walking = True self.velocity -= right * self.acceleration * dt if keys["right"]: self.walking = True self.velocity += right * self.acceleration * dt if self.walking: self.inControl = True mouseWatcher = base.mouseWatcherNode if mouseWatcher.hasMouse(): xSize = base.win.getXSize() ySize = base.win.getYSize() xPix = float(xSize % 2) / xSize yPix = float(ySize % 2) / ySize mousePos = Vec2(base.mouseWatcherNode.getMouse()) mousePos.addX(-xPix) mousePos.addY(-yPix) if abs(mousePos.x) < xPix: mousePos.x = 0 if abs(mousePos.y) < yPix: mousePos.y = 0 else: mousePos = self.lastMousePos if mousePos.length() > 0.01: axis = right * (mousePos.y) + up * (-mousePos.x) axis.normalize() angle = mousePos.length() * self.turnRate * dt rotQuat = Quat() rotQuat.setFromAxisAngle(angle, axis) self.root.setQuat(quat * rotQuat) if not self.weaponSets[0][0].active: self.alterEnergy( math.sin(1.071 * self.energy / self.maxEnergy + 0.5) * self.energyRechargeRate * dt) self.updateEnergyUI() self.updateHealthUI() self.updateRadar() #self.root.setH(self.root.getH() - mousePos.x*self.mouseSpeedHori*self.mouseSensitivity) #self.actor.setP(self.actor.getP() + mousePos.y*self.mouseSpeedVert*self.mouseSensitivity) if keys["shoot"]: self.startFiringSet(0) else: self.ceaseFiringSet(0) if keys["shootSecondary"]: self.startFiringSet(self.missileSetIndex + 1) else: for i in range(self.numMissileSets): self.ceaseFiringSet(i + 1) [effect.update(self, dt) for effect in self.updatingEffects] [ effect.cleanup() for effect in self.updatingEffects if not effect.active ] self.updatingEffects = [ effect for effect in self.updatingEffects if effect.active ] if self.targetingQueue.getNumEntries() > 0: self.targetingQueue.sortEntries() entry = self.targetingQueue.getEntry(0) intoNP = entry.getIntoNodePath() if intoNP.hasPythonTag(TAG_OWNER): other = intoNP.getPythonTag(TAG_OWNER) if other is self.prospectiveLockTarget and other is not self.lockedTarget: self.lockTargetTimer += dt if self.lockTargetTimer >= self.lockDuration: self.lockedTarget = other else: self.lockTargetTimer = 0 self.prospectiveLockTarget = other else: self.lockTargetTimer = 0 else: self.lockTargetTimer = 0 perc = self.lockTargetTimer / self.lockDuration self.lockBar.setTexOffset(TextureStage.getDefault(), 0, -perc * 1.1) if self.lockedTarget is not None: if self.lockedTarget.health <= 0: self.lockedTarget = None else: relPos = self.lockedTarget.root.getPos(self.root) planarVec = relPos.getXz() relDist = relPos.length() if relDist == 0: angle = 0 else: angle = math.acos(relPos.y / relDist) if relDist > 200 or angle > 1.7453: self.lockedTarget = None else: if self.lockMarkerRoot.isHidden(): self.lockMarkerRoot.show() camPt = Point2() convertedPt = Common.framework.showBase.cam.getRelativePoint( Common.framework.showBase.render, self.lockedTarget.root.getPos( Common.framework.showBase.render)) if Common.framework.showBase.camLens.project( convertedPt, camPt): self.lockMarkerRoot.setPos( Common.framework.showBase.render2d, camPt.x, 0, camPt.y) if self.lockMarkerRoot.isHidden(): self.lockMarkerRoot.show() for child in self.lockMarkerRoot.getChildren(): child.getChild(0).setZ( (1.0 - min(1, relDist / 100)) * 5 + 0.2) elif not self.lockMarkerRoot.isHidden(): self.lockMarkerRoot.hide() if relPos.y < 0 or angle > 0.6: planarVec.normalize() self.directionIndicator.setPos(planarVec.x * 0.4, 0, planarVec.y * 0.4) angle = math.degrees( math.atan2(planarVec.x, planarVec.y)) self.directionIndicator.setR(angle) if self.directionIndicator.isHidden(): self.directionIndicator.show() elif not self.directionIndicator.isHidden(): self.directionIndicator.hide() else: if not self.directionIndicator.isHidden(): self.directionIndicator.hide() if not self.lockMarkerRoot.isHidden(): self.lockMarkerRoot.hide()
def cameraLerp(self, i): pos, hpr = cameraLerps[i] quat = Quat() quat.setHpr(hpr) camera.posQuatInterval(1.2, pos, quat).start()
def __init__(self): self.pos = Vec3() self.quat = Quat() self.time = 0 self.empty = True
def drawFern(self,LOD,pos,quat,drawResourcesFactory,scale=1.0): scalar=random.random() scale*=scalar if scale<.3: return count=int((scalar**.7)*12) if scale<.8: if LOD==self.lowLOD: return else: if LOD==self.midLOD: return leafResources=drawResourcesFactory.getDrawResources(self.leafDataIndex[LOD]) leafTri=leafResources.getGeomTriangles() vertexWriter=leafResources.getWriter("vertex") normalWriter=leafResources.getWriter("normal") if self.leafTexture: texcoordWriter = leafResources.getWriter("texcoord") scale*=self.scalar*3 q2=Quat() q3=Quat() for i in xrange(count): p=(random.random()**2)*60+20 h=random.random()*360 q2.setHpr((h,p,0)) q3.setHpr((h,p-20-p/4,0)) length1=scale*4 length2=scale*3 f=q2.getForward()*length1 r=q2.getRight()*scale*.5 f2=q3.getForward()*length2+f norm0=q2.getUp() norm2=q3.getUp() norm1=norm0+norm2 norm1.normalize() for x in range(2): leafRow = vertexWriter.getWriteRow() vertexWriter.addData3f(pos) vertexWriter.addData3f(pos+f+r) vertexWriter.addData3f(pos+f-r) vertexWriter.addData3f(pos+f2) if self.leafTexture: texcoordWriter.addData2f(0,0) texcoordWriter.addData2f(0,1) texcoordWriter.addData2f(1,0) texcoordWriter.addData2f(1,1) if x==1: # back sides norm0=-norm0 norm1=-norm1 norm2=-norm2 leafTri.addVertices(leafRow+1,leafRow,leafRow+2) leafTri.addVertices(leafRow+3,leafRow+1,leafRow+2) else: leafTri.addVertices(leafRow,leafRow+1,leafRow+2) leafTri.addVertices(leafRow+1,leafRow+3,leafRow+2) normalWriter.addData3f(norm0) normalWriter.addData3f(norm1) normalWriter.addData3f(norm1) normalWriter.addData3f(norm2)
def setFrom(self, snapshot): self.pos = Vec3(snapshot.pos) self.quat = Quat(snapshot.quat) self.time = engine.clock.time self.empty = snapshot.empty
def release(self): Gag.release(self) base.audio3d.attachSoundToObject(self.woosh, self.gag) base.playSfx(self.woosh, node=self.gag) if self.isLocal() and base.localAvatar.battleControls: if base.localAvatar.isFirstPerson(): # Add a small kick to the camera to give more feedback self.getFPSCam().addViewPunch( Vec3(random.uniform(.5, 1), random.uniform(-.5, -1), 0)) startPos = camera.getPos(render) + camera.getQuat( render).xform(Vec3.right()) push = 0.0 else: startPos = self.handJoint.getPos(render) push = (startPos - camera.getPos(render)).length() hitPos = PhysicsUtils.getHitPosFromCamera() else: startPos = self.handJoint.getPos(render) quat = Quat() quat.setHpr( self.avatar.getHpr(render) + (0, self.avatar.lookPitch, 0)) hitPos = quat.xform(Vec3.forward() * self.power) hit = PhysicsUtils.rayTestClosestNotMe( self.avatar, startPos, hitPos, CIGlobals.WorldGroup | CIGlobals.LocalAvGroup) if hit is not None: hitPos = hit.getHitPos() throwDir = (hitPos - startPos).normalized() endPos = startPos + (throwDir * self.power) - (0, 0, 90) entity = self.gag if not entity: entity = self.build() gagRoot = render.attachNewNode('gagRoot') gagRoot.setPos(startPos) entity.reparentTo(render) entity.setPos(0, 0, 0) entity.headsUp(throwDir) rot = entity.getHpr(render) entity.reparentTo(gagRoot) entity.setHpr(rot[0], -90, 0) self.gag = None if not self.handJoint: self.handJoint = self.avatar.find('**/def_joint_right_hold') track = FlightProjectileInterval(gagRoot, startPos=startPos, endPos=endPos, gravityMult=1.07, duration=2.5) event = self.avatar.uniqueName('throwIvalDone') + '-' + str( hash(entity)) track.setDoneEvent(event) base.acceptOnce(event, self.__handlePieIvalDone, [entity]) track.start() if self.isLocal(): collider = self.buildCollisions(entity) self.entities.append([gagRoot, track, collider]) base.localAvatar.sendUpdate('usedGag', [self.id]) else: self.entities.append([gagRoot, track, NodePath()]) self.reset()
def __updateTask(self, task): # TODO -- This function does a lot of math, I measured it to take .5 ms on my laptop # That's a lot of time for something miniscule like sway and bob. dt = globalClock.getDt() time = globalClock.getFrameTime() if base.localAvatar.isFirstPerson(): eyePoint = base.localAvatar.getEyePoint() if base.localAvatar.walkControls.crouching: eyePoint[2] = eyePoint[2] / 2.0 eyePoint[2] = CIGlobals.lerpWithRatio(eyePoint[2], self.lastEyeHeight, 0.4) self.lastEyeHeight = eyePoint[2] camRootAngles = Vec3(0) # Mouse look around mw = base.mouseWatcherNode if mw.hasMouse(): md = base.win.getPointer(0) center = Point2(base.win.getXSize() / 2, base.win.getYSize() / 2) xDist = md.getX() - center.getX() yDist = md.getY() - center.getY() sens = self.__getMouseSensitivity() angular = -(xDist * sens) / dt base.localAvatar.walkControls.controller.setAngularMovement( angular) camRootAngles.setY(self.lastPitch - yDist * sens) if camRootAngles.getY() > FPSCamera.MaxP: camRootAngles.setY(FPSCamera.MaxP) yDist = 0 elif camRootAngles.getY() < FPSCamera.MinP: yDist = 0 camRootAngles.setY(FPSCamera.MinP) base.win.movePointer(0, int(center.getX()), int(center.getY())) if base.localAvatar.isFirstPerson(): # Camera / viewmodel bobbing vmBob = Point3(0) vmAngles = Vec3(0) vmRaise = Point3(0) camBob = Point3(0) maxSpeed = base.localAvatar.walkControls.BattleRunSpeed * 16.0 speed = base.localAvatar.walkControls.speeds.length() * 16.0 speed = max(-maxSpeed, min(maxSpeed, speed)) bobOffset = CIGlobals.remapVal(speed, 0, maxSpeed, 0.0, 1.0) self.bobTime += (time - self.lastBobTime) * bobOffset self.lastBobTime = time # Calculate the vertical bob cycle = self.bobTime - int( self.bobTime / self.BobCycleMax) * self.BobCycleMax cycle /= self.BobCycleMax if cycle < self.BobUp: cycle = math.pi * cycle / self.BobUp else: cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 - self.BobUp) verticalBob = speed * 0.005 verticalBob = verticalBob * 0.3 + verticalBob * 0.7 * math.sin( cycle) verticalBob = max(-7.0, min(4.0, verticalBob)) verticalBob /= 16.0 # Calculate the lateral bob cycle = self.bobTime - int( self.bobTime / self.BobCycleMax * 2) * self.BobCycleMax * 2 cycle /= self.BobCycleMax * 2 if cycle < self.BobUp: cycle = math.pi * cycle / self.BobUp else: cycle = math.pi + math.pi * (cycle - self.BobUp) / (1.0 - self.BobUp) lateralBob = speed * 0.005 lateralBob = lateralBob * 0.3 + lateralBob * 0.7 * math.sin(cycle) lateralBob = max(-7.0, min(4.0, lateralBob)) lateralBob /= 16.0 # Apply bob, but scaled down a bit vmBob.set(lateralBob * 0.8, 0, verticalBob * 0.1) # Z bob a bit more vmBob[2] += verticalBob * 0.1 # Bob the angles vmAngles[2] += verticalBob * 0.5 vmAngles[1] -= verticalBob * 0.4 vmAngles[0] -= lateralBob * 0.3 # ================================================================ # Viewmodel lag/sway angles = self.camRoot.getHpr(render) quat = Quat() quat.setHpr(angles) invQuat = Quat() invQuat.invertFrom(quat) maxVMLag = 1.5 lagforward = quat.getForward() if dt != 0.0: lagdifference = lagforward - self.lastFacing lagspeed = 5.0 lagdiff = lagdifference.length() if (lagdiff > maxVMLag) and (maxVMLag > 0.0): lagscale = lagdiff / maxVMLag lagspeed *= lagscale self.lastFacing = CIGlobals.extrude(self.lastFacing, lagspeed * dt, lagdifference) self.lastFacing.normalize() lfLocal = invQuat.xform(lagdifference) vmBob = CIGlobals.extrude(vmBob, 5.0 / 16.0, lfLocal * -1.0) pitch = angles[1] if pitch > 180: pitch -= 360 elif pitch < -180: pitch += 360 vmBob = CIGlobals.extrude(vmBob, pitch * (0.035 / 16), Vec3.forward()) vmBob = CIGlobals.extrude(vmBob, pitch * (0.03 / 16), Vec3.right()) vmBob = CIGlobals.extrude(vmBob, pitch * (0.02 / 16), Vec3.up()) # ================================================================ vmRaise.set( 0, 0, 0 ) #(0, abs(camRootAngles.getY()) * -0.002, camRootAngles.getY() * 0.002) camBob.set(0, 0, 0) # Apply bob, raise, and sway to the viewmodel. self.viewModel.setPos(vmBob + vmRaise + self.lastVMPos) self.vmRoot2.setHpr(vmAngles) self.camRoot.setPos(eyePoint + camBob) newPitch = camRootAngles.getY() if abs(newPitch - self.lastPitch) > self.PitchUpdateEpsilon: # Broadcast where our head is looking head = base.localAvatar.getPart("head") if head and not head.isEmpty(): # Constrain the head pitch a little bit so it doesn't look like their head snapped headPitch = max(-47, newPitch) headPitch = min(75, headPitch) base.localAvatar.b_setLookPitch(headPitch) self.lastPitch = newPitch if base.localAvatar.isFirstPerson(): # Apply punch angle self.decayPunchAngle() camRootAngles += self.punchAngle self.camRoot.setHpr(camRootAngles) return task.cont
def drawTree(self,base,drawResourcesFactories,collision,scale=1.0): age=random.random()**3.5 to = 12*age if to<3: return leafScaler=age**.5 leafSize=10.0*self.scalar*leafScaler*scale maxbend=40+random.random()*20 forks=int(to/2-1) lengthList=[] numCopiesList=[] radiusList=[] currR=age*1.0*(random.random()*2+1) forkCount=0 lengthScale=2.0*scale for i in xrange(forks+1): currR*=1/math.sqrt(2) endR=currR*.9*.9 if i==forks: endR=0 forkCount=0 if i<2: lengthList.extend([lengthScale,lengthScale,lengthScale]) numCopiesList.extend([forkCount,0,0]) radiusList.extend([currR,currR*.9,endR]) else: lengthList.extend([lengthScale*3]) numCopiesList.extend([forkCount]) radiusList.extend([endR]) forkCount=2+(i%2) doLeaves=True dotCount=1 stack = [base] LODs=list(drawResourcesFactories.keys()) angleDatas=[] for LODnum,LOD in enumerate(LODs): drawResourcesFactory=drawResourcesFactories[LOD] if LOD==self.minLOD: numVertices=2 elif LOD==self.lowLOD: numVertices=3 elif LOD==self.midLOD: numVertices=4 else: numVertices=6 #cache some info needed for placeing the vertexes angleData=[] if self.barkTexture: vNum=numVertices+1 else: vNum=numVertices for i in xrange(vNum): #doubles the last vertex to fix UV seam angle=-2 * i * math.pi / numVertices angleData.append((math.cos(angle),math.sin(angle),1.0*i / numVertices)) angleDatas.append(angleData) bottom=True if collision: cNode=CollisionNode('cnode') cnodePath = NodePath(cNode) cnodePath.reparentTo(collision) cnodePath.setCollideMask(collisionUtil.groundMask) #cnodePath.show() while stack: pos, quat, depth, previousRows, sCoord = stack.pop() length = lengthList[depth] sCoord += length/4.0 radius=radiusList[depth] perp1 = quat.getRight() perp2 = quat.getForward() startRows=[] for LODnum,LOD in enumerate(LODs): drawResourcesFactory=drawResourcesFactories[LOD] previousRow=previousRows[LODnum] angleData=angleDatas[LODnum] vNum=len(angleData) if LOD==self.minLOD: cutoffRadius=.7 elif LOD==self.lowLOD: cutoffRadius=.5 elif LOD==self.midLOD: cutoffRadius=.1 else: cutoffRadius=-1 trunkResources=drawResourcesFactory.getDrawResources(self.trunkDataIndex[LOD]) lines = trunkResources.getGeomTristrips() vertWriter = trunkResources.getWriter("vertex") normalWriter = trunkResources.getWriter("normal") if self.barkTexture: texWriter = trunkResources.getWriter("texcoord") # else: # colorWriter = trunkResources.getWriter("color") startRow = vertWriter.getWriteRow() startRows.append(startRow) if radius>cutoffRadius: #this draws the body of the tree. This draws a ring of vertices and connects the rings with #triangles to form the body. #vertex information is written here for cos,sin,tex in angleData: adjCircle = pos + (perp1 * cos + perp2 * sin) * radius * self.scalar normal = perp1 * cos + perp2 * sin normalWriter.addData3f(normal) vertWriter.addData3f(adjCircle) if self.barkTexture is not None: texWriter.addData2f(tex,sCoord) # else: # colorWriter.addData4f(.4,.3,.3,1) #we cant draw quads directly so we use Tristrips if not bottom: for i in xrange(vNum): lines.addVertices(i + previousRow,i + startRow) if not self.barkTexture: lines.addVertices(previousRow,startRow) lines.closePrimitive() bottom=False if depth + 1 < len(lengthList): #move foward along the correct axis newPos = pos + quat.getUp() * length * self.scalar # if makeColl: # self.makeColl(pos, newPos, radiusList[depth]) numCopies = numCopiesList[depth] if numCopies: angleOffset=random.random()*2*math.pi for i in xrange(numCopies): newQuat= _angleRandomAxis(quat, 2 * math.pi * i / numCopies+angleOffset, maxbend) newPos2=pos + newQuat.getUp() * length * self.scalar stack.append((newPos2,newQuat, depth + 1, startRows, sCoord)) if collision: tube = CollisionTube(Point3(pos),Point3(newPos2),radius) cNode.addSolid(tube) else: #just make another branch connected to this one with a small variation in direction stack.append((newPos, _randomBend(quat, 20), depth + 1, startRows, sCoord)) if collision: tube = CollisionTube(Point3(pos),Point3(newPos),radius) cNode.addSolid(tube) elif doLeaves: q=Quat() q.setHpr((random.random()*2*math.pi,0,0)) quat=quat*q up=quat.getUp() down=-up # size s=leafSize dir1=perp1*s dir2=perp2*s bend=-up*(s/4.0) v0=pos+dir1 v1=pos+dir2+bend v2=pos-dir1 v3=pos-dir2+bend norm1=dir1.cross(dir2+bend) norm1.normalize() norm2=dir1.cross(dir2-bend) norm2.normalize() for LOD,drawResourcesFactory in drawResourcesFactories.iteritems(): leafResources=drawResourcesFactory.getDrawResources(self.leafDataIndex[LOD]) leafTri=leafResources.getGeomTriangles() n1=norm1 n2=norm2 upVec=up leafVertexWriter=leafResources.getWriter("vertex") leafNormalWriter=leafResources.getWriter("normal") if self.leafTexture: leafTexcoordWriter = leafResources.getWriter("texcoord") else: leafColorWriter = leafResources.getWriter("color") for x in range(2): leafRow = leafVertexWriter.getWriteRow() leafVertexWriter.addData3f(v0) leafVertexWriter.addData3f(v1) leafVertexWriter.addData3f(v2) leafVertexWriter.addData3f(v3) if self.leafTexture is not None: n=dotCount leafTexcoordWriter.addData2f(0,0) leafTexcoordWriter.addData2f(0,n) leafTexcoordWriter.addData2f(n,n) leafTexcoordWriter.addData2f(n,0) else: leafColorWriter.addData4f(.5,.4,.0,1) leafColorWriter.addData4f(.0,.4,.0,1) leafColorWriter.addData4f(.5,.4,.0,1) leafColorWriter.addData4f(.0,.4,.0,1) if x==1: # back sides upVec=-up n1=-norm1 n2=-norm2 leafTri.addVertices(leafRow+1,leafRow,leafRow+2) leafTri.addVertices(leafRow+2,leafRow,leafRow+3) else: leafTri.addVertices(leafRow,leafRow+1,leafRow+2) leafTri.addVertices(leafRow,leafRow+2,leafRow+3) leafNormalWriter.addData3f(upVec) leafNormalWriter.addData3f(n1) leafNormalWriter.addData3f(upVec) leafNormalWriter.addData3f(n2)
def get_unit(hpr): q = Quat() q.setHpr(hpr) return q.xform(Vec3(0, 1, 0))
def getViewMatrix(self): quat = Quat() quat.setHpr(self.getViewHpr()) mat = Mat4() quat.extractToMatrix(mat) return mat
def rotate(self, point): quat = Quat() quat.setHpr(self.getViewHpr()) return quat.xform(point)
def invRotate(self, point): quat = Quat() quat.setHpr(self.getViewHpr()) return LEUtils.makeForwardAxis(point, quat)
def simulationTask(task): global deltaTimeAccumulator # Add the deltaTime for the task to the accumulator deltaTimeAccumulator += globalClock.getDt() while deltaTimeAccumulator > stepSize: # Remove a stepSize from the accumulator until # the accumulated time is less than the stepsize deltaTimeAccumulator -= stepSize # Step the simulation world.quickStep(stepSize) # set the new positions Counter.setText('Electron Pairs: ' + str(len(electrons))) drawLines() global strafe global elevation global cameradistance strafe += 0.00 #handles the keyboard inputs if keyboard.is_pressed('w') and elevation < 3.12 / 2.0: elevation += 0.02 if keyboard.is_pressed('s') and elevation > -3.12 / 2.0: elevation -= 0.02 if keyboard.is_pressed('d'): strafe += 0.02 if keyboard.is_pressed('a'): strafe -= 0.02 if keyboard.is_pressed('+'): cameradistance -= 1 if keyboard.is_pressed('-'): cameradistance += 1 if keyboard.is_pressed('esc'): hideHelp() for x in range(len(bodies)): electrons[x].model.setPosQuat(render, bodies[x].getPosition(), Quat(bodies[x].getQuaternion())) setCamera() # takes care of all the repulsive forces for a in electrons: xAccum = 0 yAccum = 0 zAccum = 0 for b in electrons: distance = math.sqrt( math.pow(a.model.getX() - b.model.getX(), 2) + math.pow(a.model.getY() - b.model.getY(), 2) + math.pow(a.model.getZ() - b.model.getZ(), 2)) try: xAccum += 10 * (a.model.getX() - b.model.getX()) / math.pow( distance, 3) except: xAccum += 0 try: yAccum += 10 * (a.model.getY() - b.model.getY()) / math.pow( distance, 3) except: yAccum += 0 try: zAccum += 10 * (a.model.getZ() - b.model.getZ()) / math.pow( distance, 3) except: zAccum += 0 a.setX(a.getX() + xAccum) a.setY(a.getY() + yAccum) a.setZ(a.getZ() + zAccum) for e in electrons: e.updatePos() for a in range(len(bodies)): bodies[a].setPosition(electrons[a].model.getPos(render)) return task.cont
def makeForwardAxis(vec, quat): invQuat = Quat() invQuat.invertFrom(quat) result = invQuat.xform(vec) result.setY(0.0) return result
def __updateParticleParent(self, task=None): time = globalClock.getFrameTime() streamPos = self.waterStreamParent.getPos(render) distance = self.sprayParticleDist if self.isLocal(): if base.localAvatar.backpack.getSupply(self.id) <= 0: base.localAvatar.b_gagThrow(self.id) return task.done camQuat = camera.getQuat(render) pFrom = camera.getPos(render) push = (streamPos - pFrom).length() pFrom += camQuat.xform(Vec3.forward()) * push pTo = pFrom + camQuat.xform( Vec3.forward()) * (self.sprayParticleDist + (pFrom - streamPos).length()) hitPos = Point3(pTo) result = base.physicsWorld.rayTestClosest(pFrom, pTo, CIGlobals.WorldGroup) if result.hasHit(): node = result.getNode() hitPos = result.getHitPos() distance = (hitPos - streamPos).length() if time - self.lastDmgTime >= self.dmgIval: self._handleSprayCollision(NodePath(node), hitPos, distance) self.lastDmgTime = time if time - self.lastSprayTime >= self.dmgIval: self.getFPSCam().addViewPunch( Vec3(random.uniform(-0.6, 0.6), random.uniform(0.25, 1.0), 0.0)) base.localAvatar.sendUpdate('usedGag', [self.id]) self.lastSprayTime = time else: pFrom = self.avatar.getPos(render) + self.avatar.getEyePoint() + ( 1, 0, 0) quat = Quat() quat.setHpr( self.avatar.getHpr(render) + (0, self.avatar.lookPitch, 0)) pTo = pFrom + quat.xform( Vec3.forward()) * (self.sprayParticleDist + (pFrom - streamPos).length()) hitPos = Point3(pTo) hit = PhysicsUtils.rayTestClosestNotMe( self.avatar, pFrom, pTo, CIGlobals.WorldGroup | CIGlobals.LocalAvGroup) if hit is not None: hitPos = hit.getHitPos() distance = (hitPos - streamPos).length() self.waterStreamParent.lookAt(render, hitPos) if self.sprayParticle: system = self.sprayParticle.getParticlesNamed('particles-1') # Make the particles die off at the hit point. lifespan = min( 1, distance / self.sprayParticleDist) * self.sprayParticleLife system.factory.setLifespanBase(lifespan) if task: return task.cont
def generate_roads(models, terrain, map, json_out): numroads = 0 for center in progress.bar(map.centers.values(), label='Generating roads... '): road_edges = [e for e in center.edges if e.is_road and e.corner0 is not None and e.corner1 is not None] if len(road_edges) != 2: continue e1, e2 = road_edges e1_0 = numpy.array([e1.corner0.x, e1.corner0.y, e1.corner0.elevation * Z_SCALE], dtype=numpy.float32) e1_1 = numpy.array([e1.corner1.x, e1.corner1.y, e1.corner1.elevation * Z_SCALE], dtype=numpy.float32) e2_0 = numpy.array([e2.corner0.x, e2.corner0.y, e2.corner0.elevation * Z_SCALE], dtype=numpy.float32) e2_1 = numpy.array([e2.corner1.x, e2.corner1.y, e2.corner1.elevation * Z_SCALE], dtype=numpy.float32) region_center = numpy.array([center.x, center.y, center.elevation * Z_SCALE]) for end1, edge1, edge2 in [(region_center, e1_0, e1_1), (region_center, e2_0, e2_1)]: end2 = v3mid(edge1, edge2) midpt = v3mid(end1, end2) midpt = scene.mapgen_coords_to_sirikata(midpt, terrain) kata_pt1 = scene.mapgen_coords_to_sirikata(end1, terrain) kata_pt2 = scene.mapgen_coords_to_sirikata(end2, terrain) scale = v3dist(kata_pt1, kata_pt2) / 2 m = scene.SceneModel(ROAD_PATH, x=float(midpt[0]), y=float(midpt[1]), z=float(midpt[2]), scale=scale, model_type='road') kataboundmin, kataboundmax = scene.sirikata_bounds(m.boundsInfo) scenemin = kataboundmin * scale + midpt scenemax = kataboundmax * scale + midpt xmid = (scenemax[0] - scenemin[0]) / 2.0 + scenemin[0] road_edge1 = numpy.array([xmid, scenemin[1], scenemin[2]], dtype=numpy.float32) road_edge2 = numpy.array([xmid, scenemax[1], scenemin[2]], dtype=numpy.float32) midv3 = Vec3(midpt[0], midpt[1], midpt[2]) src = Vec3(road_edge2[0], road_edge2[1], road_edge2[2]) src -= midv3 src_copy = Vec3(src) target = Vec3(kata_pt1[0], kata_pt1[1], kata_pt1[2]) target -= midv3 cross = src.cross(target) w = math.sqrt(src.lengthSquared() * target.lengthSquared()) + src.dot(target) q = Quat(w, cross) q.normalize() orig_up = q.getUp() orig_up.normalize() edge1_kata = scene.mapgen_coords_to_sirikata(edge1, terrain) edge2_kata = scene.mapgen_coords_to_sirikata(edge2, terrain) new_up = normal_vector(kata_pt1, edge1_kata, edge2_kata) new_up = Vec3(new_up[0], new_up[1], new_up[2]) rotate_about = orig_up.cross(new_up) rotate_about.normalize() angle_between = orig_up.angleDeg(new_up) r = Quat() r.setFromAxisAngle(angle_between, rotate_about) r.normalize() q *= r q.normalize() m.orient_x = q.getI() m.orient_y = q.getJ() m.orient_z = q.getK() m.orient_w = q.getR() numroads += 1 json_out.append(m.to_json()) print 'Generated (%d) road objects' % numroads
def generate(self, Params, baseFlair=[]): # defines a "branch" as a list of BranchNodes and then calls branchfromNodes # Creates a scaled length,width, height geometry to be later # otherwise can not maintain UV per unit length (if that's desired) # returns non-rotated, unpositioned geom node # branchlen = Params['L'] # branchSegs = Params['nSegs'] Params.update({'iSeg': 0}) # Base flair: nice to flair out the first segment on a "trunk" branch sometimes if baseFlair: bff = baseFlair else: bff = 1 rootPos = Vec3( 0, 0, 0 ) # + self.PositionFunc(**Params) #add noise to root node; same as others in loop rootNode = BranchNode._make([ rootPos, bff * self.R0, Vec3(0, 0, 0), Quat(), _uvScale, 0, self.length ]) # initial node # make a starting node flat at 0,0,0 self.nodeList = [rootNode ] # start new branch list with newly created rootNode prevNode = rootNode for i in range(1, self.nSeg + 1): # start a 1, 0 is root node, now previous Params.update({'iSeg': i}) newPos = self.PositionFunc(**Params) fromVec = newPos - prevNode.pos # point dL = ( prevNode.deltaL + fromVec.length() ) # cumulative length accounts for off axis node lengths; percent of total branch length radius = self.RadiusFunc( position=dL / self.length, **Params ) # pos.length() wrt to root. if really curvy branch, may want the sum of segment lengths instead.. # MOVE TO UVfunc # perim = 2*_polySize*radius*sin(pi/_polySize) # use perimeter to calc texture length/scale # if going to use above perim calc, probably want a high number of BranchNodes to minimuze the Ushift at the nodes perim = 1 # integer tiling of uScale; looks better; avoids U shifts at nodes UVcoord = ( _uvScale[0] * perim, rootNode.texUV[1] + dL * float(_uvScale[1]) ) # This will keep the texture scale per unit length constant ## newNode = BranchNode._make([ newPos, radius, fromVec, rootNode.quat, UVcoord, dL, self.length - dL ]) # i*Lseg = distance from root self.nodeList.append(newNode) prevNode = newNode # this is now the starting point on the next iteration # sends the BranchNode list to the drawBody function to generate the # actual geometry for i, node in enumerate(self.nodeList): # if i == 0: isRoot = True # else: isRoot = False # if i == len(nodeList)-1: keepDrawing = True # else: self.drawBody(node.pos, node.quat, node.radius, node.texUV) return self.nodeList
def generate_roads(models, terrain, map, json_out): numroads = 0 for center in progress.bar(map.centers.values(), label='Generating roads... '): road_edges = [ e for e in center.edges if e.is_road and e.corner0 is not None and e.corner1 is not None ] if len(road_edges) != 2: continue e1, e2 = road_edges e1_0 = numpy.array( [e1.corner0.x, e1.corner0.y, e1.corner0.elevation * Z_SCALE], dtype=numpy.float32) e1_1 = numpy.array( [e1.corner1.x, e1.corner1.y, e1.corner1.elevation * Z_SCALE], dtype=numpy.float32) e2_0 = numpy.array( [e2.corner0.x, e2.corner0.y, e2.corner0.elevation * Z_SCALE], dtype=numpy.float32) e2_1 = numpy.array( [e2.corner1.x, e2.corner1.y, e2.corner1.elevation * Z_SCALE], dtype=numpy.float32) region_center = numpy.array( [center.x, center.y, center.elevation * Z_SCALE]) for end1, edge1, edge2 in [(region_center, e1_0, e1_1), (region_center, e2_0, e2_1)]: end2 = v3mid(edge1, edge2) midpt = v3mid(end1, end2) midpt = scene.mapgen_coords_to_sirikata(midpt, terrain) kata_pt1 = scene.mapgen_coords_to_sirikata(end1, terrain) kata_pt2 = scene.mapgen_coords_to_sirikata(end2, terrain) scale = v3dist(kata_pt1, kata_pt2) / 2 m = scene.SceneModel(ROAD_PATH, x=float(midpt[0]), y=float(midpt[1]), z=float(midpt[2]), scale=scale, model_type='road') kataboundmin, kataboundmax = scene.sirikata_bounds(m.boundsInfo) scenemin = kataboundmin * scale + midpt scenemax = kataboundmax * scale + midpt xmid = (scenemax[0] - scenemin[0]) / 2.0 + scenemin[0] road_edge1 = numpy.array([xmid, scenemin[1], scenemin[2]], dtype=numpy.float32) road_edge2 = numpy.array([xmid, scenemax[1], scenemin[2]], dtype=numpy.float32) midv3 = Vec3(midpt[0], midpt[1], midpt[2]) src = Vec3(road_edge2[0], road_edge2[1], road_edge2[2]) src -= midv3 src_copy = Vec3(src) target = Vec3(kata_pt1[0], kata_pt1[1], kata_pt1[2]) target -= midv3 cross = src.cross(target) w = math.sqrt( src.lengthSquared() * target.lengthSquared()) + src.dot(target) q = Quat(w, cross) q.normalize() orig_up = q.getUp() orig_up.normalize() edge1_kata = scene.mapgen_coords_to_sirikata(edge1, terrain) edge2_kata = scene.mapgen_coords_to_sirikata(edge2, terrain) new_up = normal_vector(kata_pt1, edge1_kata, edge2_kata) new_up = Vec3(new_up[0], new_up[1], new_up[2]) rotate_about = orig_up.cross(new_up) rotate_about.normalize() angle_between = orig_up.angleDeg(new_up) r = Quat() r.setFromAxisAngle(angle_between, rotate_about) r.normalize() q *= r q.normalize() m.orient_x = q.getI() m.orient_y = q.getJ() m.orient_z = q.getK() m.orient_w = q.getR() numroads += 1 json_out.append(m.to_json()) print 'Generated (%d) road objects' % numroads
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
def getViewQuat(self): quat = Quat() quat.setHpr(self.getViewHpr())