Пример #1
0
 def setupTexture(self):
     cm = CardMaker('quadMaker')
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0,
                 htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     self.quad = NodePath(card)
     self.quad.reparentTo(self.parent)
     self.guiTex = Texture('guiTex')
     self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1,
                              Texture.TUnsignedByte, Texture.FRgba)
     self.guiTex.setMinfilter(Texture.FTLinear)
     self.guiTex.setKeepRamImage(True)
     self.guiTex.makeRamImage()
     self.guiTex.setWrapU(Texture.WMRepeat)
     self.guiTex.setWrapV(Texture.WMRepeat)
     ts = TextureStage('webTS')
     self.quad.setTexture(ts, self.guiTex)
     self.quad.setTexScale(ts, 1.0, -1.0)
     self.quad.setTransparency(0)
     self.quad.setTwoSided(True)
     self.quad.setColor(1.0, 1.0, 1.0, 1.0)
     self.calcMouseLimits()
Пример #2
0
 def loadFlatQuad(self, fullFilename):
     cm = CardMaker('cm-%s' % fullFilename)
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0,
                 htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     quad = NodePath(card)
     jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT)
     smallerJpgFile = PNMImage()
     readFile = smallerJpgFile.read(Filename(fullFilename))
     if readFile:
         jpgFile.copySubImage(smallerJpgFile, 0, 0)
         guiTex = Texture('guiTex')
         guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1,
                             Texture.TUnsignedByte, Texture.FRgba)
         guiTex.setMinfilter(Texture.FTLinear)
         guiTex.load(jpgFile)
         guiTex.setWrapU(Texture.WMClamp)
         guiTex.setWrapV(Texture.WMClamp)
         ts = TextureStage('webTS')
         quad.setTexture(ts, guiTex)
         quad.setTransparency(0)
         quad.setTwoSided(True)
         quad.setColor(1.0, 1.0, 1.0, 1.0)
         result = quad
     else:
         result = None
     Texture.setTexturesPower2(1)
     return result
Пример #3
0
    def nextConfig(self):
        N = self.whichConfig = (self.whichConfig + 1) % NUM_CONFIGS

        if self.envNP != None: self.envNP.removeNode()
        if self.pathNP != None: self.pathNP.removeNode()

        self.environment = Environment(OBSTACLE_FILE,\
               ALL_CONFIGS[N][0], ALL_CONFIGS[N][1], ALL_CONFIGS[N][2])
        self.environment.dump()
        print("Start: " + self.environment.start.__str__())
        print("End: " + self.environment.end.__str__())
        print("Shooter: " + self.environment.shooterPos.__str__())
        shortestPath = getShortestPath(self.environment)
        print("Path: ")
        print(shortestPath)
        self.envNP = render.attachNewNode(self.environment.produceRending())
        self.pathNP = render.attachNewNode(
            self.environment.renderPath(shortestPath,
                                        Vec4(1.000, 0.647, 0.000, 1)))
        for i in range(len(self.environment.obstaclesWalls)):
            wall = self.environment.obstaclesWalls[i]
            ls = LineSegment(Point2(300, -300), Point2(-300, 400))
            I = ls.intersectLines(wall)
            if I[1] == 1:
                print(i)
Пример #4
0
 def __init__(self, manager, xml):
     self.texture = loader.loadTexture('data/textures/bullet-hole.png')
     self.texture.setMinfilter(Texture.FTLinearMipmapLinear)
     self.container = render.attachNewNode(ModelRoot('bullet-holes'))
     self.card = CardMaker('bullet-hole')
     s = BULLETHOLE_SIZE * 0.5
     self.card.setFrame(-s, s, -s, s)
     self.card.setUvRange(Point2(0, 0), Point2(1, 1))
