def __init__(self): base.disableMouse() # This disables the default mouse based camera control used by panda. This default control is awkward, and won't be used. base.camera.setPos(0,20,20) base.camera.lookAt(0,0,0) # Gives the camera an initial position and rotation. self.mx,self.my=0,0 # Sets up variables for storing the mouse coordinates self.orbiting=False # A boolean variable for specifying whether the camera is in orbiting mode. Orbiting mode refers to when the camera is being moved # because the user is holding down the right mouse button. self.target=Vec3() # sets up a vector variable for the camera's target. The target will be the coordinates that the camera is currently focusing on. self.camDist = 40 # A variable that will determine how far the camera is from it's target focus self.panRateDivisor = 20 # This variable is used as a divisor when calculating how far to move the camera when panning. Higher numbers will yield slower panning # and lower numbers will yield faster panning. This must not be set to 0. self.panZoneSize = .15 # This variable controls how close the mouse cursor needs to be to the edge of the screen to start panning the camera. It must be less than 1, # and I recommend keeping it less than .2 self.panLimitsX = Vec2(-20, 20) self.panLimitsY = Vec2(-20, 20) # These two vairables will serve as limits for how far the camera can pan, so you don't scroll away from the map. self.setTarget(0,0,0) # calls the setTarget function to set the current target position to the origin. self.turnCameraAroundPoint(0,0) # calls the turnCameraAroundPoint function with a turn amount of 0 to set the camera position based on the target and camera distance self.accept("mouse3",self.startOrbit) # sets up the camrea handler to accept a right mouse click and start the "drag" mode. self.accept("mouse3-up",self.stopOrbit) # sets up the camrea handler to understand when the right mouse button has been released, and ends the "drag" mode when # the release is detected. # The next pair of lines use lambda, which creates an on-the-spot one-shot function. self.accept("wheel_up",lambda : self.adjustCamDist(0.9)) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 0.9 self.accept("wheel_down",lambda : self.adjustCamDist(1.1)) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 1.1 taskMgr.add(self.camMoveTask,'camMoveTask')
def restart(self): """Start or restart the plugin.""" self.draw = Draw() # Utility for drawing 2D lines and shapes in 3-space path = Path([Vec2(40,40),Vec2(40,-40),Vec2(-40,40),Vec2(-40,-40)]) for vehicle in self.vehicles[:3]: vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100) vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2) vehicle.followPath(path,loop=True) c=(.6,.6,.6,.3) t=1 z=1.5 self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t) self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t) self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t) self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t) path = Path([Vec2(-40,-40),Vec2(40,-40),Vec2(-40,40),Vec2(40,40)]) for vehicle in self.vehicles[3:]: vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100) vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2) vehicle.followPath(path,loop=True) self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t) self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t) self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t) self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t) for vehicle in self.vehicles: vehicle.avoidObstacles = True vehicle.avoidVehicles = True vehicle.maxforce = 0.1 vehicle.maxspeed = 0.5 + (random.random()/2) node = self.draw.create() np = NodePath(node) np.reparentTo(render)
def _drawHole(self, x, y): center = Vec2(x, y) ul = center - Vec2(self._radius, self._radius) lr = center + Vec2(self._radius, self._radius) x = int(ul[0]) while x <= lr[0]: y = int(ul[1]) while y <= lr[1]: if x > 0 and y > 0 and x < self._maskResolution and y < self._maskResolution: self._revealFunctions[self._revealFunction](x, y, center) y += 1 x += 1 self.maskTexture.load(self._maskImage) self.mask.setTexture(self.maskTexture, 1)
def grassTexture(imgSize=(256,256)): """Return a green, 'grassy' texture (PNMImage) of the given image size, produced using 2D Perlin noise.""" # Initialuse the PNMImage object img = PNMImage(*imgSize) # Initalise 4 PerlinNoise2 objects to produce noise at different scales noise1 = PerlinNoise2() noise1.setScale(2.0) noise2 = PerlinNoise2() noise2.setScale(5.0) noise3 = PerlinNoise2() noise3.setScale(0.25) noise4 = PerlinNoise2() noise4.setScale(0.125) # For each pixel in the image, set the red and blue values of the pixel to # constant values, and set the green value of the pixel using all 4 # PerlinNoise2 objects. red = 0.125 # Colour values in PNMImage are doubles in the range [0.0,1.0] blue = 0.0625 for x in xrange(imgSize[0]): for y in xrange(imgSize[1]): img.setRed(x,y,red) img.setBlue(x,y,blue) pos = Vec2(1.0/32*x, 1.0/32*y) img.setGreen(x,y,(0.5 + noise1(pos)*0.0625 + noise2(pos)*0.0625 + noise3(pos)*0.125 + noise4(pos)*0.0625)) return img
def OnUpdate(self, task): """ Task to control mouse events. Gets called every frame and will update the scene accordingly. """ p3d.Camera.OnUpdate(self, task) # Return if no mouse is found or alt not down if not self.mouseWatcherNode.hasMouse( ) or not p3d.MOUSE_ALT in self.mouse.modifiers: return # ORBIT - If left mouse down if self.mouse.buttons[0]: self.Orbit( Vec2(self.mouse.dx * self.speed, self.mouse.dy * self.speed)) # DOLLY - If middle mouse down elif self.mouse.buttons[1]: self.Move( Vec3(self.mouse.dx * self.speed, 0, -self.mouse.dy * self.speed)) # ZOOM - If right mouse down elif self.mouse.buttons[2]: self.Move(Vec3(0, -self.mouse.dx * self.speed, 0))
def _revealSmoothCircle(self, x, y, center): length = (Vec2(x, y) - center).length() goalAlpha = max(0.0, length / float(self._radius) - 0.5) self._maskImage.setXelA( x, y, VBase4D(0.0, 0.0, 0.0, min(self._maskImage.getAlpha(x, y), goalAlpha * 2.0)))
def setPolygonalNeighbors(self, prev, next): vecToPrev = prev.pos - self.pos vecToNext = next.pos - self.pos angle = vecToPrev.signedAngleDeg(vecToNext) angle %= 360 # Convert this to an unsigned angle. self.prevPolyNeighbor = prev self.nextPolyNeighbor = next self.interiorAngle = angle prevAngle = Vec2(1, 0).signedAngleDeg(vecToPrev) extrudeAngle = prevAngle + self.interiorAngle / 2.0 + 180 extrudeAngle *= math.pi / 180 # Degrees to radians self.extrudeVector = Vec2(math.cos(extrudeAngle), math.sin(extrudeAngle))
def wander(self, elapsed): pos = Vec2(self.getPos().xy) r = elapsed * self.maxSpeed * 3 if (pos - self.startPosition).length() > self.wanderRadius: change = self.startPosition - pos change.normalize() change *= r else: change = Vec2(random.uniform(-r, r), random.uniform(-r, r)) desiredVelocity = self.wanderVelocity + change desiredVelocity.normalize() desiredVelocity *= self.maxSpeed self.wanderVelocity = desiredVelocity desiredHeading = math.degrees( math.atan2(desiredVelocity.y, desiredVelocity.x)) + 90 desiredVelocity = Vec3(desiredVelocity.x, desiredVelocity.y, 0) #logging.info( desiredVelocity) self.move(desiredVelocity, desiredHeading, elapsed)
def __init__(self, parent): wx.Window.__init__(self, parent) self.points = [] self.curvepoints = [] self.SetBackgroundColour(wx.Colour(255, 255, 255)) self.Bind(wx.EVT_PAINT, self.onPaint) self.Bind(wx.EVT_LEFT_DOWN, self.onLeftDown) self.Bind(wx.EVT_LEFT_UP, self.onLeftUp) self.Bind(wx.EVT_RIGHT_UP, self.onAddPoint) self.Bind(wx.EVT_MOUSEWHEEL, self.onZoom) self.Bind(wx.EVT_SIZE, self.onSize) self.Bind(wx.EVT_MOTION, self.onMotion) self.active_point = None self.max_value = 50 self.points = [Vec2(-10, -20), Vec2(0, 20), Vec2(10, -20)] self.actualizePoints()
def greenNoise(imgSize=(32,32),scale=0.25): """Return a PNMImage of the given size containing Perlin noise at the given scale in the green colour values of the image pixels.""" # Initialuse the PNMImage object img = PNMImage(*imgSize) # Initalise PerlinNoise2 object noise = PerlinNoise2() noise.setScale(scale) # Fill in the pixels of img, setting the red and blue values of each pixel # to 0 and the green value to Perlin noise. for x in xrange(imgSize[0]): for y in xrange(imgSize[1]): img.setRed(x,y,0) img.setBlue(x,y,0) pos = Vec2(1.0/32*x, 1.0/32*y) img.setGreen(x,y,(noise(pos)+1.0)/2.0) return img
def __init__(self, heightFunction, x=0, y=0): NodePath.__init__(self, "Creature") self.reparentTo(render) self.startPosition = Vec2(x, y) z = heightFunction(x, y) self.setPos(x, y, z) # movement self.acceleration = 25 self.velocity = Vec3(0, 0, 0) self.maxSpeed = 10 self.speed = 0 self.maxAngularVelocity = 360 self.turbo = 1 self.maxStoppingDistance = self.maxSpeed / self.acceleration * 0.5 self.body = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.body.setScale(0.25) self.body.reparentTo(self) self.heightFunction = heightFunction
def directionalVector(rads, speed): return Vec2(cos(rads), sin(rads)) * speed
def getMouseVec(self): """ returns mouse vector """ md = base.win.getPointer(0) return Vec2(md.getX(), md.getY())
def directionalVector(heading, speed): rads = radians(heading) return Vec2(cos(rads), sin(rads)) * speed
def __init__(self, fov=60.0, pos=(-10, -100, 25), lookAt=(0, 0, 0)): # Camera field of view self.fov = fov # Camera position self.pos = Vec3(pos) # Point the camera looks at self.lookAt = Vec3(lookAt) # Camera target. This is what the camera should be looking at self.target = Vec3(lookAt) # camVec = (self.target - self.pos) self.camDist = camVec.length() #LOG.debug("self.pos = %s, self.target = %s, self.camDist = %s" % (self.pos, self.target, self.camDist)) # Camera state variables self.movingUp = False self.movingDown = False self.movingLeft = False self.movingRight = False self.dragging = False # The gutter is the area around the border of the screen where # the mouse cursor entering this area triggers the panning action self.leftgutter = -0.8 self.rightgutter = 0.8 self.bottomgutter = -0.8 self.topgutter = 0.8 # Mouse position from previous event. Used to calculate distance the # mouse has moved. self.mx = 0 self.my = 0 self.mpos = Vec2(0, 0) # Options self.gutterdrive = False # Factor used to convert mouse movement into world movement self.gutterdriveMouseFactor = 100 self.panMouseFactor = 2000 self.zoomFactor = 3 # Build the camera rotation maticies self.leftrightRotationDegrees = 0.5 self.updownRotationDegrees = 2 rSin = math.sin(self.leftrightRotationDegrees * RAD_FACTOR) rCos = math.cos(self.leftrightRotationDegrees * RAD_FACTOR) self.leftMatrix = Mat3(rCos, rSin, 0, -rSin, rCos, 0, 0, 0, 1) self.rightMatrix = Mat3(rCos, -rSin, 0, rSin, rCos, 0, 0, 0, 1) rSin = math.sin(self.updownRotationDegrees * RAD_FACTOR) rCos = math.cos(self.updownRotationDegrees * RAD_FACTOR) self.upMatrix = Mat3(rCos, 0, -rSin, 0, 1, 0, rSin, 0, rCos) self.downMatrix = Mat3( rCos, 0, rSin, 0, 1, 0, -rSin, 0, rCos, )
def __init__(self, showbase): self.showbase = showbase self.showbase.disableMouse() # This disables the default mouse based camera control used by panda. This default control is awkward, and won't be used. self.showbase.camera.setPos(0, -150, 200) self.showbase.camera.lookAt(0, 0, 0) # Gives the camera an initial position and rotation. self.mx, self.my = 0, 0 # Sets up variables for storing the mouse coordinates self.orbiting = False # A boolean variable for specifying whether the camera is in orbiting mode. Orbiting mode refers to when the camera is being moved # because the user is holding down the right mouse button. self.target = Vec3() # sets up a vector variable for the camera's target. The target will be the coordinates that the camera is currently focusing on. self.camDist = 150 # A variable that will determine how far the camera is from it's target focus self.panRateDivisor = 10 # This variable is used as a divisor when calculating how far to move the camera when panning. Higher numbers will yield slower panning # and lower numbers will yield faster panning. This must not be set to 0. self.panZoneSize = .1 # This variable controls how close the mouse cursor needs to be to the edge of the screen to start panning the camera. It must be less than 1, # and I recommend keeping it less than .2 self.panLimitsX = Vec2(-1000, 1000) self.panLimitsY = Vec2(-1000, 1000) # These two vairables will serve as limits for how far the camera can pan, so you don't scroll away from the map. self.maxZoomOut = 500 self.maxZoomIn = 25 #These two variables set the max distance a person can zoom in or out self.orbitRate = 75 # This is the rate of speed that the camera will rotate when middle mouse is pressed and mouse moved # recommended rate 50-100 self.setTarget(0, 0, 0) # calls the setTarget function to set the current target position to the origin. self.turnCameraAroundPoint(0, 0) # calls the turnCameraAroundPoint function with a turn amount of 0 to set the camera position based on the target and camera distance self.accept("mouse2", self.startOrbit) # sets up the camrea handler to accept a right mouse click and start the "drag" mode. self.accept("mouse2-up", self.stopOrbit) # sets up the camrea handler to understand when the right mouse button has been released, and ends the "drag" mode when # the release is detected. self.storeX = 0 self.storeY = 0 # for storing of the x and y for the orbit # The next pair of lines use lambda, which creates an on-the-spot one-shot function. self.accept("wheel_up", self.zoomIn) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 0.9 self.accept("wheel_down", self.zoomOut) # sets up the camera handler to detet when the mouse wheel is rolled upwards and uses a lambda function to call the # adjustCamDist function with the argument 1.1 # Keys array (down if 1, up if 0) self.keys = {"cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0} # Using Arrow Keys self.accept("arrow_left", self.setValue, [self.keys, "cam-left", 1]) self.accept("arrow_right", self.setValue, [self.keys, "cam-right", 1]) self.accept("arrow_up", self.setValue, [self.keys, "cam-up", 1]) self.accept("arrow_down", self.setValue, [self.keys, "cam-down", 1]) self.accept("arrow_left-up", self.setValue, [self.keys, "cam-left", 0]) self.accept("arrow_right-up", self.setValue, [self.keys, "cam-right", 0]) self.accept("arrow_up-up", self.setValue, [self.keys, "cam-up", 0]) self.accept("arrow_down-up", self.setValue, [self.keys, "cam-down", 0]) self.keyPanRate = 1.5 # pan rate for when user presses the arrow keys # set up plane for checking collision with for mouse-3d world self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
def _flareTask(self, task): #going through the list of lightNodePaths #for index in xrange(0, len(self.lightNodes)): pos2d = self._get2D(self.sunlight) #if the light source is visible from the cam's point of view, # display the lens-flare if pos2d: #print ("Flare visible") # The the obscured factor obscured = self._getObscured(self.suncardcolor) # Scale it to [0,1] self.obscured = obscured / 100 ##print obscured # Length is the length of the vector that goes from the screen # middle to the pos of the light. The length gets smaller the # closer the light is to the screen middle, however, since # length is used to calculate the brightness of the effect we # actually need an inverse behaviour, since the brightness # will be greates when center of screen= pos of light length = math.sqrt(pos2d.getX() * pos2d.getX() + pos2d.getY() * pos2d.getY()) invLength = 1.0 - length * 2 # Subtract the obscured factor from the inverted distence and # we have a value that simulates the power of the flare #brightness flarePower = invLength - self.obscured #print("light pos=%s | length=%s"%(pos2d,length)) print("obs=%s | length=%s | inv=%s | pow=%s" % (self.obscured, length, invLength, flarePower)) # Clamp the flare power to some values if flarePower < 0 and self.obscured > 0: flarePower = 0.0 if flarePower < 0 and self.obscured <= 0: flarePower = 0.3 if flarePower > 1: flarePower = 1 print("flarepower=%s" % (flarePower)) # if self.obscured >= 0.8: self.texcardNP.find('**/Sun:starburstNode').hide() else: self.texcardNP.find('**/Sun:starburstNode').show() #drawing the lens-flare effect... r = self.suncolor.getX() g = self.suncolor.getY() b = self.suncolor.getZ() r = math.sqrt(r * r + length * length) * self.strength g = math.sqrt(g * g + length * length) * self.strength b = math.sqrt(b * b + length * length) * self.strength print("%s,%s,%s" % (r, g, b)) # if self.obscured > 0.19: a = self.obscured - 0.2 else: a = 0.4 - flarePower # if a < 0: a = 0 if a > 0.8: a = 0.8 # self.hdr.setColor(r, g, b, 0.8 - a) self.hdr.setR(90 * length) self.texcardNP.find('**/Sun:starburstNode').setColor( r, g, b, 0.5 + length) self.hdr.setPos(pos2d.getX(), 0, pos2d.getY()) self.hdr.setScale(8.5 + (5 * length)) vecMid = Vec2(self.mid2d.getX(), self.mid2d.getZ()) vec2d = Vec2(vecMid - pos2d) vec3d = Vec3(vec2d.getX(), 0, vec2d.getY()) self.starburst_0.setPos(self.hdr.getPos() - (vec3d * 10)) self.starburst_1.setPos(self.hdr.getPos() - (vec3d * 5)) self.starburst_2.setPos(self.hdr.getPos() - (vec3d * 10)) self.texcardNP.show() #print "a",a else: #hide the lens-flare effect for a light source, if it is not visible... self.texcardNP.hide() return Task.cont
def _revealHardCircle(self, x, y, center): length = (Vec2(x, y) - center).length() if length <= self._radius: self._maskImage.setXelA(x, y, VBase4D(0, 0, 0, 0))
def pointAlongLine(self, distance): v = Vec2(self.direction) v.normalize() return self.pt1 + v * distance
def setWander(self, radius=50): self.wanderVelocity = Vec2(0, 0) self.wanderRadius = radius