##THE ALL PURPOSE PROGRAMMING LIBRARY## #NOW WORKS WITH RUN-TIMES! ############################################################### #APPLE3.py #Original Author: Jordan Williamson, July 22, 2008 #Last edited: Tues July 22, 2008 ############################################################### #BANANA.py #Current Author: Sunjay Varma. (Updating, Optimizing, Adding, Hosting) #March, 2010 #Check out www.sunjay-varma.com for the latest updates. (Scripts section, under Resources.) ############################################################### #As raider said: #I don't mind how you use this. Credit is nice, games are nicer. ^^ #There are many modules used in this module. import types,math,GameLogic,random,PhysicsConstraints,Mathutils,Rasterizer from types import * from math import * from GameLogic import * from random import * from PhysicsConstraints import * from Mathutils import * from Rasterizer import * ##=======================Variables==========================================## sqrt = math.sqrt sin = math.sin cos = math.cos pi = math.pi e = math.e #The base orientation for an object. BASEORI = Matrix(*[[1,0,0],[0,1,0],[0,0,1]]) #The base linear velocity for an object. BASELINV = Vector([0,0,0]) #A dictionary with the axis names associated with their coresponding numbers. AXISDICT = {0:'x',1:'y',2:'z'} #The list of objects in the current scene (This is for quick access. For advanced usage, see function: getObjects()) oblist = getCurrentScene().objects ##======================Mouse/Screen Functions=============================## #Just so you don't always have to import Rasterizer to do this. Defaults to just show the mouse. def ShowMouse(n=1): showMouse(n) #Gets the screens length and width. Returns [Width,Length] def getScreen(): return [getWindowWidth(),getWindowHeight()] ##Uses a mouse over sensor to move an object## def mouseCursor(obj,cont,mouseOverSensorName): mPosi = cont.sensors[mouseOverSensorName] cursorPosi = mPosi.raySource obj.localPosition = cursorPosi #-------------------------MouseLook------------------------------------------# ##Very easy/simple/efficient mouselook## ##The old mouselook was sort of ineffecient. So I added raider's mouselook. # #This should be attached to a camera. The camera should have a mouse movement sensor #The camera's parent should be the character. #This is great for FPS games #################### ##Raider's Mouselook### 2 OBJECT VARIANT ## #################### #By Aiden John Sibley aka Raiderium Neo # # I don't mind how you use this. Credit is nice, games are nicer. ^^ # #Note: Always rotate the parent object (the box); rotating the camera object #does not change the way the box rotates, and control will be #skewed. #If you don't understand what I mean, use ALT+R on the camera object, #then don't rotate it from that orientation. def TwoObjMouselook(cont,mouseSensorName,xlimit=90,sensitivity=0.2): own = cont.owner par = own.parent mouse = cont.sensors[mouseSensorName] #Get the screen's middle point and the mouse position mid = Vector(getWindowWidth(),getWindowHeight())/2 mpos = Vector(mouse.position) #Initialise stuff if not "ml_angle" in own: #Record the initial local orientation of the object own["ml_own_mat"] = Matrix(*own.localOrientation).invert() own["ml_par_mat"] = Matrix(*par.localOrientation).invert() #Init the view angle own["ml_angle"] = Vector(0,0) #Ignore the mouse position on the first frame. mpos = mid #Get mouse position offset from the middle of the screen, and apply sensitivity. own["ml_angle"] += (mpos - mid)*sensitivity #Limit x (up/down) angle own["ml_angle"][1] = max(min(own["ml_angle"][1],xlimit),-xlimit) #Generate rotation matrices for the up/down, left/right viewing angles xmat = RotationMatrix(-own["ml_angle"][1],3,"x") zmat = RotationMatrix(-own["ml_angle"][0],3,"y") #Add the up/down to the Own object, add left/right to parent own.localOrientation = (xmat*own["ml_own_mat"]).invert() par.localOrientation = (zmat*own["ml_par_mat"]).invert() #Set mouse position to the middle of the screen. setMousePosition(int(mid[0]),int(mid[1])) #This just orients the object to where ever the user moves the mouse. #Needs a mouse movement sensor def OneObjectMouselook(cont,mouseSensorName,xlimit=90,sensitivity=0.2): #################### #Raider's Mouselook# #################### #By Aiden John Sibley aka Raiderium Neo # # I don't mind how you use this. Credit is nice, games are nicer. ^^ own = cont.owner mouse = cont.sensors[mouseSensorName] #Get the screen's middle point and the mouse position mid = Vector(getWindowWidth(),getWindowHeight())/2 mpos = Vector(mouse.position) #Initialise stuff if not "ml_angle" in own: #Record the initial local orientation of the object own["ml_start_mat"] = Matrix(*own.localOrientation).invert() #Init the view angle own["ml_angle"] = Vector(0,0) #Ignore the mouse position on the first frame. mpos = mid #Get mouse position offset from the middle of the screen, and apply sensitivity. own["ml_angle"] += (mpos - mid)*sensitivity #Limit x (up/down) angle own["ml_angle"][1] = max(min(own["ml_angle"][1],xlimit),-xlimit) #Generate rotation matrices for the up/down, left/right viewing angles xmat = RotationMatrix(-own["ml_angle"][1],3,"x") zmat = RotationMatrix(-own["ml_angle"][0],3,"y") #Combine them and add them to the initial orientation omat = (xmat*zmat)*own["ml_start_mat"] #Set the local object matrix own.localOrientation = omat.invert() #Set mouse position to the middle of the screen. setMousePosition(int(mid[0]),int(mid[1])) #------------------------------MouseLookEnd------------------------------------------------------# ##Mouse-controlled forces## ##Acts on X,Z axes## def mouseForceX(obj,cont,SCALE,mouseSensName,WName=None,LName=None,reset=1,local=[1,1]): import Rasterizer as r cont = GameLogic.getCurrentController() own = cont.owner mouse = cont.sensors[mouseSensName] SCALE[0] = float(SCALE[0])/1000 SCALE[1] = float(SCALE[1])/1000 pos = mousePos(cont,mouseSensName,SCALE) if LName: lmotion = cont.actuators[LName] lmotion.force = [pos[0],0,0] lmotion.useLocalForce = local[0] cont.activate(lmotion) if WName: wmotion = cont.actuators[WName] wmotion.force = [0,0,pos[1]] wmotion.useLocalForce = local[1] cont.activate(wmotion) if reset: r.setMousePosition(r.getWindowWidth()/2,r.getWindowHeight()/2) ##Mouse-controlled forces## ##Acts on Y,Z axes## def mouseForceY(obj,cont,SCALE,mouseSensName,WName=None,LName=None,reset=1,local=[1,1]): import Rasterizer as r cont = GameLogic.getCurrentController() own = cont.owner mouse = cont.sensors[mouseSensName] SCALE[0] = float(SCALE[0])/1000 SCALE[1] = float(SCALE[1])/1000 pos = mousePos(cont,mouseSensName,SCALE) if LName: lmotion = cont.actuators[LName] lmotion.force = [0,pos[0],0] lmotion.useLocalForce = local[0] cont.activate(lmotion) if WName: wmotion = cont.actuators[WName] wmotion.force = [0,0,pos[1]] wmotion.useLocalForce = local[1] cont.activate(wmotion) if reset: r.setMousePosition(r.getWindowWidth()/2,r.getWindowHeight()/2) ##Mouse-controlled forces## ##Acts on X,Y axes## def mouseForceZ(obj,cont,SCALE,mouseSensName,WName=None,LName=None,reset=1,local=[1,1]): import Rasterizer as r cont = GameLogic.getCurrentController() own = cont.owner mouse = cont.sensors[mouseSensName] SCALE[0] = float(SCALE[0])/1000 SCALE[1] = float(SCALE[1])/1000 pos = mousePos(cont,mouseSensName,SCALE) if LName: lmotion = cont.actuators[LName] lmotion.force = [pos[0],0,0] lmotion.useLocalForce = local[0] cont.activate(lmotion) if WName: wmotion = cont.actuators[WName] wmotion.force = [0,pos[1],0] wmotion.useLocalForce = local[1] cont.activate(wmotion) if reset: r.setMousePosition(r.getWindowWidth()/2,r.getWindowHeight()/2) ##Returns mouse position in screen coordinates## ##REQUIRED for mouse related functions## def mousePos(cont,mouseSensName,SCALE=[1,1],reset=0): import Rasterizer as r mouse = cont.sensors[mouseSensName] x = (r.getWindowWidth()/2-mouse.getXPosition())*-SCALE[0] y = (r.getWindowHeight()/2-mouse.getYPosition())*-SCALE[1] if reset: r.setMousePosition(r.getWindowWidth()/2,r.getWindowHeight()/2) return(x,y) def MultMat(a,b): mat = [] for r in range(len(a)): row = [] for c in range(len(b)): if len(a) == 2: row.append(a[r][0]*b[0][c]+a[r][1]*b[1][c]) elif len(a) == 3: row.append(a[r][0]*b[0][c]+a[r][1]*b[1][c]+a[r][2]*b[2][c]) else: # len(a) == 4 row.append(a[r][0]*b[0][c]+a[r][1]*b[1][c]+a[r][2]*b[2][c]+a[r][3]*b[3][c]) mat.append(row) return mat def draw(*args): try: drawLine(*args) except: raise KeyError('Something went wrong while trying to draw your line.\nPlease check your parameters') #First object draws a line to the second object, and so on..... #the factor is the offset that will be added to the starting vector. def drawLineToLast(obs,factor=[0,0,0],color=[0,0,0]): if len(obs) <= 1: return for obj in obs: if type(obj) != ListType: obj = obj.worldPosition drawTo = obs[0] #Default for ob in obs[1:]: drawLine(listAddition(ob,factor),drawTo,color) drawTo = ob ##======================Object Functions=============================## ##Simulates aerodynamics (like papers blowing in the wind and airplanes)## ##Asks for a AERODYNAMIC TENSOR, which is a 3x3 matrix describing the## ##basic surface areas of the object## def Aerodynamics(ob,tensor,windSpeed): orient = ob.worldOrientation #windSpeed=listTimesMat(windSpeed,orient) dotX = VEC_dot(windSpeed,orient[0]) dotY = VEC_dot(windSpeed,orient[1]) dotZ = VEC_dot(windSpeed,orient[2]) newSpeedX = listTimesNum(windSpeed,abs(dotX)) newSpeedY = listTimesNum(windSpeed,abs(dotY)) newSpeedZ = listTimesNum(windSpeed,abs(dotZ)) ########################################## forceXX = listTimesNum(newSpeedX,tensor[0][0]) forceXY = listTimesNum(newSpeedX,tensor[0][1]) forceXZ = listTimesNum(newSpeedX,tensor[0][2]) forceXZ = [0,0,VEC_length(forceXZ)] forceXY = [0,VEC_length(forceXY),0] forceYX = listTimesNum(newSpeedY,tensor[1][0]) forceYY = listTimesNum(newSpeedY,tensor[1][1]) forceYZ = listTimesNum(newSpeedY,tensor[1][2]) forceYX = [VEC_length(forceYX),0,0] forceYZ = [0,0,VEC_length(forceYZ)] forceZX = listTimesNum(newSpeedZ,tensor[2][0]) forceZY = listTimesNum(newSpeedZ,tensor[2][1]) forceZZ = listTimesNum(newSpeedZ,tensor[2][2]) forceZX = [VEC_length(forceZX),0,0] forceZY = [0,VEC_length(forceZY),0] ########################################## forceX = listAddition(forceXX,forceYX) forceX = listAddition(forceX,forceZX) forceY = listAddition(forceXY,forceYY) forceY = listAddition(forceY,forceZY) forceZ = listAddition(forceXZ,forceYZ) forceZ = listAddition(forceZ,forceZZ) netForce = listAddition(forceX,forceY) netForce = listAddition(netForce,forceZ) setLinV(ob,netForce,1) ##Super simple bouyancy## #Asumes that object is already under the surface def bouyancy(ob,waterDensity,obDensity,obwidth=0): currentX, currentY, Z = ob.worldPosition obPos = Z-obwidth densDiff = float(obDensity)-float(waterDensity) if densDiff < 0: ob.applyImpulse(ob.worldPosition,[currentX,currentY*0.0177,ob.mass/(obDensity*3)]) else: #ob.applyImpulse([0,0,0],[0,0,densDiff*0.017]) pass damping(ob,waterDensity*15) ##Makes a breakable hinge constraint## def breakableHingeConstraint(ob,root,pivot,axis,threshold): own = ob if not hasattr(own,'const'): own['const'] = 0 if not hasattr(own,'broken'): own['broken'] = 0 if not own['const'] and not own['broken']: own['const'] = hingeConstraint(own,root,pivot,axis) accel = getAcceleration(own) if accel.magnitude > threshold: removeConstraint(own.const) own.const = 0 own.broken = 1 ##Breakable Point-2-point constraint## def breakablep2pConstraint(ob,root,pivot,threshold): own = ob if not own.has_key('const'): own['const'] = 0 if not own.has_key('broken'): own['broken'] = 0 if not own.has_key('const') and not own.broken: own['const'] = p2pConstraint(own,root,pivot) accel = getAcceleration(own) if accel.magnitude > threshold: removeConstraint(own['const']) own['const'] = 0 own['broken'] = 1 ##Breakable Rigid body constraint## def breakableRagdollConstraint(ob,root,position,threshold,sizeIndex=2): own = ob if not hasattr(own,'const'): own.const = 0 if not hasattr(own,'broken'): own.broken = 0 if not own.const and not own.broken: own.const = ragdollConstraint(own,root,position,sizeIndex) accel = getAcceleration(own) if accel.magnitude > threshold: removeConstraint(own.const) own.const = 0 own.broken = 1 ##Non-default Z-axis collision buffer## ##keeps objects above the given ground plane## ##keep RA and CA defaulted## def collisionBuffer(ob,groundPlane,RA=1,CA=0): pos = ob.worldPosition ground = groundPlane groundpos = ground.worldPosition resetAmount = RA reset = [RA,RA,RA] newpos = [groundpos[0]+reset[0],groundpos[1]+reset[1],groundpos[2]+reset[2]] clipamount = CA if pos[2] < groundpos[2]+CA: ob.localPosition = [pos[0],pos[1],groundpos[2]+RA] ##Sets one object at the position of the second## def copyPosition(ob,ob2): ob.localPosition = ob2.worldPosition ##Damping## ##damp should be between 0 and 100## def damping(ob,damp): vel = getLinV(ob) negVel = listTimesNum(vel,-1) totalDamp = listTimesNum(negVel,damp/100.0) ob.applyImpulse(ob.worldPosition,totalDamp) ##Explosions## def explode(ob,strength,ignore=[],vertical=0,calc='linear',falloff=1): if ob not in ignore: ignore.append(ob) sc = GameLogic.getCurrentScene() for own in sc.objects: if own.mass != 0 and own not in ignore: vecO = Vector(own.worldPosition) pos = Vector(owner.worldPosition) diff = Vector(vec0-pos) if diff.magnitude > 0 and diff.magnitude <= falloff*strength: if calc == 'quad' and not retn: force = diff*(strength/diffLen**2) force[2] = force[2]+vertical own.applyImpulse([0,0,0],force) elif calc == 'linear' and not retn: force = diff*(strength/diffLen) force[2] = force[2]+vertical own.applyImpulse([0,0,0],force) ##Explode Object## ## WARNING: This is not done yet. For any additions to this ## please visit: sunjay-varma.com and hit "Contact Us" def explodeOb(ob,speed,amplitude,length,vertical=0,calc='radial',falloff=1): import time names = [] owner = ob if not ob.has_key('TIME'): ob['TIME'] = time.clock() elapsedT = (time.clock()-ob['TIME'])*speed x,y,z = owner.worldPosition for vert in getVertexArray(owner.meshes[0]): pos = vert.getXYZ() dist = sqrt((pos[0]-x)**2+(pos[1]-y)**2+(pos[2]-z)**2) if calc == 'radial': force = Vector([sin((dist/length)+elapsedT*pi/180*90)*amplitude]*3) force[2] = force[2]+vertical vert.setXYZ(force) elif calc == 'linear': force = listTimesNum(VEC_normalize(diff),(strength/diffLen)) force[2] = force[2]+vertical #Senses collisions. Good for fast moving, static objects. def getCollision(obj): opos = Vector(obj.position) if not obj.has_key("PREV_POS"): obj["PREV_POS"] = opos colray = obj.rayCast(opos, obj["PREV_POS"], 0,"") if colray[0]: cpos = Vector(colray[1]) cnor = Vector(colray[2]) obj.position = cpos+cnor*0.001 obj["PREV_POS"] = Vector(own.position) ##Fixed hinge constraint## ##from physics demos## def fixedConstraint(own,ob): oid = own.getPhysicsId() rid = ob.getPhysicsId() const1 = PhysicsConstraints.createConstraint(oid,rid,2,0,0,0,1,0,0) const2 = PhysicsConstraints.createConstraint(oid,rid,2,0,0,0,0,1,0) return [const1.getConstraintId(),const2.getConstraintId()] ##Gets acceleration of object, in vector form## def getAcceleration(own): if not own.has_key('vel'): own['vel'] = "[0.0,0.0,0.0]" old = eval(own['vel']) vel = getLinV(own) own['vel'] = str(vel) accel = listSubtraction(eval(own['vel']),old) return Vector(accel) ##Gets the total force of an object## def getForce(ob): return listTimesNum(getAcceleration(ob),ob.mass) ##Returns the force of gravitation## def getGravity(own,constant): obs = initGame()['obs'] totalforce = 0,0,0 for ob in obs: if ob.mass != 0 and ob.name != own.name: dist = own.getDistanceTo(ob) if dist > 0: pos1 = own.worldPosition pos2 = ob.worldPosition mass1 = own.mass mass2 = ob.mass force = constant*((mass1*mass2)/(dist*dist)) diff = VEC_normalize(listSubtraction(pos2,pos1)) force = listTimesNum(diff,force) totalforce = listAddition(force,totalforce) return totalforce ##Gets the kinetic energy of an object## def getKineticEnergy(ob): return (getSpeed(ob)**2)*(ob.mass*0.5) ##Returns the "thickness" of the object, or## ##the radius of the smallest sphere that can## ##contain all the vertices of the object## ##MBD=maximum bounds distance def getMBD(ob): verts = getVertexPositionArray(ob.meshes[0]) noDoubles = removeDoubles(verts) max = 0 i = 0 for vert in noDoubles: distSquared = getDistanceSquared(vert,[0,0,0]) print distSquared if distSquared > max: max = distSquared i += 1 return math.sqrt(max) ##Returns the "thickness" of the object, or## ##the square of the radius of the smallest## ##sphere that can contain all the vertices## ##of the object## ##MBDS=maximum bounds distance squared def getMBDS(ob): mesh = ob.meshes[0] #print dir(mesh) verts = getVertexPositionArray(mesh) noDoubles = removeDoubles(verts) max = 0 i = 0 for vert in noDoubles: distSquared = getDistanceSquared(vert,[0,0,0]) if distSquared > max: max = distSquared i += 1 return max ##Gets the potential energy of an object with respect to a position and a force## def getPotentialEnergy(ob,position,force): return ob.mass*DistanceToPoint(ob,position)*VEC_length(force) ##Gets the momentum of the object## def getMomentum(ob): return VEC_length(ob.getLinearVelocity())*ob.mass ##Gets nearest object's distance away from given object## def getNearestDistance(obj,dynamicOnly=0): distances=[] for o,d in getObjectDistances(obj,dynamicOnly).iteritems(): distances.append(d) nearestDistance = min(distances) return nearestDistance ##Gets nearest object (replaces near sensor) If you just want to get the nearest object leave prop as None## ## obj = the object to start from. prop = prop objects must have to get checked. maxdist = maximum distance to look. ## dynamicOnly = get dynamic objects only. oblist = the object list to look through. (leave as None to look through all objects.) ## ignore = a list of objects and things to ignore. ##Note: Script will not return the object defined as obj. def getClosest(obj,prop=None,maxdist=None,dynamicOnly=0,oblist=None,ignore=set()): closest = None closest_dist = maxdist objects = oblist or GameLogic.getCurrentScene().objects ignore = set(ignore) ignore.update([obj]) for ob in objects: if (not prop or prop in ob) and (not dynamicOnly or ob.mass > 0) and ob not in ignore: dist = obj.getDistanceTo(ob) if closest_dist is None or dist < closest_dist: closest = ob closest_dist = dist return(closest) ##Gets the distances of all the objects in the scene (optionally, only dynamic ones)## def getObjectDistances(obj,dynamicOnly=0,ignore=[]): obs = initGame()['obs'] retn = {} for ob in obs: if ob != obj: if dynamicOnly: if ob.mass != 0 and ob not in ignore: retn[ob]=(ob.getDistanceTo(obj)) else: retn[ob]=(ob.getDistanceTo(obj)) return retn ##Returns three vectors that correspond to the## ##orientation matrix of an object## def getOrientationAxes(ob): x,y,z = ob.worldOrientation neworiX = [x[0],-x[1],-x[2]] neworiY = [-y[0],y[1],-y[2]] neworiZ = [-z[0],-z[1],z[2]] return [neworiX,neworiY,neworiZ] ##Gets the absolute speed of an object## def getSpeed(ob): return Vector(ob.getLinearVelocity()).magnitude ##Gets the square of the speed of an object## ##Runs faster than calling getSpeed(), doesn't use sqr root## ##can be used for comparisons between speeds## def getSpeedSquared(ob): return Vector(ob.getLinearVelocity()).magnitude**2.0 ##Returns the angle between two vectors## def getVecAngle(vec1,vec2): return invCos(VEC_dot(vec1,vec2)) ##Returns a list of vert objects in a mesh## def getVertexArray(mesh,numMaterials=1): list = [] for material in range(numMaterials): vertices = mesh.getVertexArrayLength(material) for v in range(vertices): vert = mesh.getVertex(material,v) list.append(vert) return list ##Returns a list of the positions of all the "vertices" in a mesh## def getVertexPositionArray(mesh,numMaterials=1): list = [] for material in range(numMaterials): vertices = mesh.getVertexArrayLength(material) for v in range(vertices): vertPos = mesh.getVertex(material,v).getXYZ() list.append(vertPos) return list ##Gravitation## ##gravitates to ALL dynamic objects## def gravitation(own,constant): obs = initGame()['obs'] totalforce = 0,0,0 for ob in obs: if ob.getPhysicsId() != 0 and ob.name != own.name: dist = own.getDistanceTo(ob) if dist > 0: pos1 = own.worldPosition pos2 = ob.worldPosition mass1 = own.mass mass2 = ob.mass force = constant*((mass1*mass2)/(dist*dist)) diff = VEC_normalize(listSubtraction(pos2,pos1)) force = listTimesNum(diff,force) totalforce = listAddition(force,totalforce) own.applyImpulse(own.worldPosition,listTimesNum(totalforce,0.177)) ##Gravitation## ##gravitates to ALL dynamic objects## ##allows you to acount for object's thicknesses## def thickGravitation(own,constant): obs = initGame()['obs'] totalforce = Vector(0,0,0) for ob in obs: if ob.getPhysicsId() != 0 and ob.getName() != own.getName(): dist = own.getDistanceTo(ob)-ob.radius if dist > 0: pos1 = own.worldPosition pos2 = ob.worldPosition mass1 = own.mass mass2 = ob.mass force = constant*((mass1*mass2)/(dist*dist)) diff = VEC_normalize(listSubtraction(pos2,pos1)) force = listTimesNum(diff,force) totalforce = listAddition(force,totalforce) own.applyImpulse([0,0,0],listTimesNum(totalforce,0.177)) ##Gravitation## ##gravitates to ONE dynamic object## def gravitateOb(own,obj2,constant): ob = obj2 dist = own.getDistanceTo(ob) if dist > 0: pos1 = own.worldPosition pos2 = ob.worldPosition if not own.mass: mass1 = 1 elif hasattr(own,'Mass'): mass1 = own.Mass else: mass1 = own.mass if not ob.mass: mass2 = 1 elif hasattr(ob,'Mass'): mass2 = ob.Mass else: mass2 = ob.mass force=constant*((mass1*mass2)/(dist*dist)) diff = VEC_normalize(listSubtraction(pos2,pos1)) totalforce = listTimesNum(diff,force) own.applyImpulse([0,0,0],listTimesNum(totalforce,0.177)) ##Hinge constraint## ##from the physics demos## def hingeConstraint(own,ob,pivotInA,axisInA): oid = own.getPhysicsId() rid = ob.getPhysicsId() const = PhysicsConstraints.createConstraint(oid,rid,2,pivotInA[0],pivotInA[1],pivotInA[2],axisInA[0],axisInA[1],axisInA[2]) return const.getConstraintId() ##Applies a force, but without needing a motion actuator## ##NOTE: may have errors if framerate changes drastically## ##NOTE: accelerates as long as is called, so don't call for long## def impulseForce(ob,force,point=[0,0,0]): ob.applyImpulse(point,listTimesNum(force,0.0177)) ##Applies torque, but without needing a motion actuator## ##NOTE: may have errors if framerate changes drastically## ##NOTE: accelerates as long as is called, so don't call for long## def impulseSpin(ob,force,local=0): ob.applyTorque(listTimesNum(force,-0.0177),local) #Applies rotation def impulseRot(ob,force,local=0): ob.applyRotation(listTimesNum(force,-0.0177),local) #Set an objects linV. def setLinV(ob,linV=[0,0,0],local=1,axis='xyz'): final = getLinV(ob) if 'x' in axis: final[0] = linV[0] if 'y' in axis: final[1] = linV[1] if 'z' in axis: final[2] = linV[2] ob.setLinearVelocity(final,local) #Gets the Linear Velocity of an object def getLinV(ob,local=0): return ob.getLinearVelocity(local) #Gets the dimensions of an object based on the mesh. #returns a list [width,length,height] def getDimensions(obj): verts = getVertexArray(obj.meshes[0]) x1 = y1 = z1 = x2 = y2 = z2 = None for vert in verts: x,y,z = vert.getXYZ() if not x2 or x > x2: x2 = x if not x1 or x < x1: x1 = x if not y2 or y > y2: y2 = y if not y1 or y < y1: y1 = y if not z2 or z > z2: z2 = z if not z1 or z < z1: z1 = z return [round(x2-x1,2),round(y2-y1,2),round(z2-z1,2)] #Gets the volume of an object. Returns float. def getVolume(obj): x,y,z = getDimensions(obj) return float(float(x)*float(y)*float(z)) #Gets the Angular Velocity. def getAngV(ob): return ob.getAngularVelocity() #Sets the Angular Velocity. def setAngV(ob,angV=[0,0,0],local=1,axis='xyz'): final = getAngV(ob) if 'x' in axis: final[0] = angV[0] if 'y' in axis: final[1] = angV[1] if 'z' in axis: final[2] = angV[2] ob.setAngularVelocity(final,local) #Gets the objects orientation def getOri(ob): return ob.worldOrientation #Sets the objects orientation. def setOri(ob,ori=BASEORI): ob.localOrientation = ori #Impulse def impulse(ob,point,force): ob.applyImpulse(point,force) ##Returns true if number is within range of a second number## def inRange(number,targetNumber,Range): if number == targetNumber: return True elif number <= targetNumber+Range and number >= targetNumber-Range: return True else: return False ##Converts an integer to a list of 1s and 0s## def intTobinary(integer): glaba=[1] binary=[] N=0 while integer-2**(N+1) >= 0: N += 1 glaba.append(2**N) glaba.reverse() for num in glaba: if integer-num>=0: integer = integer-num binary.append(1) else: binary.append(0) return binary ##cos^-1## def invCos(num): return math.degrees(math.acos(num)) ##Returns true if movement## def isMoving(ob,speed=0): if getSpeed(ob) >= speed: return True else: return False ##Magnetism## def magnetism(own,k,prop=None): obs = initGame()['obs'] pos1 = own.worldPosition force = [0,0,0] for ob in obs: if not prop or ob.has_key(prop): pos2 = ob.worldPosition dist = own.getDistanceTo(ob) if dist: diff = VEC_normalize(listSubtraction(pos1,pos2)) const = k*own.charge*ob.charge/dist f = listTimesNum(diff,const) force = listAddition(force,f) own.applyImpulse(own.worldPosition,force) ##Animates a mesh to wave.## ##Mode can be 'radial','linearX','linearY', or 'linearXY'## ##Use recalculatemesh to recalculate the physics mesh. ##WARNING: recalculation can cause slow downs. def meshWave(ob,speed,amplitude,length,mode='radial',x=0,y=0,AX=1,AY=1,recalulatemesh=True): import time if not ob.has_key('init'): ob['init'] = time.clock() elapsedT = (time.clock()-ob['init'])*speed verts = getVertexArray(ob.meshes[0]) if not ob.has_key('init'): ob['init'] = 1 for vert in verts: pos = vert.getXYZ() if mode == 'radial': dist = sqrt((pos[0]-x)**2+(pos[1]-y)**2) z = sin((dist/length)+elapsedT*pi/180*90)*amplitude vert.setXYZ([pos[0],pos[1],z]) elif mode == 'linearX': z = sin((pos[0]/length)+elapsedT*pi/180*90)*amplitude vert.setXYZ([pos[0],pos[1],z]) elif mode == 'linearY': z = sin((pos[1]/length)+elapsedT*pi/180*90)*amplitude vert.setXYZ([pos[0],pos[1],z]) elif mode == 'linearXY': z = sin((pos[0]/length)+elapsedT*pi/180*90)*cos((pos[1]/length)+elapsedT*pi/180*90)*amplitude vert.setXYZ([pos[0],pos[1],z]) if recalulatemesh: ob.reinstancePhysicsMesh() ##Rotates an object to a ray's hit object's normal## ##useful for bullet holes## def normalOrientate(obj,raySensor): obj.localOrientation = (MAT_trackvector(raySensor.hitNormal), [0.0,0.0,01.0]) ##Predicts an object's position a given time into the future## def predictedPosition(ob,time): vel = ob.getLinearVelocity() pos = ob.worldPosition newPos = listTimesNum(listAddition(pos,vel),time) return newPos ##Point-2-point constraint## ##from the physics demos## def p2pConstraint(own,ob2,pivot): physicsid = own.getPhysicsId() physicsid2 = ob2.getPhysicsId() const = PhysicsConstraints.createConstraint(physicsid,physicsid2,1,pivot[0],pivot[1],pivot[2]) return const.getConstraintId() ##Rigid body constraint## ##from the physics demos## def ragdollConstraint(owner,ob,position,sizeIndex=2): root = ob phido = owner.getPhysicsId() phidr = root.getPhysicsId() size = owner.scaling const = PhysicsConstraints.createConstraint(phido,phidr,position[0],position[1],position[2],size[sizeIndex]) return const.getConstraintId() ##Simulates the effect of bullets by a ray sensor## def rayImpulse(mouseOverAnySensor,power): sensor = mouseOverAnySensor hit = sensor.hitObject objpos = hit.worldPosition pos = sensor.hitPosition dir = sensor.rayDirection dir = listTimesNum(dir,power) localpos = [pos[0]-objpos[0],pos[1]-objpos[1],pos[2]-objpos[2]] hit.applyImpulse(localpos,dir) ##Positions an object at the hit point of a ray sensor## def rayPosition(ob,sensor): if sensor.positive: ob.localPosition = sensor.hitPosition ##Using a ray, stretches object to a point## ##NOTE: ob1 must have a property called frm## def rayStretchIpo(ob1,sensor,offset=0): obpos = ob1.worldPosition if sensor.positive: pos = sensor.hitPosition dist = getDistance(obpos,pos) ob1['frm'] = dist+offset else: ob1['frm'] = 0 ##Removes the velocity of an object## ##Basically just sets it all to zero.## def removeVelocity(ob): ob.setLinearVelocity([0,0,0]) ##Repulsion## ##negative gravity, repulses away from ALL dynamic objects (That aren't in ignore)## def repulsion(obj,constant,ignore=set()): obs = initGame()['obs'] totalforce = [0,0,0] ignore = set(ignore) if not obj in ignore: ignore.update(obj) for ob in [o for o in obs if not o in ignore]: if ob.getPhysicsId() != 0 and ob.name != own.name: dist = own.getDistanceTo(ob) if dist > 0: pos1 = own.position; pos2 = ob.position; mass1 = own.mass; mass2 = ob.mass; force = constant*((mass1*mass2)/(dist*dist)); diff = VEC_normalize(listSubtraction(pos2,pos1)); force = listTimesNum(diff,force); totalforce = listAddition(force,totalforce); own.applyImpulse([0,0,0],listTimesNum(totalforce,-0.177)); ##Scales an object by given factors, x y and z## ##Note: Doesn't set the scale, multiplies. def scaleObject(ob,factors=[1,1,1]): if not factors[0]: factors[0] = 1 if not factors[1]: factors[1] = 1 if not factors[2]: factors[2] = 1 scale = ob.worldScale ob.localScale = Vector([scale[0]*factors[0],scale[1]*factors[1],scale[2]*factors[2]]) ##Simple shadow. Made by Remi Berthier## ##Copy the object which you want to project the shadow from.## ##Name that copy a combination of: ## ## -the name of the lamp ## +"_"+plane on which your casting the shadow ## +"_"+object your casting from ## An example is "Lamp_Plane_Box"## ##Make sure that the shadow's center is higher than the original's## ##You'll also want to give it a black material## def simpleShadow(own): obs = initGame()['obs'] ownPos = own.worldPosition objectNameList = own.name.split("_",3) light = obs[objectNameList[0]] plane = obs["OB" + objectNameList[1]] parent = obs["OB" + objectNameList[2]] parentPos = parent.worldPosition parentOri = parent.worldOrientation lightPos = light.worldPosition planePos = plane.worldPosition planeN = plane.meshes[0].getVertex(0,0).getNormal() d = lightPos[0]*planeN[0] + lightPos[1]*planeN[1] + lightPos[2]*planeN[2] c = planePos[0]*planeN[0] + planePos[1]*planeN[1] + planePos[2]*planeN[2] - d matrixProjection = [\ [lightPos[0]*planeN[0]+c,planeN[1]*lightPos[0],planeN[2]*lightPos[0],-lightPos[0]*c-lightPos[0]*d],\ [planeN[0]*lightPos[1],planeN[1]*lightPos[1]+c,planeN[2]*lightPos[1],-lightPos[1]*c-lightPos[1]*d],\ [planeN[0]*lightPos[2],planeN[1]*lightPos[2],planeN[2]*lightPos[2]+c,-lightPos[2]*c-lightPos[2]*d],\ [planeN[0],planeN[1],planeN[2],-d]\ ] positionP = [parentPos[0],parentPos[1],parentPos[2],1.0] orientationP = [\ [parentOri[0][0],parentOri[0][1],parentOri[0][2],0.0],\ [parentOri[1][0],parentOri[1][1],parentOri[1][2],0.0],\ [parentOri[2][0],parentOri[2][1],parentOri[2][2],0.0],\ [0.0,0.0,0.0,1.0]\ ] vecPosP = MatMultVec(matrixProjection,positionP) vecOriP = MultMat(matrixProjection,orientationP) newPos = [vecPosP[0]/vecPosP[3],vecPosP[1]/vecPosP[3],vecPosP[2]/vecPosP[3]] newPos = [newPos[0]+planeN[0]*0.05,newPos[1]+planeN[1]*0.05,newPos[2]+planeN[2]*0.050] newOri = [\ [vecOriP[0][0]/vecOriP[3][3],vecOriP[0][1]/vecOriP[3][3],vecOriP[0][2]/vecOriP[3][3]],\ [vecOriP[1][0]/vecOriP[3][3],vecOriP[1][1]/vecOriP[3][3],vecOriP[1][2]/vecOriP[3][3]],\ [vecOriP[2][0]/vecOriP[3][3],vecOriP[2][1]/vecOriP[3][3],vecOriP[2][2]/vecOriP[3][3]]\ ] own.localPosition = newPos own.localOrientation = newOri ##Spring## def spring(ob1,ob2,stiff,length): pos1 = ob1.worldPosition pos2 = ob2.worldPosition diff1 = VEC_normalize(listSubtraction(pos1,pos2)) diff2 = VEC_normalize(listSubtraction(pos2,pos1)) ob1.applyImpulse([0,0,0],listTimesNum(diff2,stiff*0.1*getDistance(pos1,pos2))) ob2.applyImpulse([0,0,0],listTimesNum(diff1,stiff*0.1*getDistance(pos1,pos2))) ##A sprite-type animation script## ##This is Doc Holiday's TileTex5in1 adapted for BANANA## ##A good idea, if this is connected to an Always sensor, would be to## ##delay it to maybe 3 frames, depending on the desired effect## def SpriteAnim(Own,Cont,Matrix,Mode=0,Play=0,Part=-1): from math import floor def setMtx(MtxL): CurrLoc = (Own.CurrMtxLoc-floor(Own.CurrMtxLoc/Own.MtxX)*Own.MtxX,floor(Own.CurrMtxLoc/Own.MtxX)) NewLoc = (MtxL-floor(MtxL/Own.MtxX)*Own.MtxX,floor(MtxL/Own.MtxX)) if Part < Own.MatCount: if Part == -1: CS,CE = (0,Own.MatCount) else: CS,CE = (Part,Part+1) for Mat in range(CS,CE): Mlen = Mesh.getVertexArrayLength(Mat) for Vi in range(0,Mlen): Vertex = Mesh.getVertex(Mat,Vi) uv = Vertex.getUV() uv[0] = (uv[0]-CurrLoc[0]*1.0/Own.MtxX) + NewLoc[0]*1.0/Own.MtxX uv[1] = (uv[1]-CurrLoc[1]*1.0/Own.MtxY) + NewLoc[1]*1.0/Own.MtxY Vertex.setUV(uv) Vi += 1 Own.CurrMtxLoc = MtxL else: print "** WARNING: Part overflow! **" # =================================================== Mesh = Own.meshes[0] Sens = Cont.sensors[0] # Timer zuruecksetzen # ~~~~~~~~~~~~~~~~~~~ Own.Speed = 0 # finde Matrix und setzte Start Variablen # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if not Own.has_key("NL"): Own.MtxX = int(Matrix.split("x")[0]) Own.MtxY = int(Matrix.split("x")[1]) # ~~~~~~~~~~~ Settings Own.First = 1 if not Mode: Own.Mode = 0 else: Own.Mode = Mode Own.CurrMtxLoc = getattr(Own,"StartAt",0) Own.NL = 0 Own.Sleep = 0 if not Play: Own.Play = -1 else: Own.Play = Play #if Part != -1:= -1: # Own.Part = Part Own.MatCount = Mesh.getNumMaterials() # verarbeite Sleep- & PlayLoops # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if not Own.CurrMtxLoc and Own.Mode <=2 and not Own.First: if Own.Sleep: Own.Sleep -= 1 else: if Own.Play > 0: Own.Play -= 1 if not Own.Play: Own.First = 1 if hasattr(Own,"Wait") and not Own.First: Own.Sleep = Own.Wait # verarbeite AnimationsModus # ~~~~~~~~~~~~~~~~~~~~~~~~~~ if Sens.positive and not Own.Sleep and Own.Play: Own.First = 0 if not Own.Mode: # ------------------------------ >> Mode 0 << - Linear Own.NL += 1 if Own.NL == Own.MtxX*Own.MtxY: Own.NL = 0 setMtx(Own.NL) Own.PPR = 1 elif Own.Mode == 1: # --------------------------- >> Mode 1 << - Linear Reverse Own.NL -= 1 if Own.NL == -1: Own.NL = Own.MtxX*Own.MtxY-1 setMtx(Own.NL) Own.PPR = 0 elif Own.Mode == 2: # --------------------------- >> Mode 2 << - Ping Pong if not hasattr(Own,"PPR"): Own.PPR = 1 if Own.PPR: Own.NL += 1 if Own.NL == Own.MtxX*Own.MtxY: Own.NL -= 2 Own.PPR = 0 setMtx(Own.NL) else: Own.NL -= 1 if Own.NL == -1: Own.NL += 2 Own.PPR = 1 setMtx(Own.NL) elif Own.Mode == 3: # --------------------------- >> Mode 3 << - Set Frame if not hasattr(Own,"DFrame"): print "** WARNING: Integer-DFrame Property missing. **" else: if Own.DFrame > Own.MtxX*Own.MtxY-1 or Own.DFrame < 0: print "** WARNING: Wrong DFrame Value! **" elif Own.DFrame != Own.CurrMtxLoc: setMtx(Own.DFrame) elif Own.Mode == 4: # --------------------------- >> Mode 4 << - Random Frame while Own.NL == Own.CurrMtxLoc: Own.NL = floor(Own.MtxX*Own.MtxY*GameLogic.getRandomFloat()) setMtx(Own.NL) ##Ipo-distance Stretch## ##NOTE: ob1 must have a property called frm## def stretchIpo(ob,ob2,offset=0,trackAct=None,diffob=None,factor=1): dist = ob.getDistanceTo(ob2) if not diffob: ob.frm = dist*factor+offset else: diffob.frm = offset+dist*factor if trackAct: trackAct.object = ob2 OnOff(cont,trackAct,1) ##Transporter## ##place can be an object, or list of XYZ coordinates## ##You can decide weather or not you want the exact coordinates by changing the factor. def teleport(ob,place,factor=[0,0,0]): if type(place) is ListType: ob.localPosition = listAddition(place,factor) else: ob.localPosition = listAddition(place.worldPosition,factor) ##UV Scroll## def UVscroll(ob,x,y): mesh = ob.meshes[0] numVerts = mesh.getVertexArrayLength(0) for i in range(numVerts): vert = mesh.getVertex(0,i) uv = vert.getUV() uv[0] = uv[0]+float(x)/1000.0 uv[1] = uv[1]+float(y)/1000.0 vert.setUV(uv) ##Vehicle physics## ##from the physics demos## ##NOTE: chassis MUST have following properties: ## ##int-init,int-cid,float-steer,float-force def vehiclePhysics(chassis,cont,wheelsXYZ,suspensionRestLength,wheelRadius,influence,stiffness,damping,compression,friction): chassis.applyImpulse([0.0,0.0,0.0],[0.0,0.0,0.0]) if (chassis.init == 0): chassis.init = 1 physicsid = chassis.getPhysicsId() vehicle = PhysicsConstraints.createConstraint(physicsid,0,11) chassis.cid = vehicle.getConstraintId() vehicle = PhysicsConstraints.getVehicleConstraint(chassis.cid) attachHeightLocal = wheelsXYZ[2] wheelAttachPosLocal = [wheelsXYZ[0] ,wheelsXYZ[1], attachHeightLocal] wheelAttachDirLocal = [0,0,-1] wheelAxleLocal = [-1,0,0] hasSteering = 1 act0 = cont.actuators["wheel0"] wheel0 = act0.owner vehicle.addWheel(wheel0,wheelAttachPosLocal,wheelAttachDirLocal,wheelAxleLocal,suspensionRestLength,wheelRadius,hasSteering) act1 = cont.actuators["wheel1"] wheel1 = act1.owner wheelAttachPosLocal = [-wheelsXYZ[0] ,wheelsXYZ[1], attachHeightLocal] vehicle.addWheel(wheel1,wheelAttachPosLocal,wheelAttachDirLocal,wheelAxleLocal,suspensionRestLength,wheelRadius,hasSteering) hasSteering = 0 wheelAttachPosLocal = [-wheelsXYZ[0] ,-wheelsXYZ[1], attachHeightLocal] act2 = cont.actuators["wheel2"] wheel2 = act2.owner vehicle.addWheel(wheel2,wheelAttachPosLocal,wheelAttachDirLocal,wheelAxleLocal,suspensionRestLength,wheelRadius,hasSteering) wheelAttachPosLocal = [wheelsXYZ[0] ,-wheelsXYZ[1], attachHeightLocal] act3 = cont.actuators["wheel3"] wheel3 = act3.owner vehicle.addWheel(wheel3,wheelAttachPosLocal,wheelAttachDirLocal,wheelAxleLocal,suspensionRestLength,wheelRadius,hasSteering) else: vehicle = PhysicsConstraints.getVehicleConstraint(chassis.cid) vehicle.setSteeringValue(chassis.steer,0) vehicle.setSteeringValue(chassis.steer,1) vehicle.applyEngineForce(chassis.force*.4,0) vehicle.applyEngineForce(chassis.force*.4,1) vehicle.applyEngineForce(chassis.force*.4,2) vehicle.applyEngineForce(chassis.force*.4,3) #the following lines are not necessary:s #act0 = cont.getActuator("wheel0") #wheel0 = act0.getOwner() #pos = vehicle.getWheelPosition(0) #don't need to do this here, the vehicle updates the wheels automatically #wheel0.setPosition(pos) #orn = vehicle.getWheelOrientationQuaternion(0) #wheel0.setOrientation(orn) vehicle.setRollInfluence(influence,0) vehicle.setRollInfluence(influence,1) vehicle.setRollInfluence(influence,2) vehicle.setRollInfluence(influence,3) vehicle.setSuspensionStiffness(stiffness,0) vehicle.setSuspensionStiffness(stiffness,1) vehicle.setSuspensionStiffness(stiffness,2) vehicle.setSuspensionStiffness(stiffness,3) vehicle.setSuspensionDamping(damping,0) vehicle.setSuspensionDamping(damping,1) vehicle.setSuspensionDamping(damping,2) vehicle.setSuspensionDamping(damping,3) vehicle.setSuspensionCompression(compression,0) vehicle.setSuspensionCompression(compression,1) vehicle.setSuspensionCompression(compression,2) vehicle.setSuspensionCompression(compression,3) vehicle.setTyreFriction(friction,0) vehicle.setTyreFriction(friction,1) vehicle.setTyreFriction(friction,2) vehicle.setTyreFriction(friction,3) #This function moves an object globally. #target = the object that will move. #ob is the destination. Can be list ([x,y,z]) or object #speed is the speed to which it will reach the ob. (Leave at 0 to set position) #axis can be any combination of the letters x, y,& z. #Note: If object is not dynamic, returns velocity needed to reach target based on parameters. def move(target,ob,speed=0,axis='xyz',retn=0): #Moves the target ob to the ob at the speed specified. vec = target.getVectTo(ob)[1] linv = [n*speed for n in vec] final = Vector(0,0,0) for l in axis: if l == 'x': final[0] = linv[0] if l == 'y': final[1] = linv[1] if l == 'z': final[2] = linv[2] if retn: return final if target.mass > 0: target.setLinearVelocity(final,0) else: target.applyMovement(final,0) #Tracks to object, no actuators needed. # target: object that will track #axis: "y" or "-y" Use x or z for other axis. #time in game ticks #ob can be object or list. #use3D is the same as the 3D button on the actuator. def track(target,ob,axis='y',time=0,use3D=1): # calculate the factor if not bool(time): factor = 1.0 else: factor = 1.0/time vec = target.getVectTo(ob)[1] if "-" in axis: vec = -Vector(vec) axis = spop(axis, "-") final = [0,0,0] if not use3D: final[0],final[1] = vec[0],vec[1] else: final = vec axis = {'x':0, 'y':1, 'z':2}[axis.lower()[0]] target.alignAxisToVect(final, axis, factor) #Every objects tracks to the one before it. (Except for first) def trackToLast(obs,axis=1,factor=1): trackTo = obs[0].worldPosition #Default for ob in obs[1:]: track(ob,trackTo,axis,factor) trackTo = ob.worldPosition #Assigns a value to an object. def assignProp(target,targetProp,value): target[targetProp] = value #gets the prop value from an object def getprop(target,prop): if not target.has_key(prop): raise KeyError('%s does not have key: %s'%(target.name[2:],prop)) return None else: return target[prop] #Replaces the objects mesh def replaceMesh(ob,mesh,dispMesh=True,physMesh=False): ob.replaceMesh(mesh,dispMesh,physMesh) #Rotates an object a certain degrees. #axis can be any combination of "x", "y" or "z" def rotate(ob,deg=360,axis='x'): final,deg = [0,0,0],radians(deg) if 'x' in axis: final[0] = deg if 'y' in axis: final[1] = deg if 'z' in axis: final[2] = deg ob.applyRotation(final) #Gets the distance to the ground. def distToGround(obj,prop=None,maxlook=10000): dist = 0 pos = Vector(obj.worldPosition).copy() while True: dist += maxlook/100 pos[2] -= dist ob = obj.rayCastTo(pos) if prop and not ob.has_key(prop): pos = Vector(ob.worldPosition).copy() continue if ob != None: dist = obj.worldPosition[2]-ob.worldPosition[2] break if dist > maxlook: print IOError("Could not find ground after looking %i units below."%maxlook) return 0 return dist #Aquires the closest of a list of objects from the givin range in a givin angle. # obj = Object that is seeking a target # range = max distance to look. # angleOfSight = the angle to look. # Returns object def AquireTarget(obj,range,angleOfSight,prop=None,objlist=None): #Check for objects in the angle of sight, who are in range. inrange = [] objlist = objlist or list([ob for ob in oblist if not prop or ob.has_key(prop)]) for enemy in objlist: dist = obj.getDistanceTo(enemy) if dist < range: v1 = Vector(obj.getVectTo(enemy)[1]).normalize() v2 = Vector(obj.getAxisVect([1,0,0])) if AngleBetweenVecs(v1,v2) <= angleOfSight/2.0: inrange.append([enemy,dist]) #Found enemy in range who is in sight. closest = range target = False for entry in inrange: if entry[1] < closest: target = entry[0] return target #Gets a vector from one point to another. #returns (distance,globalVector(3),localVector(3)) #obj = KX_GameObject, string, list [x,y,z] #other = KX_GameObject or list [x,y,z] def getVect(obj,other): try: mat = Matrix(*obj.worldOrientation) obj = Vector(obj.worldPosition) except: raise AttributeError try: other = Vector(other.worldPosition) except: try: list(other) except: raise IOError("Could not convert "+other) #Get the vector globalVector = other-obj #Set its magnitude to 1 globalVector /= globalVector.magnitude #Creates the local vector based on the orientation matrix localVector = mat * globalVector a = obj; b = other; dist = sqrt((a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2) return (dist,globalVector,localVector) ##======================Math Functions=============================## ##Converts binary numbers to integers## def binaryToint(binary): i = 0 integer = 0 binary = list(binary) binary.reverse() for num in binary: if num: integer+=2**i i+=1 return integer ##Adds two binary numbers## def addBinaries(bin1,bin2): binA = binaryToint(bin1) binB = binaryToint(bin2) binC = binA+binB return intTobinary(binC) ##Returns the average position from all the objects in the list. ##obs is the object list. def averagePositions(obs): NewPos = Vector(0,0,0) for ob in obs: pos = Vector(ob.worldPosition) NewPos = pos+NewPos NewPos = Vector(NewPos)/len(obs) return NewPos def euler2mat(rx,ry,rz): A,B = math.sin(rx), math.cos(rx) C,D = math.sin(ry), math.cos(ry) E,F = math.sin(rz), math.cos(rz) AC,BC = A*C, B*C return [[D*F,D*E,-C], [AC*F-B*E,AC*E+B*F,A*D], [BC*F+A*E,BC*E-A*F,B*D]] ##Factors a number## def factor(x): i = 1 factors = [] while i <= x: if math.fmod(x,i) == 0: factors.append(i) i += 1 return factors #gets the distance between two points, two objects, or any combination of those two. def getDistance(a,b): if type(a) == StringType: a = getObject(a) if type(b) == StringType: b = getObject(b) if not type(a) == ListType: a = a.worldPosition if not type(b) == ListType: b = b.worldPosition distancesquared = abs(a[0]-b[0])**2+abs(a[1]-b[1])**2+abs(a[2]-b[2]) distance = sqrt(distancesquared) return distance ##Gets the square of the distance between the endpoints of two 1x3 vectors## def getDistanceSquared(vec1,vec2): return ((vec2[0]-vec1[0])**2+(vec2[1]-vec1[1])**2+(vec2[2]-vec1[2])**2) ##Returns true if arg is repeated in list## def isDouble(arg,list): if arg in returnDoubles(list): return 1 else: return 0 ##Returns the given list without repeated elements## def removeDoubles(list): return [x for x in list if not x in returnDoubles(list)] ##Returns a list of the elements that were repeated in a list## def returnDoubles(list): doubles = [] done = [] for x in list: if not x in done: done.append(x) else: doubles.append(x) return doubles ##For each element in a list, it gets the indexes of the other elements in## ##a list that are the same, stores that list in a list, and returns the ## ##list of lists## def returnDoublesIndex(list): doubles = returnDoubles(list) indexes = [] for elem in doubles: matches = [] i = 0 for el2 in list: if el2 == elem: matches.append(i) i += 1 indexes.append(matches) return indexes ##Returns a list of indexes that point to where the given elements doubles## ##are, if it has any## def returnElementDoubleIndexes(el,list): if not isDouble(el,list): return [] else: ind = list.index(el) doubleIndexes = returnDoublesIndex(list) for doubleSet in doubleIndexes: if ind in doubleSet: doubleSet.pop(doubleSet.index(ind)) return doubleSet return [] ##Returns a list of the elements that were not repeated in a list## def returnNonDoubles(list): return removeDoubles(list) ##For each element in a list, it gets the indexes of the other elements in## ##a list that are not the same, stores that list in a list, and returns ## ##the list of lists## def returnNonDoublesIndex(list): nondoubles = returnNonDoubles(list) indexes = [] for elem in nondoubles: i = 0 for el2 in list: if el2 == elem: indexes.append(i) i+=1 return indexes #Pythagoras; #Leave a parameter as None to solve for it. def pyth(a=None,b=None,hy=None): # a**2 + b**2 = hy**2 if a == None or not a: return sqrt((hy**2)-(b**2)) elif b == None or not b: return sqrt((hy**2)-(a**2)) elif hy == None or not hy: return sqrt((a**2)+(b**2)) else: raise AttributeError('You must leave one and only one of the parameters as None or False') return 0 ##Adds two 3x3 lists## def listAddition(vec1,vec2): nlist = [] for i in range(len(vec1)): nlist.append(vec1[i]+vec2[i]) return nlist ##Multiplies a list times a number# def listTimesNum(list,n): return [num*n for num in list] def listDivision(vec,n): return [num/n for num in vec] ##Multiplies a 1x3 list times a 3x3 matrix## def listTimesMat(list,mat): answer=[list[0]*mat[0][0]+list[1]*mat[1][0]+list[2]*mat[2][0],list[0]*mat[0][1]+list[1]*mat[1][1]+list[2]*mat[2][1],list[0]*mat[0][2]+list[1]*mat[1][2]+list[2]*mat[2][2]] return answer ##Subtracts two 3x3 lists## def listSubtraction(vec1,vec2): return [vec1[0]-vec2[0],vec1[1]-vec2[1],vec1[2]-vec2[2]] ##Does....something## ##if anybody knows exactly what this does, contact me @ www.sunjay-varma.com ## def MAT_trackvector(fw, y): if abs(abs(fw[2]) - abs(y[2])) < .001: #prevent gimbol lock y.append(y[0]) del y[0] right = VEC_normalize(VEC_cross(y, fw)) up = VEC_cross(fw, right) return [[right[0], up[0], fw[0]],[right[1], up[1], fw[1]],[right[2], up[2], fw[2]]] def mat2euler(mat): t = mat[0][2] if t < -1.0: angle_y = 1.570796327 elif t > 1.0: angle_y = -1.570796327 else : angle_y = -asin(t) C = cos(angle_y) if C != 0.0: 1.0/C angle_x = math.atan2(mat[1][2]*C,mat[2][2]*C) angle_z = math.atan2(mat[0][1]*C,mat[0][0]*C) return (angle_x,angle_y,angle_z) def MatMultVec(a,b): vec = [] for r in range(len(a)): if len(a) == 2: vec.append(a[r][0]*b[0]+a[r][1]*b[1]) elif len(a) == 3: vec.append(a[r][0]*b[0]+a[r][1]*b[1]+a[r][2]*b[2]) else: # len(a) == 4 vec.append(a[r][0]*b[0]+a[r][1]*b[1]+a[r][2]*b[2]+a[r][3]*b[3]) return vec ##Converts radians to degrees def radiansToDegrees(rads): return rads*180/math.pi ##Converts degrees to radians def degeesToRadians(degs): return degs*pi/180 ##Truncates numbers## def truncate(first,second): if first > second: return second elif first < -second: return -second else: return first ##keeps a vector under a certain length## def truncateVector(vec,length): if getDistance([0,0,0],vec) > length: vec = listTimesNum(VEC_normalize(vec),length) return vec #----------------------------Vector Functions-----------------------------------------------# ##Not quite needed but used by some functions## def VEC_dot(x,y): return x[0]*y[0]+x[1]*y[1]+x[2]*y[2] def VEC_cross(x, y): return [x[1]*y[2] - x[2]*y[1], x[2]*y[0] - x[0]*y[2], x[0]*y[1] - x[1]*y[0]] def VEC_length(x): return math.sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2]) def VecMultMat(a,b): vec = [] for r in range(len(a)): if len(a) == 2: vec.append(a[0]*b[0][r]+a[1]*b[1][r]) elif len(a) == 3: vec.append(a[0]*b[0][r]+a[1]*b[1][r]+a[2]*b[2][r]) else: # len(a) == 4 vec.append(a[0]*b[0][r]+a[1]*b[1][r]+a[2]*b[2][r]+a[3]*b[3][r]) return vec def VEC_normalize(x): length = VEC_length(x) if length != 0: return [x[0]/length,x[1]/length,x[2]/length] else: return [0,0,0] ##This function gives you a vector that is a given length# ##in a given vector's direction## def VEC_scale(vec,length): newVec = VEC_normalize(vec) return listTimesNum(newVec,length) ##Multiplies a vector and a rotation matrix## def VecRotMatrix(vec,rotMat): newMat = [0,0,0] newMat[0] = rotMat[0] newMat[1] = rotMat[1] newMat[2] = rotMat[2] a = listTimesNum(newMat[0],vec[0]) b = listTimesNum(newMat[1],vec[1]) c = listTimesNum(newMat[2],vec[2]) Ans = listAddition(listAddition(b,c),a) return Ans #----------------------------------VectorFunctionsEnd---------------------------------------# #Tests if all objects after the decimal are 0s or not. and if an object can be converted to an int. def testInt(num): if type(num) != FloatType or type(num) != StringType: print('FunctionError (testInt): Only Float types and string types are supported.') try: n = str(num).index('.') for number in str(num)[n:]: if number.isdigit() and number != '0': return True else: continue except: return False return False ##======================Scene/Camera Functions=============================## ##Zooms a camera to an object and stays a certain distance from it. ## def cameraZoom(cameraOb, zoomOb,minDist=0,maxDist=0,timeOffset=1): #Calculate moveSpeed moveSpeed = cameraOb.getDistanceTo(zoomOb)/2 moving = False vec = Vector(zoomOb.worldPosition) if cameraOb.getDistanceTo(zoomOb) > maxDist: if vec.magnitude > minDist: vec.magnitude = vec.magnitude - minDist moving = True elif cameraOb.getDistanceTo(zoomOb) < minDist: movespeed = -movespeed moving = True if moving: move(cameraOb,vec,moveSpeed) track(cameraOb,zoomOb,-2,timeOffset) ##Dynamic Camera, replaces the camera actuator. ##axis: 0=x, 1=y ##Note: Very experimental... def dynamicCamera(cameraOb,zoomOb,axis=0,height=0,minDist=0,maxDist=0): track(cameraOb,zoomOb,-2,use3D=1) #position where the camera should idealy be at. pos = Vector(zoomOb.worldPosition) pos[axis] += -pyth(height,None,minDist) pos[2] += height pos = Matrix(*zoomOb.worldOrientation) * Vector(pos) if cameraOb.getDistanceTo(zoomOb) > maxDist*2: cameraOb.localPosition = pos else: moveSpeed = cameraOb.getDistanceTo(pos)/10 moveVec = move(cameraOb,pos,moveSpeed) cameraOb.applyMovement(moveVec) #This function can do 1 of 3 things. # 1. Split screen. ::::: SS # 2. Main screen + corner map. ::::: MSCM # 3. Split screen with center map. ::::: SSWCM def viewports(LeftCam=None,RightCam=None,MapCam=None,mode='SSWCM'): height = getWindowHeight() width = getWindowWidth() #Objects scene = GameLogic.getCurrentScene() obList = scene.objects if LeftCam: bluecam = obList[LeftCam] if mode == 'SS' or mode == 'SSWCH': bluecam.setViewport(0,0,width/2,height) elif mode == 'MSCM': bluecam.setViewport(0,0,width,height) bluecam.useViewport = True bluecam.enableViewport(True) if RightCam: redcam = obList[RightCam] if mode == 'SS' or mode == 'SSWCH': redcam.setViewport(width/2,0,width,height) redcam.useViewport = True redcam.enableViewport(True) if MapCam: overview = obList[MapCam] if mode == 'SSWCM': overview.setViewport(width/4,0,width*3/4,height*1/3) elif mode == 'MSCM': overview.setViewport(0,0,width/4,height*1/3) overview.setOnTop() overview.enableViewport(True) #Gets a scene, leave at None to get current scene def getScene(name=None): if not name: return GameLogic.getCurrentScene() else: try: return GameLogic.getSceneList()[name] except: raise KeyError('No such scene as, %s'%name) #Gets the active camera or sets it if name is defined. def camera(name=None): if name: try: GameLogic.getCurrentScene().active_camera = name except: raise KeyError('No such camera as: %s' % name ) else: return GameLogic.getCurrentScene().active_camera #Adds an object to the scene #object can be an object or a string-the object to add #other-the object's center to use when adding the object. #time - the life time of the object in frames. def addObject(object,other,time=0): GameLogic.getCurrentScene().addObject(object,other,time) #Add each object in the dictionary. Note: Each key should be an object #and the value should be the object's center to add at. #Leave obdict at none to add all the inactive objects, to objects with the specified prefix. def addObjects(obdict=None,prefix='Adder_',time=0): oblist = getObjects() adders = [ob for ob in oblist if ob.name.startswith('OB'+(prefix or ''))] if obdict == None: for ob in getObjects(2): randomObjectInScene = choice(adders) addObject(ob,randomObjectInScene,time) else: for ob in obdict.keys(): addObject(ob,obdict[ob],time) #gets a list of the lights in the current scene def getLights(): return GameLogic.getCurrentScene().lights #set num to 1 for a full list of all the objects in the scene plus the ones on other layers. #set num to 2 for just the inactive layers def getObjects(num=0): l = [] if num == 0 or num == 1: l.extend(GameLogic.getCurrentScene().objects) if num == 1 or num == 2: l.extend(GameLogic.getCurrentScene().objectsInactive) return l #Gets an object based on its name def getObject(name): return GameLogic.getCurrentScene().objects['OB'+name] ##Standard script init## ##This gets your own,cont,obs, etc## def initGame(): cont1 = GameLogic.getCurrentController() own1 = cont1.owner obs1 = GameLogic.getCurrentScene().objects return {'cont':cont1,'own':own1,'obs':obs1} ##Returns the coordinates of the xbox 360 controller's joystick## def joystick(joystickSensorName,sensitivity): cont = initGame()['cont'] joystick = cont.sensors[joystickSensorName] axisVal = joystick.axisValue center = joystick.axis centerX = -1120 centerY = -2421 centerZ = -2417 maxX = 32126 minX = -32768 maxY = 32767 minY = -32768 maxZ = 32190 minZ = -32768 ratioX = sensitivity[0] / (maxX - minX) ratioY = sensitivity[1] / (maxY - minY) ratioZ = sensitivity[2] / (maxZ - minZ) moveXPosi = (axisVal[0] - centerX) * ratioX moveYPosi = (axisVal[1] - centerY) * ratioY moveZPosi = (axisVal[3] - centerZ) * ratioZ if moveXPosi > (sensitivity[0]/8.0) or moveXPosi < -(sensitivity[0]/8.0): value = moveXPosi else: value = 0 if moveYPosi > (sensitivity[1]/8.0) or moveYPosi < -(sensitivity[1]/8.0): value2 =- moveYPosi else: value2 = 0 if countElements(sensitivity)>2: if moveZPosi > (sensitivity[2]/8.0) or moveZPosi < -(sensitivity[2]/8.0): value3 =- moveZPosi else: value3 = 0 return [value,value2,value3] else: return [value,value2] ##Actuator on/off## ##yes, i'm that lazy## def OnOff(cont,actuator,action): if action: cont.activate(actuator) else: cont.deactivate(actuator) ##Randomly adjusts the pitch of a sound for more realistic bangs, clangs, and smacks## def realSound(cont,actuatorName,range,custom=None): sound = cont.actuators[actuatorName] if range == 'mediumlow': choices = [0.9,0.8,0.7,1.0,0.9,0.8] if range == 'low': choices = [0.3,0.4,0.5,0.3,0.4,0.5] if range == 'medium': choices = [1.0,1.1,1.2,1.1,0.9,1.3] if range == 'mediumhigh': choices = [1.4,1.3,1.5,1.4,1.3,1.5] if range == 'high': choices = [1.5,1.6,1.7,1.8,1.9,1.6] if range == 'custom': choices = custom pick = choice(choices) sound.pitch = pick OnOff(cont,sound,1) ##Removes the given constraint## def removeConstraint(ID): PhysicsConstraints.removeConstraint(ID) #Saves an objects prop to the globalDict #Note: to save the globalDict use the game actuator. #name is where it will be saved. def save(name,prop): GameLogic.globalDict[name] = prop #Loads the prop. def load(name): if not name in GameLogic.globalDict: return None else: return GameLogic.globalDict[name] ##======================String Functions=============================## #Capitalizes all the words in a string. sep is the seporator. def capwords(s,sep=None): return (sep or ' ').join([x.capitalize() for x in s.split(sep)]) # removes an item from a string. # if item is left None, it removes the last item. def spop(s, item=None): try: i = s.index(item) except: i = len(s)-1 return ''.join(list(s).pop(i)) ##======================Useful Classes=============================## # A ray class, replaces ray sensor class ray: # sends the ray. Use attributes to access the results. def __init__(self, obj, prop=None, rayRange=0.01, axis='y', xray=0): self.object = obj self.range = rayRange = max(0.01, min(10000, rayRange)) # the range of the ray. # check if the axis should be negitive. x = 1 if '-' in axis: self.range *= -1 x *= -1 axis = spop(axis, '-') self.axis = axis # set the axis # calculate the axis. axis = {'x':0,'y':1,'z':2}[str(axis).lower()[0]] # create an empty vector v = Vector() # set the axis to x which is calculated obove. v[axis] = x # Change the direction of the object's orientation point = Matrix(*self.object.worldOrientation) * v # then set the length based on the rayRange point.magnitude = rayRange # last step is to add the object's position to the point of the ray. vec = Vector(self.object.worldPosition)+point # send the actual ray, and collect the results. if not prop: prop = '' self.hitObject, self.hitPosition, self.hitNormal, self.poly = self.object.rayCast(vec, self.object, rayRange, prop, 1, xray, 1) self.rayDirection = Vector([self.object.worldOrientation[i][axis] for i in range(3)]).normalize() self.positive = True if not self.hitObject or self.hitObject == self.object: self.positive = False ##======================Artificial Intelligence Functions=============================## #A series of simple AI. #AI that globally moves toward the target. Optional Jumping. #Great for boulders or other objects set to rigid body. #obj is the AI object. #jumpfactor is the factor that decides how often to jump. (1=always) #stopdistance is the distance from the object you want to stop at. (Leave at None to chase unitl collision) #Note: This can be attached to any sensor you want. For best results: # Always sensor, true level pulse, 30 GT delay def AIFollower(obj,target,movespeed=5,jumpforce=None,jumpfactor=20,stopdistance=None): if type(target) == StringType: target = getObject(target) if type(obj) == StringType: obj = getObject(obj) move(obj,target,8,'xy') if jumpforce: if randint(0,jumpfactor) == 1: setLinV(obj,[0,0,jumpforce],0,'z') #This is a more independant AI. #This one moves around then after the specified time, turns. #forward = the forward axis of the object. "y" or "-y" (Use either x or z in place of those for other access) #look = the amount to look in front of the object. #speed = the speed that the object moves #stime = the amount to wait before you automatically turn. def AIMover(obj,look=2,forward='y',speed=10,stime=2): #import time module. This is how we will keep track of time. import time #First just get the object(if its not a KX_GameObject already.) if type(obj) == StringType: obj = getObject(obj) #Left and right turn force. left = -pi/2 right = pi/2 #The variable that makes sure we only turn once. LEAVE AT 0 turn = 0 if forward < 0: look = look*-1 speed = -speed forward = forward*-1 raysens = ray(obj,None,look,forward) #ray turning if raysens.positive: direction = choice([1,2]) if direction == 1: turn = left if direction == 2: turn = right obj['TIMER'] = time.clock() #timer turning if not obj.has_key('TIMER'): obj['TIMER'] = time.clock() eTime = (time.clock()-obj['TIMER']) if eTime >= stime: direction = choice([1,2]) if direction == 1: turn = left if direction == 2: turn = right obj['TIMER'] = time.clock() #print 'Timer new value:',obj['TIMER'],' = ',time.clock()-obj['TIMER'] #Rotate the object obj.applyRotation([0,0,turn]) # calculate the actual forward access # first, delete the "-" sign if there is any. forward = spop(forward, '-') forward = {'x':0,'y':1,'z':2}[forward.lower()[0]] #move the object linV = [0,0,0] linV[forward] = speed setLinV(obj,linV,1) ##======================Miscellaneous Functions=============================## def delete(fileOb): ''' Deletes an already declared fileOb ''' from os import remove try: remove(fileOb) except: raise TypeError("fileOb argument must already be opened!") # Copies an already opened file to the directory. def copy(fileOb, directory): ''' Opens a fileOb and the copies it into the directory. ''' import os import Tkinter as t if type(fileOb) != FileType: raise TypeError("fileOb argument must already be opened!") if not os.path.isdir(directory): try: if directory.endswith(os.sep): directory += os.sep os.mkdir(directory) except: raise IOError("Could not make directory: %s"%directory) canWork = True def yes(): canWork = True root.destroy() def no(): canWork = False root.destroy() if not directory.endswith(os.sep): directory += os.sep if os.path.isfile(directory+fileOb.name): root = t.Tk(className="Copying...") t.Label(root, text="Would you like to overwrite the file \" %s \"?"%fileOb.name).pack(expand=t.YES, fill=t.BOTH) t.Button(root, text='Yes', command=yes).pack(side=t.LEFT,expand=t.YES,fill=t.X) t.Button(root, text='No', command=no).pack(side=t.RIGHT,expand=t.YES, fill=t.X) root.mainloop() if not canWork: return False else: try: target = file(directory+fileOb.name, 'w') s = fileOb.read() target.write(s) target.close() except: raise IOError("Failed to write to "+target.name) # Deletes an entire directory. def deldir(dir): ''' Deletes entire folders. ''' import os if dir[-1] == os.sep: dir = dir[:-1] files = os.listdir(dir) for file in files: if file == '.' or file == '..': continue path = dir + os.sep + file if os.path.isdir(path): deldir(path) else: os.unlink(path) os.rmdir(dir) ##======================GUI Functions (Popup Boxes)=============================## # creates a box with the buttons yes and no. # message: specialized message defaults to "Yes or No?" # yes: Value of yes button defaults to "Yes" # no: Value of no button defaults to "No" # box name: name of popup box. def confirmbox(message=None,yes=None,no=None,boxname=None): # fix up the variables...just in case! if not message: message = "Yes or No?" if not yes: yes = "Yes" if not no: no = "No" if not boxname: boxname = "Yes or No" #----------------------------------------------------# # define a function to decide what to do when a button is clicked. def Yes(): canwork.append(True) # for some reason just assigning a variable didn't work. root.destroy() # end the box. def No(): canwork.append(False) # for some reason just assigning a variable didn't work. root.destroy() # end the box #----------------------------------------------------# import Tkinter as t canwork = [] # make a list to store the returned value. root = t.Tk(className=boxname) root["padx"] = 20 root["pady"] = 10 t.Label(root, text=message, pady=10).pack(expand=t.YES, fill=t.BOTH) t.Button(root, text=yes, command=Yes, width=10).pack(side=t.LEFT,expand=t.YES, fill=t.X) t.Button(root, text=no, command=No, width=10).pack(side=t.RIGHT,expand=t.YES, fill=t.X) # give the window focus root.focus_set() root.mainloop() try: return canwork[0] except: return None # creates a single line text entry box. def promtbox(message=None, width=None, buttonText=None, boxname=None, **entryOptions): # fix up the variables message = message or "Enter some text." width = width or 50 buttonText = buttonText or "Submit" boxname = boxname or "Text Input Box" #----------------------------------------------------# def retriveEntry(): text.append(entry.get()) root.destroy() #----------------------------------------------------# # start building the box. import Tkinter as t # text holder. Don't know why I have to keep using lists... text = [] # main widget root = t.Tk(className=boxname) root.title(boxname) root["padx"] = 20 root["pady"] = 10 # create our message t.Label(root, text=message, pady=10).pack(side=t.TOP) # the text field. entry = t.Entry(root, **entryOptions) if width: entry.config(width=width) entry.pack() t.Button(root, text=buttonText, width=10, command=retriveEntry).pack(side=t.BOTTOM) # give the window focus root.focus_set() root.mainloop() try: return text[0] except: return False def alertbox(message=None, buttonText=None, boxname=None): message = message or "Alert!" buttonText = buttonText or "Ok" boxname = boxname or "Alert" #----------------------------------------------------# def submit(): canwork.append(True) root.destroy() #----------------------------------------------------# import Tkinter as t canwork = [] # make a list to store the returned value. root = t.Tk() root.title(boxname) root["padx"] = 20 root["pady"] = 10 t.Label(root, text=message, pady=10).pack(expand=t.YES, fill=t.BOTH) t.Button(root, text=buttonText, command=submit, width=10).pack(side=t.BOTTOM,expand=t.YES, fill=t.X) # give the window focus root.focus_set() root.mainloop() try: return canwork[0] except: return None # opens up a file manager. def filemanager(message=None): message = message or "Please Select a file:" #----------------------------------------------------# import tkFileDialog as tkfd import Tkinter as t import os root = t.Tk() root.title("File Manager") root["padx"] = 40 root["pady"] = 10 t.Label(root, text=message, pady=10).pack() frame = t.Frame(root) e = t.Entry(frame, width=50) e.delete(0,t.END) e.insert(0, os.sep) output = [] #----------------------------------------------------# def openDialog(): newpath = tkfd.askopenfilename() if bool(newpath): e.delete(0,t.END) e.insert(0, newpath) def exitBox(): output.append(e.get()) root.destroy() #----------------------------------------------------# e.pack(fill=t.X, side=t.LEFT) t.Button(frame, text="Browse", command=openDialog, width=15, cursor="hand2").pack() frame.pack(pady=5) t.Button(root, text="Ok", command=exitBox, width=15, cursor="hand2").pack(side=t.BOTTOM) # give the window focus root.focus_set() # start the program root.mainloop() try: return output[0] except: return None # opens up a folder manager. def foldermanager(message=None): message = message or "Please select a folder:" #----------------------------------------------------# import tkFileDialog as tkfd import Tkinter as t import os root = t.Tk() root.title("Folder Manager") root["padx"] = 40 root["pady"] = 10 t.Label(root, text=message, pady=10).pack() frame = t.Frame(root) e = t.Entry(frame, width=50) e.delete(0,t.END) e.insert(0, os.sep) output = [] #----------------------------------------------------# def openDialog(): newpath = tkfd.askdirectory() if bool(newpath): e.delete(0,t.END) e.insert(0, newpath) def exitBox(): output.append(e.get()) root.destroy() #----------------------------------------------------# e.pack(fill=t.X, side=t.LEFT) t.Button(frame, text="Browse", command=openDialog, width=15, cursor="hand2").pack() frame.pack(pady=5) t.Button(root, text="Ok", command=exitBox, width=15, cursor="hand2").pack(side=t.BOTTOM) # give the window focus root.focus_set() # start the program root.mainloop() try: return output[0] except: return None ##==================================End=============================##