Пример #5
0
    def loadFlatQuad(self, fullFilename):
        """Load the flat jpg into a quad."""
        assert self.notify.debugStateCall(self)
        #Texture.setTexturesPower2(AutoTextureScale.ATSUp)
        #Texture.setTexturesPower2(2)
        
        cm = CardMaker('cm-%s'%fullFilename)
        cm.setColor(1.0, 1.0, 1.0, 1.0)
        aspect = base.camLens.getAspectRatio()
        htmlWidth = 2.0*aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)		
        htmlHeight = 2.0*float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) 

        # the html area will be center aligned and vertically top aligned
        #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0)
        cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, - htmlHeight / 2.0, htmlHeight / 2.0)

        bottomRightX = (WEB_WIDTH_PIXELS) / float( WEB_WIDTH +1)
        bottomRightY = WEB_HEIGHT_PIXELS / float (WEB_HEIGHT+1)

        #cm.setUvRange(Point2(0,0), Point2(bottomRightX, bottomRightY))
        cm.setUvRange(Point2(0,1-bottomRightY), Point2(bottomRightX,1))
        
        card = cm.generate()
        quad = NodePath(card)
        #quad.reparentTo(self.parent)

        jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT)
        smallerJpgFile = PNMImage()
        readFile = smallerJpgFile.read(Filename(fullFilename))
        if readFile:
            jpgFile.copySubImage(smallerJpgFile, 0, 0)

            guiTex = Texture("guiTex")
            guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
            guiTex.setMinfilter(Texture.FTLinear)
            guiTex.load(jpgFile)
            #guiTex.setKeepRamImage(True)		
            #guiTex.makeRamImage()				
            guiTex.setWrapU(Texture.WMClamp)
            guiTex.setWrapV(Texture.WMClamp)

            ts = TextureStage('webTS')
            quad.setTexture(ts, guiTex)
            #quad.setTexScale(ts, 1.0, -1.0)

            quad.setTransparency(0)
            quad.setTwoSided(True)
            quad.setColor(1.0, 1.0, 1.0, 1.0)
            result= quad
        else:
            # if we have an error loading the file, return None to signify an error
            result = None

        #Texture.setTexturesPower2(AutoTextureScale.ATSDown)
        Texture.setTexturesPower2(1)
        return result
Пример #6
0
	def UpdateSelRect(self, task): 
		#Make sure we hae the mouse 
		if not base.mouseWatcherNode.hasMouse(): 
			return Task.cont 
		mpos = base.mouseWatcherNode.getMouse() 
		t = globalClock.getRealTime() 
		#First check the mouse position is different 
		if self.pt2LastMousePos != mpos: 
			self.booMouseMoved = True 
			#We only need to check this function every once in a while 
			if (t - self.fTimeLastUpdateSelRect) > self.UpdateTimeSelRect: 
				self.fTimeLastUpdateSelRect =  t 
				self.pt2LastMousePos = Point2(mpos) 
					 
				#Update the selection rectange graphically 
				d = self.pt2LastMousePos - self.pt2InitialMousePos 
				self.npSelRect.setScale(d[0] if d[0] else 1e-3, 1, d[1] if d[1] else 1e-3) 
				
		if (abs(self.pt2InitialMousePos[0] - self.pt2LastMousePos[0]) > .01) & (abs(self.pt2InitialMousePos[1] - self.pt2LastMousePos[1]) > .01): 
			if (t - self.fTimeLastUpdateSelected) > self.UpdateTimeSelected: 
				#A better way to handle a large number of objects is to first transform the 2-d selection rect into 
				#its own view fustrum and then check the objects in world space. Adding space correlation/hashing 
				#will make it go faster. But I'm lazy. 
				self.fTimeLastUpdateSelected = t 
				self.listLastSelected = self.listSelected 
				self.listSelected = [] 
				#Get the bounds of the selection box 
				fMouse_Lx = min(self.pt2InitialMousePos[0], self.pt2LastMousePos[0]) 
				fMouse_Ly = max(self.pt2InitialMousePos[1], self.pt2LastMousePos[1]) 
				fMouse_Rx = max(self.pt2InitialMousePos[0], self.pt2LastMousePos[0]) 
				fMouse_Ry = min(self.pt2InitialMousePos[1], self.pt2LastMousePos[1]) 
				for i in self.listConsideration: 
					if type(i) != libpanda.NodePath: 
						raise 'Unknown objtype in selection' 
					else: 
						#Get the loosebounds of the nodepath 
						sphBounds = i.getBounds() 
						#Put the center of the sphere into the camera coordinate system 
						#p3 = base.cam.getRelativePoint(render, sphBounds.getCenter()) 
						p3 = base.cam.getRelativePoint(i.getParent(), sphBounds.getCenter()) 
						#Check if p3 is in the view fustrum 
						p2 = Point2() 
						if base.camLens.project(p3, p2): 
							if (p2[0] >= fMouse_Lx) & (p2[0] <= fMouse_Rx) & (p2[1] >= fMouse_Ry) & (p2[1] <= fMouse_Ly): 
								self.listSelected.append(i) 
								self.funcSelectActionOnObject(i) 
				for i in self.listLastSelected: 
					if not objKeyBoardModifiers.booControl: 
						if i not in self.listSelected: 
							self.funcDeselectActionOnObject(i) 
							pass
					else: 
						self.listSelected.append(i) 
		
		return Task.cont 
Пример #7
0
	def OnStartSelect(self): 
		if not base.mouseWatcherNode.hasMouse(): 
			return 
		self.booMouseMoved = False 
		self.booSelecting = True 
		self.pt2InitialMousePos = Point2(base.mouseWatcherNode.getMouse()) 
		self.pt2LastMousePos = Point2(self.pt2InitialMousePos) 
		self.npSelRect.setPos(self.pt2InitialMousePos[0], 1, self.pt2InitialMousePos[1]) 
		self.npSelRect.setScale(1e-3, 1, 1e-3) 
		self.npSelRect.show() 
		self.taskUpdateSelRect = taskMgr.add(self.UpdateSelRect, "UpdateSelRect") 
		self.taskUpdateSelRect.lastMpos = None 
Пример #8
0
	def newGame(self):
		N = WINDOW_SZ / 4
		speed = getRandom(20, 50)
		
		self.avatar.kinematic.position = Point2(-N, -N)
		self.avatar.kinematic.orientation = getRandom(0, 360)
		heading = getRandom(0, 360) 
		self.avatar.kinematic.velocity = directionalVector(heading, speed) 
		
		self.target.kinematic.position = Point2(N, N)
		self.target.kinematic.orientation = getRandom(0, 360)
		heading = getRandom(0, 360) 
		self.target.kinematic.velocity = directionalVector(heading, speed) 
Пример #9
0
    def makeCard(self, color, width, height, i, j, divisions):
        divisions = float(divisions)
        x = i / divisions
        y = j / divisions
        d = 1 / divisions

        card = CardMaker("wall")
        card.setColor(*color)
        card.setFrame(width * (x * 2 - 1), width * ((x + d) * 2 - 1),
                      height * (y * 2 - 1), height * ((y + d) * 2 - 1))
        card.setUvRange(Point2(width * x, height * y),
                        Point2(width * (x + d), height * (y + d)))
        card.setHasUvs(True)
        card.setHasNormals(True)
        node = self.node.attachNewNode(card.generate())
    def _projectPointToLine(self, point, line):
        x1, y1, x2, y2 = line
        x, y = point

        origin = Point2(x1, y1)
        vecLine = Point2(x2, y2) - origin
        vecPoint = Point2(x, y) - origin

        projectedPoint = vecPoint.project(vecLine)
        if projectedPoint.lengthSquared() > vecLine.lengthSquared():
            return None
        elif projectedPoint.dot(vecLine) < 0:
            return None

        return origin + projectedPoint
Пример #11
0
	def __init__(self):
		global taskMgr, base
		# Initialize the ShowBase class from which we inherit, which will
		# create a window and set up everything we need for rendering into it.
		ShowBase.__init__(self)
		
		lens = OrthographicLens()
		lens.setFilmSize(WINDOW_SZ, WINDOW_SZ)
		base.cam.node().setLens(lens)

		# Disable default mouse-based camera control.  This is a method on the
		# ShowBase class from which we inherit.
		self.disableMouse()
		
		# point camera down onto x-y plane
		camera.setPos(LVector3(0, 0, 1))
		camera.setP(-90)
		
		self.setBackgroundColor((0, 0, 0, 1))
		self.bg = loadObject("stars.jpg", WINDOW_SZ, (0, 0, 0, 1))
		
		self.accept("escape", sys.exit)  # Escape quits
		self.accept("space", self.newGame, [])  # Escape quits
	
		speed = random.random() * 45 + 5
		N = WINDOW_SZ / 2
		
		targetColor = (1, 0, 0, 1)
		target = loadObject("ship.png", 2*AVATAR_RAD, targetColor)
		targetKinematic = Kinematic(Point2(0, 0), 0, speed, target, WINDOW_SZ)
		#targetSteering = KinematicCircular(targetKinematic)
		#targetSteering = KinematicStationary(targetKinematic)
		targetSteering = KinematicLinear(targetKinematic)
		self.target = PlayerAndMovement(targetKinematic, targetSteering)
		
		avatarColor = (0, 1, 0, 1)
		avatar = loadObject("ship.png", 2*AVATAR_RAD, avatarColor)
		avatarKinematic = Kinematic(Point2(0, 0), 0, speed, avatar, WINDOW_SZ)

		avatarLinear = KinematicLinear(avatarKinematic)
		avatarSeek = KinematicSeek(avatarKinematic, targetKinematic)
		avatarFlee = KinematicFlee(avatarKinematic, targetKinematic)
		steerings = { 'Linear' : avatarLinear, 'Seek' : avatarSeek, 'Flee' : avatarFlee }
		fsm = SteeringFSM()
		self.avatarSteering = KinematicFSM(avatarKinematic, targetKinematic, fsm, steerings)
		self.avatar = PlayerAndMovement(avatarKinematic, self.avatarSteering)
		self.newGame()
		self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
Пример #12
0
    def startupPerformMany(self):
        speed = random.random() * 45 + 5
        colors = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1),
                  (0, 1, 1, 1), (1, 0, 1, 1)]

        numObjects = 50
        kinematics = []

        # Create the kinematics
        for i in range(numObjects):
            targetColor = colors[i % len(colors)]
            pandaObject = loadObject("ship.png", 2 * AVATAR_RAD, targetColor)
            kinematic = Kinematic(Point2(0, 0), 0, speed, pandaObject,
                                  WINDOW_SZ)
            kinematics.append(kinematic)

        self.steeringObjects = []
        # Create the steering objects
        for i in range(len(kinematics)):
            thisKinematic = kinematics[i]
            otherKinematics = kinematics[0:i] + kinematics[i + 1:]
            separate = SteeringSeparate(thisKinematic, otherKinematics, 100)
            matchVelocity = SteeringMatchVelocity(thisKinematic,
                                                  otherKinematics)
            self.steeringObjects.append(
                PlayerAndMovement(thisKinematic, separate))
Пример #13
0
 def loadObject(self, tex=None, pos='default', depth=55, scale=1,
            transparency=True, parent='cam', model='plane', glow=0):
     if pos == 'default':
         pos = Point2(0,0)
     if parent == 'cam':
         parent = camera
     scaleX = 187.5
     scaleZ = 117.1875
     obj = loader.loadModelCopy('%s%s' % (self.guiMediaPath, model)) #default object uses the plane model
     if parent:
         obj.reparentTo(parent)              #Everything is parented to the camera so
                                         #that it faces the screen
     obj.setPos(Point3(pos.getX(), depth, pos.getY())) #Set initial position
     obj.setSx(scaleX)
     obj.setSz(scaleZ)
     obj.setBin("unsorted", 0)           #This tells Panda not to worry about the
                                         #order this is drawn in. (it prevents an
                                         #effect known as z-fighting)
     if transparency: obj.setTransparency(1) #All of our objects are trasnparent
     if tex:
         tex = loader.loadTexture('%s%s.png' % (self.guiMediaPath, tex)) #Load the texture
         obj.setTexture(tex, 1)                           #Set the texture
   
     self.sims.append(obj)
     obj.setShaderInput('glow',Vec4(glow,0,0,0),glow)
     return obj
Пример #14
0
 def enterHeightDrag(self):
     app.selected_object = app.mouse.hovered_object
     if app.selected_object:
         app.selected_object.old_height = app.selected_object.height
         app.mouse.drag_start = Point2(app.mouse.pos.getX(),
                                       app.mouse.pos.getY())
         app.mouse.task = app.mouse.height_drag
    def addPolygon(self, points):
        newVertices = []
        for i, point in enumerate(points):
            prevPoint = points[i - 1]
            x, y = point

            # Add a boundary line from the previous to here:
            x2, y2 = prevPoint
            self.borders.append((x2, y2, x, y))

            # Create our vertex:
            vertex = AStarVertex(Point2(x, y))
            self.vertices.append(vertex)
            newVertices.append(vertex)

        # Now set up the polygonal neighbors on all vertices:
        for i, vertex in enumerate(newVertices):
            prevVertex = newVertices[i - 1]
            nextVertex = newVertices[(i + 1) % len(newVertices)]

            vertex.setPolygonalNeighbors(prevVertex, nextVertex)
            vertex.extrudeVertex(self.VERTEX_EXTRUSION)

            if vertex.interiorAngle > 180:
                # This vertex is concave. Nothing is ever going to *walk to* it
                # in order to go somewhere else, so we can actually exclude it
                # from the pathfinding system.
                self.vertices.remove(vertex)
Пример #16
0
    def startupSeparateOne(self):
        speed = random.random() * 45 + 5

        numObjects = 50
        kinematics = []

        # Create the kinematics
        for i in range(numObjects):
            if i == 0:
                targetColor = (0, 1, 0, 1)
            else:
                targetColor = (1, 1, 1, 1)
            pandaObject = loadObject("ship.png", 2 * AVATAR_RAD, targetColor)
            kinematic = Kinematic(Point2(0, 0), 0, speed, pandaObject,
                                  WINDOW_SZ)
            kinematics.append(kinematic)

        self.steeringObjects = []
        # Create the steering objects
        for i in range(len(kinematics)):
            thisKinematic = kinematics[i]
            otherKinematics = kinematics[0:i] + kinematics[i + 1:]
            if i == 0:
                steering = SteeringSeparate(thisKinematic, otherKinematics,
                                            100)
            else:
                steering = SteeringLinear(thisKinematic)
            self.steeringObjects.append(
                PlayerAndMovement(thisKinematic, steering))
Пример #17
0
    def getMousePosition(self):
        if base.mouseWatcherNode.hasMouse():
            x = base.mouseWatcherNode.getMouseX()
            y = base.mouseWatcherNode.getMouseY()
            self.lastMousePos = Point2(x, y)

        return self.lastMousePos
Пример #18
0
    def OnMouseRelease(self):
        if not (self.isMouseInWindow()):
            return task.cont
        if (self.taskUpdateSelectRect != 0):
            taskMgr.remove(self.taskUpdateSelectRect)

        #Lets see if our mouse moved at all
        if (abs(self.pt2InitMousePos[0] - self.pt2LastMousePos[0]) <= .01) & (
                abs(self.pt2InitMousePos[1] - self.pt2LastMousePos[1]) <= .01):
            # we didn't move, so this is a single selection

            for i in self.selectable:

                #Get our distance from the camera (though i don't get the math)
                fTempObjDist = 2 * (base.camLens.getFar())**2

                #Get the bounds of the object
                sphBounds = i.getBounds()

                #Lets get our point in 3d space of the object in question
                p3 = base.cam.getRelativePoint(i.getParent(),
                                               sphBounds.getCenter())

                #Lets get the radius of said object
                r = sphBounds.getRadius()

                #Ok so we are obviously getting the screen width here .All be it complicated - and over my head :-)
                #radius / (X * tangent(radians(FieldOfView Horizontal / 2)))
                screen_width = r / (p3[1] *
                                    math.tan(math.radians(self.fFovh / 2)))

                #radius  / (X * tangent(radians(FieldOfView Vertical /2)))
                screen_height = r / (p3[1] *
                                     math.tan(math.radians(self.fFovv / 2)))

                #Lets get our point in a 2d Field
                p2 = Point2()
                base.camLens.project(p3, p2)

                #Ok lets make sure our mouse position is roughly inside the bounds of the object in question
                if (self.pt2InitMousePos[0] >= (p2[0] - screen_width / 2)):
                    if (self.pt2InitMousePos[0] <= (p2[0] + screen_width / 2)):
                        if (self.pt2InitMousePos[1] >=
                            (p2[1] - screen_height / 2)):
                            if (self.pt2InitMousePos[1] <=
                                (p2[1] + screen_height / 2)):

                                #We check the obj's distance to the camera and choose the closest one
                                #Umm what? Me = no understand
                                dist = p3[0]**2 + p3[1]**2 + p3[2]**2 - r**2
                                if dist < fTempObjDist:
                                    fTempObjDist = dist
                                    self.previousSelect.append(i)
                                    i.showBounds()

        self.selectFrame.hide()
        self.selecting = False

        return
Пример #19
0
 def newGame(self):
     for obj in self.steeringObjects:
         speed = getRandom(20, 50)
         obj.kinematic.position = Point2(getRandom(-WINDOW_SZ / 2.0, 0),
                                         getRandom(-WINDOW_SZ / 2.0, 0))
         orientation = randomRadians()
         obj.kinematic.orientation = orientation
         obj.kinematic.velocity = directionalVector(orientation, speed)
Пример #20
0
 def processObstacle(self, toks):
     vals = [int(v) for v in toks]
     xs = vals[0::2]
     ys = vals[1::2]
     pts = []
     for i in range(len(xs)):
         pts.append(Point2(xs[i], ys[i]))
     return pts
Пример #21
0
 def update(self, task):
     casterpos = Point2()
     base.camLens.project(self.sun.getPos(base.cam), casterpos)
     self.finalQuad.setShaderInput(
         'casterpos',
         Vec4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5),
              0, 0))
     return task.cont
 def reset(self):
     RepairMincroGame.reset(self)
     self.lastMousePos = Point2(0.0, 0.0)
     self.isMouseDown = False
     self.randomizeBoard()
     self.repairGame.gui.setTutorial(self.name)
     self.brush.stash()
     self.repairGame.gui.setTitle(self.name)
    def __init__(self,
                 name,
                 nrplates,
                 width,
                 height,
                 shaderfile,
                 texturefile,
                 uvlist,
                 jitter=-1):
        #print name, nrplates, width, height, shaderfile, texturefile, uvlist, jitter
        self.name = name
        self.texturefile = texturefile
        self.shaderfile = shaderfile

        self.np = NodePath('leaf')

        self.tex = loader.loadTexture('textures/' + texturefile)
        self.tex.setMinfilter(Texture.FTLinearMipmapLinear)
        self.tex.setMagfilter(Texture.FTLinearMipmapLinear)
        self.tex.setAnisotropicDegree(2)
        self.np.setTexture(self.tex)
        self.np.setTwoSided(True)
        self.np.setTransparency(TransparencyAttrib.MAlpha)
        #self.np.setTransparency( TransparencyAttrib.MMultisample )
        self.np.setDepthWrite(False)

        maker = CardMaker('leaf')
        maker.setFrame(-width / 2.0, width / 2.0, 0, height)
        #maker.setFrame( 0,1,0,1)
        for i in range(nrplates):
            if uvlist != None:
                maker.setUvRange(uvlist[i][0], uvlist[i][1])
            else:
                maker.setUvRange(Point2(0, 0), Point2(1, 0.98))
            node = self.np.attachNewNode(maker.generate())
            #node.setTwoSided( True )
            node.setHpr(i * 180.0 / nrplates, 0, 0)
        self.np.flattenStrong()
        #np.flattenLight()
        #np.setTwoSided( True )

        if jitter == -1:
            self.jitter = height / width / 2
        else:
            self.jitter = jitter
Пример #24
0
 def update(self, task = None):
     """Updates the shader inputs that need to be updated every frame.
     Normally, you shouldn't call this, it's being called in a task."""
     if self.configuration.has_key("VolumetricLighting"):
         caster = self.configuration["VolumetricLighting"].caster
         casterpos = Point2()
         self.manager.camera.node().getLens().project(caster.getPos(self.manager.camera), casterpos)
         self.finalQuad.setShaderInput("casterpos", Vec4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5), 0, 0))
     if task != None:
         return task.cont
Пример #25
0
Файл: GXO.py Проект: crempp/psg
    def _get2D(self, nodePath):
        #get the position of the light source relative to the cam
        p3d = base.cam.getRelativePoint(nodePath, Point3(0, 0, 0))
        p2d = Point2()

        #project the light source into the viewing plane and return 2d coordinates, if it is in the visible area(read: not behind the cam)
        if base.cam.node().getLens().project(p3d, p2d):
            return p2d

        return None
Пример #26
0
    def update(self, task=None):
        if self.configuration.has_key('VolumetricLighting'):
            caster = self.configuration['VolumetricLighting'].caster
            casterpos = Point2()
            self.manager.camera.node().getLens().project(
                caster.getPos(self.manager.camera), casterpos)
            self.finalQuad.setShaderInput(
                'casterpos',
                Vec4(casterpos.getX() * 0.5 + 0.5,
                     casterpos.getY() * 0.5 + 0.5, 0, 0))

        if task != None:
            return task.cont
Пример #27
0
    def OnStartSelect(self):
        if (not self.isMouseInWindow()):
            return

        #Lets clear our last selection
        for selected in self.previousSelect:
            print "Hiding bounds for ", selected
            selected.hideBounds()

        self.selecting = True
        self.pt2InitMousePos = Point2(base.mouseWatcherNode.getMouse())
        self.pt2LastMousePos = Point2(self.pt2InitMousePos)

        self.selectFrame.setPos(self.pt2InitMousePos[0], 1,
                                self.pt2InitMousePos[1])
        self.selectFrame.setScale(1e-3, 1, 1e-3)
        self.selectFrame.show()

        self.taskUpdateSelectRect = taskMgr.add(self.UpdateSelectRect,
                                                "UpdateSelectRect")
        self.taskUpdateSelectRect.lastMpos = None

        return
Пример #28
0
	def OnStopSelect(self): 
		if not base.mouseWatcherNode.hasMouse(): 
			return 
		if self.taskUpdateSelRect != 0: 
			taskMgr.remove(self.taskUpdateSelRect) 
		self.npSelRect.hide() 
		self.booSelecting = False 
		#If the mouse hasn't moved, it's a point selection 
		if (abs(self.pt2InitialMousePos[0] - self.pt2LastMousePos[0]) <= .01) & (abs(self.pt2InitialMousePos[1] - self.pt2LastMousePos[1]) <= .01): 
			objTempSelected = 0 
			fTempObjDist = 2*(base.camLens.getFar())**2 
			for i in self.listConsideration: 
				if type(i) != libpanda.NodePath: 
					raise 'Unknown objtype in selection' 
				else:
					sphBounds = i.getBounds() 
					#p3 = base.cam.getRelativePoint(render, sphBounds.getCenter()) 
					p3 = base.cam.getRelativePoint(i.getParent(), sphBounds.getCenter()) 
					r = sphBounds.getRadius() 
					screen_width = r/(p3[1]*math.tan(math.radians(self.fFovh/2))) 
					screen_height = r/(p3[1]*math.tan(math.radians(self.fFovv/2))) 
					p2 = Point2() 
					base.camLens.project(p3, p2) 
					#If the mouse pointer is in the "roughly" screen-projected bounding volume 
					if (self.pt2InitialMousePos[0] >= (p2[0] - screen_width/2)): 
						if (self.pt2InitialMousePos[0] <= (p2[0] + screen_width/2)): 
							if (self.pt2InitialMousePos[1] >= (p2[1] - screen_height/2)): 
								if (self.pt2InitialMousePos[1] <= (p2[1] + screen_height/2)):
									#We check the obj's distance to the camera and choose the closest one 
									dist = p3[0]**2+p3[1]**2+p3[2]**2 - r**2 
									if dist < fTempObjDist: 
										fTempObjDist = dist 
										objTempSelected = i 
			#if something is click-selected
			if objTempSelected != 0: 
				if objKeyBoardModifiers.booControl: 
					self.listSelected.append(objTempSelected) 
				else: 
					for i in self.listSelected: 
						self.funcDeselectActionOnObject(i) 
					self.listSelected = [objTempSelected] 
				self.funcSelectActionOnObject(objTempSelected) 
			#if nothing is selected just deselect all, a normal behaviour in RTS's game
			if objTempSelected == 0:
				for i in self.listSelected:
					self.funcDeselectActionOnObject(i)
					self.listSelected = []
		messenger.send("mouse-selection")
Пример #29
0
    def IsNodePathInside( self, np ):
        """Test if the specified node path lies within the marquee area."""
        npWorldPos = np.getPos( self.rootNp )
        p3 = self.camera.getRelativePoint( self.rootNp, npWorldPos )

        # Convert it through the lens to render2d coordinates
        p2 = Point2()
        if not self.camera.GetLens().project( p3, p2 ):
            return False
        
        # Test point is within bounds of the marquee
        min, max = self.getTightBounds()
        if ( p2.getX() > min.getX() and p2.getX() < max.getX() and 
             p2.getY() > min.getZ() and p2.getY() < max.getZ() ):
            return True
        
        return False
Пример #30
0
 def mouse_task(self, task):
     action = task.cont
     # if the current tile has a mouse point to this
     self.has_mouse = base.mouseWatcherNode.hasMouse()
     if self.has_mouse:
         self.pos = base.mouseWatcherNode.getMouse()
         if self.prev_pos:
             self.delta = self.pos - self.prev_pos
         else:
             self.delta = None
         if self.task:
             action = self.task(task)
     else:
         self.pos = None
     if self.pos:
         self.prev_pos = Point2(self.pos.getX(), self.pos.getY())
     return action