Esempio n. 1
0
 def traverse(self, nodePath, dnaStorage):
     node = PandaNode(self.name)
     node = nodePath.attachNewNode(node, 0)
     node.setPosHprScale(self.pos, self.hpr, self.scale)
     for child in self.children:
         child.traverse(node, dnaStorage)
     node.flattenMedium()
Esempio n. 2
0
    def __init__(self, name):
        FSM.__init__(self, name)
        PandaNode.__init__(self, name)
        DirectObject.__init__(self)

        self.active = True

        self.lastClickState = PGButton.SReady
        self.clickState = PGButton.SReady

        self.__hovering = False

        self.clickEvent = ''
        self.clickExtraArgs = []

        self.contents = NodePath.anyPath(self).attachNewNode('contents')

        # Create a MouseWatcherRegion:
        self.regionName = self.getUniqueName() + '-region'
        self.region = MouseWatcherRegion(self.regionName, 0, 0, 0, 0)
        base.mouseWatcherNode.addRegion(self.region)

        # Accept the mouse events:
        enterPattern = base.mouseWatcherNode.getEnterPattern()
        leavePattern = base.mouseWatcherNode.getLeavePattern()
        buttonDownPattern = base.mouseWatcherNode.getButtonDownPattern()
        buttonUpPattern = base.mouseWatcherNode.getButtonUpPattern()
        self.accept(enterPattern.replace('%r', self.regionName), self.__handleMouseEnter)
        self.accept(leavePattern.replace('%r', self.regionName), self.__handleMouseLeave)
        self.accept(buttonDownPattern.replace('%r', self.regionName), self.__handleMouseDown)
        self.accept(buttonUpPattern.replace('%r', self.regionName), self.__handleMouseUp)
Esempio n. 3
0
    def __init__(self, *args, **argv):
        PandaNode.__init__(self, *args, **argv)

        self.pandaActor = Actor("panda-model",
                                {"walk": "panda-walk4"})
        self.pandaActor.reparentTo(self)
        print("self:" + str(self.is_empty()))
        self.pandaActor.loop("walk")
Esempio n. 4
0
 def __init__(self, name, engine=None):
     PandaNode.__init__(self, name)
     self.path = NodePath(self)
     self.mouseListeners = []
     self.hi_id = Vec4()
     if engine == None:
         engine = SelectionEngine.getDefault()
     self.engine = engine
     self.engine.register(self)
     self.path.setTag('sel', 'sel')
Esempio n. 5
0
	def makeMenu(self, name, t, parent, tipe = 'vertical'):
		sybGroup=PandaNode(name)
		parent.addChild(sybGroup)
		for item in t:# make menu syblings
			mi = self.makeItem(item, tipe)
			sybGroup.addChild(mi)
		if tipe=='vertical': verticalGroupFinish(sybGroup)
		elif tipe=='horizontal':
			horizontalGroupFinish(sybGroup)
		elif tipe=='titleBar': horizontalGroupFinish(sybGroup)
		return sybGroup
Esempio n. 6
0
    def __init__(self):
        PandaNode.__init__(self, 'PositionHandle')

        CameraController.getInstance().addEventHandler(EVT_CAMERA_MOVE,
                self._fixScale)
        self.path = NodePath(self)

        self.xHandle = DirectionHandle(self, Vec4(1, 0, 0, 0.6),
                Vec3(0, 0, 90), 'x')
        self.addChild(self.xHandle)

        self.yHandle = DirectionHandle(self, Vec4(0, 1, 0, 0.6),
                Vec3(0, -90, 0), 'y')
        self.addChild(self.yHandle)
        
        self.zHandle = DirectionHandle(self, Vec4(0, 0, 1, 0.6),
                Vec3(0, 0, 0), 'z')
        self.addChild(self.zHandle)
        
        self.hHandle = RotationHandle(self, Vec4(0, 0, 1, 0.6),
                Vec3(0, 0, 0), 'z')
        self.addChild(self.hHandle)
        NodePath(self.hHandle).setScale(1.02)

        self.pHandle = RotationHandle(self, Vec4(0, 1, 0, 0.6),
                Vec3(0, -90, 0), 'y')
        self.addChild(self.pHandle)
        NodePath(self.pHandle).setScale(0.98)

        self.rHandle = RotationHandle(self, Vec4(1, 0, 0, 0.6),
                Vec3(0, 0, 90), 'x')
        self.addChild(self.rHandle)
        self._tPressed()
        
        self.path.setTransparency(1)
        self.path.setBin('transparent', 30, 50)
        #self.path.setDepthTest(False)
        self.path.setLightOff()
        self.path.setRenderModeThickness(2)
        self.setClients([])

        self.evtWatcher = DirectObject.DirectObject()
        self.evtWatcher.accept(base.win.getWindowEvent(),
            self._windowEventHandler)
        self.evtWatcher.accept('r', self._rPressed)
        self.evtWatcher.accept('t', self._tPressed)

        self.originalPos = self.path.getPos()
        self.fLenPx = base.cam.node().getLens().getFocalLength() * base.win.getXSize()
        self._fixScale()
Esempio n. 7
0
    def __init__(self, parent, color, hpr, dim):
        PandaNode.__init__(self, dim+'rotHandle')
        self.path = NodePath(self)
        self.parent = parent
        self.dim = dim

        circle = GeomNode('gnode')
        circle.addGeomsFrom(self.geomNode)

        self.clickable = ClickableNode('clickable')
        self.clickable.addChild(circle)
        self.clickable.addMouseListener(self)
        circlenp = self.path.attachNewNode(self.clickable)

        self.path.setColor(color)
        self.path.setHpr(hpr)
        self.mDownPos = Vec2()
	def __init__(self):
		self.terrainElements=[]#holds all terrainElements
		self.terrainGrid=[[]]#holds terrainElements as they will be displayed
		self.dirty=True # the terrainGrid should be refreshed on next update
		self.rootNode = PandaNode("terrainManager root")
		self.root = NodePath( self.rootNode )
		self.terrainSize=257  #first=textureSize
		self.scale=16
		#locatoin that whereIsCamera returned last frame
		self.lastCamearaLocation = (0,0)
		self.currentCamearaLocation = (0,0)
		self.defaultBlockSize=64
Esempio n. 9
0
    def __init__(self):
        self.avatar = None
        self.active = True
        self.objectCode = None

        self.chatButton = NametagGlobals.noButton
        self.chatReversed = False

        self.font = None
        self.chatFont = None

        self.shadow = None

        self.marginManager = None
        self.visible3d = True

        self.chatType = NametagGlobals.CHAT
        self.chatBalloonType = NametagGlobals.CHAT_BALLOON

        self.nametagColor = NametagGlobals.NametagColors[NametagGlobals.CCNormal]
        self.arrowColor = NametagGlobals.NametagColors[NametagGlobals.CCNormal]
        self.chatColor = NametagGlobals.ChatColors[NametagGlobals.CCNormal]
        self.speedChatColor = VBase4(1, 1, 1, 1)

        self.wordWrap = 8
        self.chatWordWrap = 12

        self.text = ''

        self.chatPages = []
        self.chatPageIndex = 0
        self.chatTimeoutTask = None
        self.chatTimeoutTaskName = self.getUniqueName() + '-timeout'

        self.stompChatText = ''
        self.stompTask = None
        self.stompTaskName = self.getUniqueName() + '-stomp'

        self.icon = PandaNode('icon')

        self.nametag2d = Nametag2d()
        self.nametag3d = Nametag3d()

        self.nametags = set()
        self.add(self.nametag2d)
        self.add(self.nametag3d)

        # Add the tick task:
        self.tickTaskName = self.getUniqueName() + '-tick'
        self.tickTask = taskMgr.add(self.tick, self.tickTaskName, sort=45)
Esempio n. 10
0
    def __init__(self, parent, color, hpr, dim):
        PandaNode.__init__(self, dim+'handle')
        self.path = NodePath(self)
        self.parent = parent
        self.dim = dim

        arrow = GeomNode('gnode')
        arrow.addGeomsFrom(self.geomNode)
        arrownp = self.path.attachNewNode(arrow)
        arrownp.hide(BitMask32(1))
        
        clickNode = ClickableNode('clicknode')
        clickNode.setDepthLevel(0.5)
        clickNode.addMouseListener(self)
        clicknp = self.path.attachNewNode(clickNode)
        
        clickgeom = clicknp.attachNewNode(GeomNode('clicknode'))
        clickgeom.hide(BitMask32(7))
        clickgeom.node().addGeomsFrom(self.clickableGeomNode)

        linesegs = LineSegs()
        linesegs.setColor(color)
        linesegs.setThickness(2)
        linesegs.moveTo(Vec3(0, 0, -30))
        linesegs.drawTo(Vec3(0, 0, -0.5))
        linesegs.moveTo(Vec3(0, 0, 0.5))
        linesegs.drawTo(Vec3(0, 0, 30))
        lines = self.path.attachNewNode(linesegs.create())
        lines.show(BitMask32(1))
        lines.hide(BitMask32(2|4|8|16))
        lines.setBin('opaque', 30, 100)
        lines.setAntialias(AntialiasAttrib.MNone)

        self.path.setColor(color)
        self.path.setHpr(hpr)
        
        self.mDownPos = Vec2()
Esempio n. 11
0
 def traverse(self, nodePath, dnaStorage):
     node = PandaNode(self.name)
     nodePath = nodePath.attachNewNode(node, 0)
     for child in self.children_:
         child.traverse(nodePath, dnaStorage)
Esempio n. 12
0
class NametagGroup:
    CHAT_TIMEOUT_MIN = 4.0
    CHAT_TIMEOUT_MAX = 12.0
    CHAT_STOMP_DELAY = 0.2

    def __init__(self):
        self.avatar = None
        self.active = True
        self.objectCode = None

        self.chatButton = NametagGlobals.noButton
        self.chatReversed = False

        self.font = None
        self.chatFont = None

        self.shadow = None

        self.marginManager = None
        self.visible3d = True

        self.chatType = NametagGlobals.CHAT
        self.chatBalloonType = NametagGlobals.CHAT_BALLOON

        self.nametagColor = NametagGlobals.NametagColors[NametagGlobals.CCNormal]
        self.arrowColor = NametagGlobals.NametagColors[NametagGlobals.CCNormal]
        self.chatColor = NametagGlobals.ChatColors[NametagGlobals.CCNormal]
        self.speedChatColor = VBase4(1, 1, 1, 1)

        self.wordWrap = 8
        self.chatWordWrap = 12

        self.text = ''

        self.chatPages = []
        self.chatPageIndex = 0
        self.chatTimeoutTask = None
        self.chatTimeoutTaskName = self.getUniqueName() + '-timeout'

        self.stompChatText = ''
        self.stompTask = None
        self.stompTaskName = self.getUniqueName() + '-stomp'

        self.icon = PandaNode('icon')

        self.nametag2d = Nametag2d()
        self.nametag3d = Nametag3d()

        self.nametags = set()
        self.add(self.nametag2d)
        self.add(self.nametag3d)

        # Add the tick task:
        self.tickTaskName = self.getUniqueName() + '-tick'
        self.tickTask = taskMgr.add(self.tick, self.tickTaskName, sort=45)

    def destroy(self):
        if self.marginManager is not None:
            self.unmanage(self.marginManager)

        if self.tickTask is not None:
            taskMgr.remove(self.tickTask)
            self.tickTask = None

        self.clearChatText()

        for nametag in list(self.nametags):
            self.remove(nametag)

        self.nametag2d = None
        self.nametag3d = None

        if self.icon is not None:
            self.icon.removeAllChildren()
            self.icon = None

        self.chatFont = None
        self.font = None

        self.chatButton = NametagGlobals.noButton

        self.avatar = None

    def getUniqueName(self):
        return 'NametagGroup-' + str(id(self))

    def tick(self, task):
        if (self.avatar is None) or (self.avatar.isEmpty()):
            return Task.cont

        chatText = self.getChatText()
        if (NametagGlobals.forceOnscreenChat and
            chatText and
            self.chatBalloonType == NametagGlobals.CHAT_BALLOON):
            visible3d = False
        elif self.avatar == NametagGlobals.me:
            if (chatText and
                self.chatBalloonType == NametagGlobals.CHAT_BALLOON and
                not base.cam.node().isInView(self.avatar.getPos(base.cam))):
                visible3d = False
            else:
                visible3d = True
        elif NametagGlobals.force2dNametags:
            visible3d = False
        elif (not NametagGlobals.want2dNametags and
              ((not chatText) or (self.chatBalloonType != NametagGlobals.CHAT_BALLOON))):
            visible3d = True
        elif self.avatar.isHidden():
            visible3d = False
        else:
            visible3d = base.cam.node().isInView(self.avatar.getPos(base.cam))

        if visible3d != self.visible3d:
            self.visible3d = visible3d
            if self.nametag2d is not None:
                self.nametag2d.setVisible(not visible3d)

        return Task.cont

    def setAvatar(self, avatar):
        self.avatar = avatar
        for nametag in self.nametags:
            nametag.setAvatar(self.avatar)

    def getAvatar(self):
        return self.avatar

    def setActive(self, active):
        self.active = active
        for nametag in self.nametags:
            nametag.setActive(self.active)

    def getActive(self):
        return self.active

    def setObjectCode(self, objectCode):
        self.objectCode = objectCode

    def getObjectCode(self):
        return self.objectCode

    def setChatButton(self, chatButton):
        self.chatButton = chatButton
        for nametag in self.nametags:
            nametag.setChatButton(self.chatButton)

    def getChatButton(self):
        return self.chatButton

    def hasChatButton(self):
        return self.chatButton != NametagGlobals.noButton

    def setChatReversed(self, reversed):
        self.chatReversed = reversed
        for nametag in self.nametags:
            nametag.setChatReversed(reversed)

    def getChatReversed(self):
        return self.chatReversed

    def setFont(self, font):
        self.font = font
        for nametag in self.nametags:
            nametag.setFont(self.font)

    def getFont(self):
        return self.font

    def setChatFont(self, chatFont):
        self.chatFont = chatFont
        for nametag in self.nametags:
            nametag.setChatFont(self.chatFont)

    def getChatFont(self):
        return self.chatFont

    def setShadow(self, shadow):
        self.shadow = shadow
        for nametag in self.nametags:
            nametag.setShadow(self.shadow)

    def getShadow(self):
        return self.shadow

    def clearShadow(self):
        self.shadow = None
        for nametag in self.nametags:
            nametag.clearShadow()

    def setChatType(self, chatType):
        self.chatType = chatType
        for nametag in self.nametags:
            nametag.setChatType(self.chatType)

    def getChatType(self):
        return self.chatType

    def setChatBalloonType(self, chatBalloonType):
        self.chatBalloonType = chatBalloonType
        for nametag in self.nametags:
            nametag.setChatBalloonType(self.chatBalloonType)

    def getChatBalloonType(self):
        return self.chatBalloonType

    def setNametagColor(self, nametagColor):
        self.nametagColor = nametagColor
        for nametag in self.nametags:
            nametag.setNametagColor(self.nametagColor)

    def getNametagColor(self):
        return self.nametagColor

    def setArrowColor(self, arrowColor):
        self.arrowColor = arrowColor
        for nametag in self.nametags:
            nametag.setArrowColor(self.arrowColor)

    def getArrowColor(self):
        return self.arrowColor

    def setChatColor(self, chatColor):
        self.chatColor = chatColor
        for nametag in self.nametags:
            nametag.setChatColor(self.chatColor)

    def getChatColor(self):
        return self.chatColor

    def setSpeedChatColor(self, speedChatColor):
        self.speedChatColor = speedChatColor
        for nametag in self.nametags:
            nametag.setSpeedChatColor(self.speedChatColor)

    def getSpeedChatColor(self):
        return self.speedChatColor

    def setWordWrap(self, wordWrap):
        self.wordWrap = wordWrap
        for nametag in self.nametags:
            nametag.setWordWrap(self.wordWrap)

    def getWordWrap(self):
        return self.wordWrap

    def setChatWordWrap(self, chatWordWrap):
        self.chatWordWrap = chatWordWrap
        for nametag in self.nametags:
            nametag.setChatWordWrap(self.chatWordWrap)

    def getChatWordWrap(self):
        return self.chatWordWrap

    def setText(self, text):
        self.text = text
        for nametag in self.nametags:
            nametag.setText(self.text)
            nametag.update()

    def getText(self):
        return self.text

    def getNumChatPages(self):
        return len(self.chatPages)

    def setChatPageIndex(self, chatPageIndex):
        if chatPageIndex >= self.getNumChatPages():
            return

        self.chatPageIndex = chatPageIndex
        for nametag in self.nametags:
            nametag.setChatText(self.chatPages[self.chatPageIndex])
            nametag.update()

    def getChatPageIndex(self):
        return self.chatPageIndex

    def setChatText(self, chatText, timeout=False):
        # If we are currently displaying chat text, we need to "stomp" it. In
        # other words, we need to clear the current chat text, pause for a
        # brief moment, and then display the new chat text:
        if self.getChatText():
            self.clearChatText()
            self.stompChatText = chatText
            self.stompTask = taskMgr.doMethodLater(
                self.CHAT_STOMP_DELAY, self.__chatStomp, self.stompTaskName,
                extraArgs=[timeout])
            return

        self.clearChatText()

        self.chatPages = chatText.split('\x07')
        self.setChatPageIndex(0)

        if timeout:
            delay = len(self.getChatText()) * 0.5
            if delay < self.CHAT_TIMEOUT_MIN:
                delay = self.CHAT_TIMEOUT_MIN
            elif delay > self.CHAT_TIMEOUT_MAX:
                delay = self.CHAT_TIMEOUT_MAX
            self.chatTimeoutTask = taskMgr.doMethodLater(
                delay, self.clearChatText, self.chatTimeoutTaskName)

    def getChatText(self):
        if self.chatPageIndex >= self.getNumChatPages():
            return ''
        return self.chatPages[self.chatPageIndex]

    def clearChatText(self, task=None):
        if self.stompTask is not None:
            taskMgr.remove(self.stompTask)
            self.stompTask = None

        self.stompChatText = ''

        if self.chatTimeoutTask is not None:
            taskMgr.remove(self.chatTimeoutTask)
            self.chatTimeoutTask = None

        self.chatPages = []
        self.chatPageIndex = 0

        for nametag in self.nametags:
            nametag.setChatText('')
            nametag.update()

        if task is not None:
            return Task.done

    def getStompChatText(self):
        return self.stompChatText

    def setIcon(self, icon):
        self.icon = icon
        for nametag in self.nametags:
            nametag.setIcon(self.icon)

    def getIcon(self):
        return self.icon

    def setNametag2d(self, nametag2d):
        if self.nametag2d is not None:
            self.remove(self.nametag2d)
            self.nametag2d = None

        if nametag2d is None:
            return

        self.nametag2d = nametag2d
        self.add(self.nametag2d)

    def getNametag2d(self):
        return self.nametag2d

    def setNametag3d(self, nametag3d):
        if self.nametag3d is not None:
            self.remove(self.nametag3d)
            self.nametag3d = None

        if nametag3d is None:
            return

        self.nametag3d = nametag3d
        self.add(self.nametag3d)

    def getNametag3d(self):
        return self.nametag3d

    def add(self, nametag):
        self.nametags.add(nametag)
        nametag.setAvatar(self.avatar)
        nametag.setActive(self.active)
        nametag.setClickEvent(self.getUniqueName())
        nametag.setChatButton(self.chatButton)
        nametag.setFont(self.font)
        nametag.setChatFont(self.chatFont)
        nametag.setChatType(self.chatType)
        nametag.setChatBalloonType(self.chatBalloonType)
        nametag.setNametagColor(self.nametagColor)
        nametag.setArrowColor(self.arrowColor)
        nametag.setChatColor(self.chatColor)
        nametag.setSpeedChatColor(self.speedChatColor)
        nametag.setWordWrap(self.wordWrap)
        nametag.setChatWordWrap(self.chatWordWrap)
        nametag.setText(self.text)
        nametag.setChatText(self.getChatText())
        nametag.setIcon(self.icon)
        nametag.update()

    def remove(self, nametag):
        nametag.destroy()
        self.nametags.remove(nametag)

    def updateAll(self):
        for nametag in self.nametags:
            nametag.update()

    def manage(self, marginManager):
        if self.marginManager is not None:
            self.unmanage(self.marginManager)
        self.marginManager = marginManager
        for nametag in self.nametags:
            if isinstance(nametag, MarginVisible):
                nametag.manage(self.marginManager)

    def unmanage(self, marginManager):
        if marginManager != self.marginManager:
            return
        if self.marginManager is None:
            return
        self.marginManager = marginManager
        for nametag in self.nametags:
            if isinstance(nametag, MarginVisible):
                nametag.unmanage(self.marginManager)

    def hideNametag(self):
        for nametag in self.nametags:
            nametag.hideNametag()

    def showNametag(self):
        for nametag in self.nametags:
            nametag.showNametag()

    def hideChat(self):
        for nametag in self.nametags:
            nametag.hideChat()

    def showChat(self):
        for nametag in self.nametags:
            nametag.showChat()

    def hideThought(self):
        for nametag in self.nametags:
            nametag.hideThought()

    def showThought(self):
        for nametag in self.nametags:
            nametag.showThought()

    def __chatStomp(self, timeout=False):
        self.setChatText(self.stompChatText, timeout=timeout)
        self.stompChatText = ''
Esempio n. 13
0
    def __init__(self):
        # Sound
        
        self.collectSoundEffect = loader.loadMusic("sounds/item_collect.mp3")
        
        self.footstepSound = loader.loadMusic("sounds/footsteps.mp3")
        self.footstepSound.setLoop(1);
        
        audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], base.camera)
        
        self.musicend = loader.loadMusic("sounds/Enchanted-Woods.mp3")
    
        # Sky Box
        starTexture = loader.loadTexture("models/stars.jpg")
        self.sky = loader.loadModel("models/box.egg")
        self.sky.setScale(300)
        self.sky.setPos(-200,-150,0)
        self.sky.setBin('background', 0)
        self.sky.setDepthWrite(0)
        self.sky.setTwoSided(True)
        self.sky.setTexture(starTexture, 1)
        
        self.sky.reparentTo(render)
        self.sky.set_compass()
    
        # allow transparency
        render.setTransparency(TransparencyAttrib.MAlpha)

        self.pieCount = 0
        self.pieDisplay = grabPie(self.pieCount)
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0, "run":0, "reset":0}
        base.win.setClearColor(Vec4(0,0,0,1))
        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        # Create the main character
        eveStartPos = self.environ.find("**/start_point").getPos()
        self.eve = Actor("models/eve",
                                 {"run":"models/eve_run",
                                  "walk":"models/eve_walk"})
        print(eveStartPos)
        self.gameOver = 0
        self.eve.reparentTo(render)
        self.eve.setScale(.2)
        #self.eve.setShear(.5, .5, .5)
        self.eve.setPos(eveStartPos)

        self.eateve = Actor("models/eve")
        self.eateve.reparentTo(render)
        self.eateve.setScale(.2)
        self.eateve.setPos(eveStartPos)
        self.eateve.hide()
        
        self.pie = loader.loadModel("models/fruit-pie-slice")
        self.pie.reparentTo(render)
        self.pie.setScale(.5)
        self.pie.setPos(Vec3(-50, -30, 10))
        #self.pie.setP(20)
        
        self.rand = Actor("models/eve")
        self.rand.reparentTo(render)
        self.rand.setScale(.2)
        self.rand.setPos(Vec3(-70, -5, eveStartPos.getZ() + 5))
        self.rand.hide()       
         
        self.rand2 = Actor("models/eve")
        self.rand2.reparentTo(render)
        self.rand2.setScale(.2)
        self.rand2.setPos(Vec3(-70, -5, eveStartPos.getZ() + 10))
        self.rand2.hide()
        # print(eveStartPos)
        
        # Blue Dragon
        self.character3=Actor('models/nik-dragon')
        #self.character3.loadModel('models/nik-dragon')
        self.character3.reparentTo(render)
        self.character3.loadAnims({'win': 'models/nik-dragon'})
        self.character3.loop('win')
        self.character3.setPlayRate(.5,'win')
        self.character3.setScale(.23)
        self.character3.setTransparency(1)
        #self.character3.setColorScale(0.4,0.2,.4,.7)
        self.character3.setColorScale(9,9,9,.3)
        self.character3.setPos(-114,11,1.9)
        
        self.blueDragonSound = audio3d.loadSfx("sounds/Snoring Giant.mp3")
        audio3d.attachSoundToObject(self.blueDragonSound, self.character3)
        self.blueDragonSound.setLoop(True)
        self.blueDragonSound.play()
        
        # Red Dragon
        self.character2=Actor()
        self.character2.loadModel('models/nik-dragon')
        self.character2.reparentTo(render)
        self.character2.loadAnims({'win': 'models/nik-dragon'})
        self.character2.loop('win')
        self.character2.setPlayRate(1.5,'win')
        self.character2.setScale(.06)
        self.character2.setColorScale(6,0.2,0.2,50)
        self.character2.setPos(-108,11,.3)

        self.redDragonStartPos = self.character2.getPos()
        self.redDragonCollideCount = 0
        
        self.redDragonSound = audio3d.loadSfx("sounds/Velociraptor Call.mp3")
        audio3d.attachSoundToObject(self.redDragonSound, self.character3)
        self.redDragonSound.setLoop(True)
        self.redDragonSound.play()
        
        # Green Dragon
        self.character=Actor()
        self.character.loadModel('models/nik-dragon')
        self.character.reparentTo(render)
        self.character.loadAnims({'win': 'models/nik-dragon'})
        self.character.loop('win')
        self.character.setScale(.1)
        self.character.setPos(-118,21,0)
        
        self.greenDragonSound = audio3d.loadSfx("sounds/Raptor Call.mp3")
        audio3d.attachSoundToObject(self.greenDragonSound, self.character3)
        self.greenDragonSound.setLoop(True)
        self.greenDragonSound.play()
        
        self.dragonStartPos = self.character.getPos()
        self.dragonCollideCount = 0
        self.AIworld = AIWorld(render)
        #self.AIworld.addObstacle(self.environ)
        
        self.dragonAI = AICharacter("character", self.character, 100, 0.05, 5)
        self.AIworld.addAiChar(self.dragonAI)
        self.AIbehaviors = self.dragonAI.getAiBehaviors()
        #self.AIbehaviors.seek(self.character2)
        #self.AIbehaviors.wander(2, 0, 5, .5)
        self.AIbehaviors.pursue(self.eateve, 1)
        #self.AIbehaviors.wander(5,0,10,.5)
        #self.AIbehaviors.evade(self.character3, 10, 20, 300)
        #self.AIbehaviors.seek(self.eve, .5)
        #self.AIbehaviors.obstacleAvoidance(1)
        
        self.randomChase = AICharacter("rand", self.rand, 50, 20, 20)
        self.AIworld.addAiChar(self.randomChase)
        self.AIbehaviorsRand = self.randomChase.getAiBehaviors()
        self.AIbehaviorsRand.wander(10,0,47,.5)
        
        self.randomChase2 = AICharacter("rand2", self.rand2, 50, 20, 20)
        self.AIworld.addAiChar(self.randomChase2)
        self.AIbehaviorsRand2 = self.randomChase2.getAiBehaviors()
        self.AIbehaviorsRand2.wander(10,0,47,.5)

        self.ghostDragonAI = AICharacter("character3", self.character3, 250, .05, 5)
        self.AIworld.addAiChar(self.ghostDragonAI)
        self.AIbehaviors3 = self.ghostDragonAI.getAiBehaviors()
        self.AIbehaviors3.pursue(self.rand, 1)
        #self.AIbehaviors3.wander(5,0,10,.5)
        
        self.redDragonChasingEve = 0
        self.redDragonAI = AICharacter("character2", self.character2, 100, .05, 7)
        self.AIworld.addAiChar(self.redDragonAI)
        self.AIbehaviors2 = self.redDragonAI.getAiBehaviors()
        self.AIbehaviors2.pursue(self.rand2, 1)
        
        taskMgr.add(self.AIUpdate, "AIUpdate")

    
        # Create a floater object to use for camera management
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)
        
        # Enable Particles
        base.enableParticles()

        # Accept the control keys for movement and rotation
        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("space", self.setKey, ["run",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("r", self.setKey, ["reset",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("space-up", self.setKey, ["run",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        self.accept("r-up", self.setKey, ["reset",0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False
        self.isRunning = False
        self.isWalking = False

        # Set up the camera
        base.disableMouse()
        base.camera.setPos(self.eve.getX(),self.eve.getY()+10,2)
        
        # Collision detection for eve against the ground and against objects
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above eve's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.eveGroundRay = CollisionRay()
        self.eveGroundRay.setOrigin(0,0,4.5)
        self.eveGroundRay.setDirection(0,0,-1)
        self.eveGroundCol = CollisionNode('eveRay')
        self.eveGroundCol.addSolid(self.eveGroundRay)
        self.eveGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.eveGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.eveGroundColNp = self.eve.attachNewNode(self.eveGroundCol)
        self.eveGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.eveGroundColNp, self.eveGroundHandler)

        self.dragonGroundRay = CollisionRay()
        self.dragonGroundRay.setOrigin(0,0,10)
        self.dragonGroundRay.setDirection(0,0,-1)
        self.dragonGroundCol = CollisionNode('dragonRay')
        self.dragonGroundCol.addSolid(self.dragonGroundRay)
        self.dragonGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.dragonGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.dragonGroundColNp = self.character.attachNewNode(self.dragonGroundCol)
        self.dragonGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.dragonGroundColNp, self.dragonGroundHandler)

        self.ghostDragonGroundRay = CollisionRay()
        self.ghostDragonGroundRay.setOrigin(0,0,25)
        self.ghostDragonGroundRay.setDirection(0,0,-1)
        self.ghostDragonGroundCol = CollisionNode('ghostDragonRay')
        self.ghostDragonGroundCol.addSolid(self.ghostDragonGroundRay)
        self.ghostDragonGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ghostDragonGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ghostDragonGroundColNp = self.character3.attachNewNode(self.ghostDragonGroundCol)
        self.ghostDragonGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ghostDragonGroundColNp, self.ghostDragonGroundHandler)

        self.redDragonGroundRay = CollisionRay()
        self.redDragonGroundRay.setOrigin(0,0,5)
        self.redDragonGroundRay.setDirection(0,0,-1)
        self.redDragonGroundCol = CollisionNode('redDragonRay')
        self.redDragonGroundCol.addSolid(self.redDragonGroundRay)
        self.redDragonGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.redDragonGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.redDragonGroundColNp = self.character2.attachNewNode(self.ghostDragonGroundCol)
        self.redDragonGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.redDragonGroundColNp, self.redDragonGroundHandler)
        
        self.pieRay = CollisionRay()
        self.pieRay.setOrigin(0,0,10)
        self.pieRay.setDirection(0,0,-1)
        self.pieCol = CollisionNode('pieRay')
        self.pieCol.addSolid(self.pieRay)
        self.pieCol.setFromCollideMask(BitMask32.bit(0))
        self.pieCol.setIntoCollideMask(BitMask32.allOff())
        self.pieColNp = self.pie.attachNewNode(self.pieCol)
        self.pieHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.pieColNp, self.pieHandler)
        
        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Shows collision rays
        #self.eveGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Shows collisions
        #self.cTrav.showCollisions(render)
        
        self.fixPieZ()
        
        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        #directionalLight.setShadowCaster(True, 512, 512)
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Esempio n. 14
0
 def __init__(self, name, fromFile=None):
     PandaNode.__init__(self, name)
     self.elements = []
     self.fromFile = fromFile
Esempio n. 15
0
def test_particle_soft_start():
    # Create a particle effect and a particle system.
    # The effect serves to test the Python-level "soft_start"  method,
    # while the system serves to test the C++-level "soft_start" method
    # (via the associated Python "soft_start" method)
    effect = ParticleEffect()
    system = Particles("testSystem", 10)

    # Setup some dummy nodes, since it seems to want them
    system.set_render_parent(NodePath(PandaNode("test")))
    system.set_spawn_render_node_path(NodePath(PandaNode("test")))

    # Add the system to the effect
    effect.add_particles(system)

    # Re-assign the system, just to make sure that we have the
    # right object.
    system = effect.get_particles_list()[0]

    # First, standard "soft_start"--i.e. without either changing
    # the birth-rate or applying a delay. This should work as it
    # used to.
    effect.soft_start()

    assert system.get_birth_rate() == 0.5

    # Now, check that the pre-existing single-parameter soft-start,
    # which alters the birth-rate, still does so.
    system.soft_start(1)

    assert system.get_birth_rate() == 1

    # Next, birth-delaying.

    # Run a standard soft-start, then check that the birth-timer
    # is zero, as used to be the case on running this command.
    effect.soft_start()

    assert system.get_tics_since_birth() == 0

    # Run an delayed soft-start via the system, then check that the
    # birth-timer has the assigned value, and that the birth-rate is
    # unchanged.

    # (We pass in a birth-rate ("br") of -1 because the related code
    # checks for a birth-rate greater than 0, I believe. This allows
    # us to change the delay without affecting the birth-rate.)
    system.soft_start(br=-1, first_birth_delay=-2)

    assert system.get_birth_rate() == 1
    assert system.get_tics_since_birth() == 2

    # Now, run a delayed soft-start via the effect, and
    # again check that the birth-timer has changed as intended,
    # and the birth-rate hasn't changed at all.
    effect.soft_start(firstBirthDelay=0.25)

    assert system.get_birth_rate() == 1
    assert system.get_tics_since_birth() == -0.25

    # Update the system, advancing it far enough that it should
    # have birthed a particle if not for the delay, but not
    # so far that it should have birthed a particle >with<
    # the delay. Check thus that no particles have been birthed.
    system.update(1)

    assert system.get_living_particles() == 0

    # Update the system again, this time far enough that with the
    # delay it should have birthed just one particle, and
    # then check that this is the case.
    system.update(1)

    assert system.get_living_particles() == 1
Esempio n. 16
0
 def loadDNAFile(self, dnaStorage, file):
     self.loadDNAFileBase(dnaStorage, file)
     nodePath = NodePath(PandaNode('dna'))
     self.prop.traverse(nodePath, self.dnaStorage)
     return nodePath
Esempio n. 17
0
    def __init__(self):
        # 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)
        '''
        cam1 = Camera('cam1')
        cam1.getLens().setNear(0.01)
        cam1.getLens().setFov(50)
        cam1.showFrustum()
        camera1 = self.render.attachNewNode(cam1)
        camera1.setName('camera1')
        camera1.setPos(0, -6, 3)

        cam2 = Camera('cam2')
        cam2.getLens().setNear(0.01)
        cam2.getLens().setFov(50)
        #cam2.showFrustum()
        camera2 = self.render.attachNewNode(cam2)
        camera2.setName('camera2')
        camera2.setPos(0, -6, 3)
        '''

        self.disableMouse()
        #self.cam = camera2
        #self.lens = self.cam.node().getLens()
        self.camera.setPos(0, -6, 3.2)
        self.camLens.setNearFar(0.01, 1000.0)
        self.camLens.setFov(50)
        #self.cam.node().setLodScale(math.tan(math.radians(100.0 * 0.5)))

        self.setBackgroundColor(1, 1, 1)

        # Check video card capabilities.
        if not self.win.getGsg().getSupportsBasicShaders():
            print(
                "Toon Shader: Video driver reports that Cg shaders are not supported."
            )
            return

        # This shader's job is to render the model with discrete lighting
        # levels.  The lighting calculations built into the shader assume
        # a single nonattenuating point light.
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(self.loader.loadShader("shader/lightingGen.sha"))
        self.cam.node().setInitialState(tempnode.getState())

        # This is the object that represents the single "light", as far
        # the shader is concerned.  It's not a real Panda3D LightNode, but
        # the shader doesn't care about that.
        light = self.render.attachNewNode("light")
        light.setPos(30, -50, 0)

        # this call puts the light's nodepath into the render state.
        # this enables the shader to access this light by name.
        self.render.setShaderInput("light", light)

        # The "normals buffer" will contain a picture of the model colorized
        # so that the color of the model is a representation of the model's
        # normal at that point.
        normalsBuffer = self.win.makeTextureBuffer("normalsBuffer", 0, 0)
        normalsBuffer.setClearColor(LVecBase4(0.5, 0.5, 0.5, 1))
        self.normalsBuffer = normalsBuffer
        normalsCamera = self.makeCamera(normalsBuffer,
                                        lens=self.cam.node().getLens())
        normalsCamera.node().setScene(self.render)
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(self.loader.loadShader("shader/normalGen.sha"))
        normalsCamera.node().setInitialState(tempnode.getState())
        # what we actually do to put edges on screen is apply them as a texture to
        # a transparent screen-fitted card
        drawnScene = normalsBuffer.getTextureCard()
        drawnScene.setTransparency(1)
        drawnScene.setColor(1, 1, 1, 0)
        drawnScene.reparentTo(self.render2d)
        self.drawnScene = drawnScene

        # this shader accepts, as input, the picture from the normals buffer.
        # it compares each adjacent pixel, looking for discontinuities.
        # wherever a discontinuity exists, it emits black ink.
        self.separation = 0.00065
        self.cutoff = 0.3
        inkGen = self.loader.loadShader("shader/inkGen.sha")
        drawnScene.setShader(inkGen)
        drawnScene.setShaderInput(
            "separation", LVecBase4(self.separation, 0, self.separation, 0))
        drawnScene.setShaderInput("cutoff", LVecBase4(self.cutoff))

        # Load a model and start its animation.
        self.character = Actor()
        #self.character.loadModel('models/miku/tda_miku')
        #self.character.loadAnims({'anim': 'models/miku/tda_miku-Anim0'})
        #self.character.listJoints()
        #node = self.character.find('**/*modelRoot')
        #geom_node = node.getChildren()[0].node()
        #geoms = geom_node.getGeoms()
        #for child in node.getChildren():
        #    print child

        self.character.loadModel('models/dekiruo/dekiruo')
        self.character.reparentTo(self.render)
        self.character.ls()

        self.character.loadAnims(
            {'normal': 'models/dekiruo/dekiruo-Anim_normal'})
        self.character.play('normal')
        #self.character.loadAnims({'anger': 'models/dekiruo/dekiruo-Anim_anger'})
        #self.character.play('anger')
        #self.character.loadAnims({'sadness2crying': 'models/dekiruo/dekiruo-Anim_sadness2crying'})
        #self.character.play('sadness2crying')
        #self.character.loadAnims({'sleep': 'models/dekiruo/dekiruo-Anim_sleep'})
        #self.character.play('sleep')
        #self.character.loadAnims({'smile': 'models/dekiruo/dekiruo-Anim_smile'})
        #self.character.play('smile')
        #self.character.loadAnims({'surprised': 'models/dekiruo/dekiruo-Anim_surprised'})
        #self.character.play('surprised')

        #self.character.loadModel('models/dekinaio/dekinaio')
        #self.character.reparentTo(self.render)
        #self.character.ls()

        #self.character.loadAnims({'normal': 'models/dekinaio/dekinaio-Anim_normal'})
        #self.character.play('normal')
        #self.character.loadAnims({'anger': 'models/dekinaio/dekinaio-Anim_anger'})
        #self.character.play('anger')
        #self.character.loadAnims({'sadness2crying': 'models/dekinaio/dekinaio-Anim_sadness2crying'})
        #self.character.play('sadness2crying')
        #self.character.loadAnims({'sleep': 'models/dekinaio/dekinaio-Anim_sleep'})
        #self.character.play('sleep')
        #self.character.loadAnims({'smile': 'models/dekinaio/dekinaio-Anim_smile'})
        #self.character.play('smile')
        #self.character.loadAnims({'surprised': 'models/dekinaio/dekinaio-Anim_surprised'})
        #self.character.play('surprised')

        #anim =  self.character.getCurrentAnim()
        #frames = self.character.getNumFrames(anim)
        #print anim, frames
        #self.character.pose(anim, int(frames * 0.9))

        # Create smiley's node to indicate 3d points
        self.smileyActor1 = self.render.attachNewNode('SmileyActorNode1')
        self.smileyActor2 = self.render.attachNewNode('SmileyActorNode2')
        smiley = self.loader.loadModel('smiley')
        smiley.setScale(0.01, 0.01, 0.01)
        smiley.instanceTo(self.smileyActor1)
        smiley.instanceTo(self.smileyActor2)

        n1 = self.character.exposeJoint(None, "modelRoot", "Eyes")
        n2 = self.character.exposeJoint(None, "modelRoot", "Head")

        self.label1 = OnscreenText(text='P1',
                                   fg=(1, 0, 0, 1),
                                   pos=(0, 0),
                                   scale=.05,
                                   mayChange=1)
        self.label2 = OnscreenText(text='P2',
                                   fg=(1, 0, 0, 1),
                                   pos=(0, 0),
                                   scale=.05,
                                   mayChange=1)
        self.info1 = OnscreenText(text='dist3d:',
                                  fg=(1, 0, 0, 1),
                                  pos=(-1, 0),
                                  scale=.05,
                                  mayChange=1)
        self.info2 = OnscreenText(text='dist2d:',
                                  fg=(1, 0, 0, 1),
                                  pos=(-1, -0.1),
                                  scale=.05,
                                  mayChange=1)
        self.info3 = OnscreenText(text='camera:',
                                  fg=(1, 0, 0, 1),
                                  pos=(-1, -0.2),
                                  scale=.05,
                                  mayChange=1)

        self.taskMgr.add(self.lookAt, 'lookAt', extraArgs=[n1, n2])
        self.taskMgr.add(self.updateNamePos,
                         'name pos update',
                         extraArgs=[n1, n2])

        # These allow you to change cartooning parameters in realtime
        self.accept("escape", sys.exit, [0])
        self.accept("arrow_up", self.camera_f)  #self.increaseSeparation)
        self.accept("arrow_down", self.camera_b)  #self.decreaseSeparation)
        self.accept("arrow_left", self.camera_l)  #self.increaseCutoff)
        self.accept("arrow_right", self.camera_r)  #self.decreaseCutoff)
        self.accept("s", self.saveImage)
        self.accept("p", self.play)
        self.accept("o", self.stop)
        self.accept("n", self.forward)
        self.accept("b", self.rewind)
        self.accept("l", self.lookAt)
        self.accept("h", self.hide)
        self.accept("1", self.cam_closeup)
        self.accept("2", self.cam_bustshot)
        self.accept("3", self.cam_longshot)
Esempio n. 18
0
    def __init__(self):

        self.d_objects = {}
        self.client = None

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))
        #base.win.setWidth(800)

        props = WindowProperties()
        props.setTitle('Panda3D/Node.js Networking Experiment')
        base.win.requestProperties(props)

        # Post the instructions
        self.title = addTitle("Roaming Ralph goes Networking")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        self.inst8 = addInstructions(0.55, "Current connection lag:")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.
        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)

        # PlayerStartPos = self.environ.find("**/start_point").getPos()
        # print "start pos:", PlayerStartPos

        self.player = None

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # ----------------------------------------------------------------------
        # new: create DynObject to "host" a Ralph model for our player avatar

        # Accept the control keys for movement and rotation
        self.accept("escape", self.exitGame)
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])

        # taskMgr.add(self.moveCamera,"CameraMoveTask")
        taskMgr.add(self.moveObjects, "ObjectsMoveTask")

        # Game state variables
        self.isMoving = False

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 1000)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Esempio n. 19
0
    def newScreen(self):
        """Creates screen with world model and actors"""

        #Loads world model
        self.world = loader.loadModel("phase/trialworld.bam")
        self.world.reparentTo(render)
        #Loads the font
        self.font = loader.loadFont("phase/LemonMilk.ttf")

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        #Loads actor and animations
        mooreStartPos = (0, 0, 0)
        self.moore = Actor("phase/ralph", {
            "run": "phase/ralph-run",
            "walk": "phase/ralph-walk"
        })
        self.moore.reparentTo(render)
        self.moore.setScale(.2)
        self.moore.setPos(mooreStartPos)
        # Loads a floater above Moore's head to point the camera at
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.moore)

        #Controls for moving actor around
        self.accept("a", self.setKey, ["left", True])
        self.accept("d", self.setKey, ["right", True])
        self.accept("w", self.setKey, ["forward", True])
        self.accept("a-up", self.setKey, ["left", False])
        self.accept("d-up", self.setKey, ["right", False])
        self.accept("w-up", self.setKey, ["forward", False])

        taskMgr.add(self.move, "moveTask")

        self.isMoving = False

        # Set up the camera
        # Disables the mouse from moving the scren
        self.disableMouse()
        self.camera.setPos(self.moore.getX(),
                           self.moore.getY() + 10,
                           self.moore.getZ() + 2)

        # Loads the music file
        self.music = self.loader.loadMusic("phase/gunsforhands.ogg")
        # Plays the music
        self.music.play()
        # Starts/stops music
        self.accept("m-up", self.startMusic)
        # Creates a title
        self.title = self.addTitle("Moore's World: The Best World", self.font)
        # Creates the instructions
        self.inst1 = self.addInstructions(0.06, "ESC: Quit", self.font)
        self.inst5 = self.addInstructions(0.12, "M: Enable/Disable Music",
                                          self.font)
        self.inst2 = self.addInstructions(0.18, "CONTROLS: W/A/D", self.font)
        self.inst5 = self.addInstructions(0.24, "TEPEE: EASY", self.font)
        self.inst5 = self.addInstructions(0.30, "HOUSE: MEDIUM", self.font)
        self.inst5 = self.addInstructions(0.36, "CASTLE: HARD", self.font)
        # Exits the program
        self.accept("escape", sys.exit)
Esempio n. 20
0
    def __init__(self):
        self.last_mousex = 0
        self.last_mousey = 0

        self.zone = None
        self.zone_reload_name = None
        
        self.winprops = WindowProperties( )

        # simple console output
        self.consoleNode = NodePath(PandaNode("console_root"))
        self.consoleNode.reparentTo(aspect2d)

        self.console_num_lines = 24
        self.console_cur_line = -1
        self.console_lines = []
        for i in range(0, self.console_num_lines):
            self.console_lines.append(OnscreenText(text='', style=1, fg=(1,1,1,1),
                        pos=(-1.3, .4-i*.05), align=TextNode.ALeft, scale = .035, parent = self.consoleNode))

        # Configuration
        self.consoleOut('World Forge v.%s loading configuration' % VERSION)
        self.configurator = Configurator(self)
        cfg = self.configurator.config
        resaveRes = False
        if 'xres' in cfg:
            self.xres = int(cfg['xres'])
        else:
            self.xres = 1024
            resaveRes = True

        if 'yres' in cfg:
            self.yres = int(cfg['yres'])
        else:
            self.yres = 768
            resaveRes = True

        if resaveRes:
            self.saveDefaultRes()

        self.xres_half = self.xres / 2
        self.yres_half = self.yres / 2
        self.mouse_accum = MouseAccume( lambda: (self.xres_half,self.yres_half))

        self.eyeHeight = 7.0
        self.rSpeed = 80
        self.flyMode = 1

        # application window setup
        base.win.setClearColor(Vec4(0,0,0,1))
        self.winprops.setTitle( 'World Forge')
        self.winprops.setSize(self.xres, self.yres) 
        
        base.win.requestProperties( self.winprops ) 
        base.disableMouse()
        
        # Post the instructions
        self.title = addTitle('World Forge v.' + VERSION)
        self.inst0 = addInstructions(0.95, "[FLYMODE][1]")
        self.inst1 = addInstructions(-0.95, "Camera control with WSAD/mouselook. Press K for hotkey list, ESC to exit.")
        self.inst2 = addInstructions(0.9,  "Loc:")
        self.inst3 = addInstructions(0.85, "Hdg:")
        self.error_inst = addInstructions(0, '')
        self.kh = []
        
        self.campos = Point3(155.6, 41.2, 4.93)
        base.camera.setPos(self.campos)
        
        # Accept the application control keys: currently just esc to exit navgen       
        self.accept("escape", self.exitGame)
        self.accept("window-event", self.resizeGame)
        
        # Create some lighting
        ambient_level = .6
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(ambient_level, ambient_level, ambient_level, 1.0))
        render.setLight(render.attachNewNode(ambientLight))

        direct_level = 0.8
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0.0, 0.0, -1.0))
        directionalLight.setColor(Vec4(direct_level, direct_level, direct_level, 1))
        directionalLight.setSpecularColor(Vec4(direct_level, direct_level, direct_level, 1))
        render.setLight(render.attachNewNode(directionalLight))
        
        # create a point light that will follow our view point (the camera for now)
        # attenuation is set so that this point light has a torch like effect
        self.plight = PointLight('plight')
        self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1.0))
        self.plight.setAttenuation(Point3(0.0, 0.0, 0.0002))
        
        self.plnp = base.camera.attachNewNode(self.plight)
        self.plnp.setPos(0, 0, 0)
        render.setLight(self.plnp)
        self.cam_light = 1
        
        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, \
            "cam-right":0, "mouse3":0, "flymode":1 }

        # setup FOG
        self.fog_colour = (0.8,0.8,0.8,1.0)
        self.linfog = Fog("A linear-mode Fog node")
        self.linfog.setColor(self.fog_colour)
        self.linfog.setLinearRange(700, 980)         # onset, opaque distances as params
        # linfog.setLinearFallback(45,160,320)
        base.camera.attachNewNode(self.linfog)
        render.setFog(self.linfog)
        self.fog = 1
        
        # camera control
        self.campos = Point3(0, 0, 0)
        self.camHeading = 0.0
        self.camPitch = 0.0
        base.camLens.setFov(65.0)
        base.camLens.setFar(1200) 
        
        self.cam_speed = 0  # index into self.camp_speeds
        self.cam_speeds = [40.0, 80.0, 160.0, 320.0, 640.0]
        
        
        # Collision Detection for "WALKMODE"
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  The ray will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        
        self.cTrav = CollisionTraverser()
        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0.0, 0.0, 0.0)
        self.camGroundRay.setDirection(0,0,-1)      # straight down
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        
        # attach the col node to the camCollider dummy node
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)  
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
        
        
        # Uncomment this line to see the collision rays
        # self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        # self.cTrav.showCollisions(render)
        
        # Add the spinCameraTask procedure to the task manager.
        # taskMgr.add(self.spinCameraTask, "SpinCameraTask")
        globals.hasClickedSpawn = False;
        globals.hasClickedGrid = False;
        taskMgr.add(self.camTask, "camTask")

        self.toggleControls(1)

        # need to step the task manager once to make our fake console work
        taskMgr.step()
Esempio n. 21
0
    def __init__(self):
        ShowBase.__init__(self)

        self.key = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam_left": 0,
            "cam_right": 0,
            "cam_down": 0,
            "cam_up": 0,
            "up": 0,
            "down": 0
        }

        #####################
        #
        #   Simply testing procedural cave generation
        #
        #####################
        self.start = PlatformSeg(LVector3(0, 0, 0))
        self.start.generateAllParts(render)
        self.lostWood = LostWood(
            LVector3(self.start.pos.x + 750,
                     self.start.parts[0].pos.y + self.start.parts[0].wid,
                     self.start.pos.z))
        self.lostWood.generateAllParts(render)
        self.cave = Cave(
            LVector3(self.lostWood.pos.x + 1100,
                     self.lostWood.parts[6].pos.y + self.lostWood.parts[6].wid,
                     self.lostWood.pos.z))
        self.cave.generateAllParts(render)
        self.end = End(
            LVector3(
                self.cave.thirdRoomParts[8].pos.x - 200,
                self.cave.thirdRoomParts[8].pos.y +
                self.cave.thirdRoomParts[8].wid,
                self.cave.thirdRoomParts[8].pos.z))
        self.end.generate(render)

        ####################
        #
        #   Setting light so that we could see the definition in the walls
        #
        ####################

        render.setShaderAuto()
        self.dlight = DirectionalLight('dlight')
        self.dlight.setColor(LVector4(0.3, 0.1, 0.7, 1))
        dlnp = render.attachNewNode(self.dlight)
        dlnp.setHpr(90, 20, 0)
        render.setLight(dlnp)

        self.alight = render.attachNewNode(AmbientLight("Ambient"))
        self.alight.node().setColor(LVector4(0.5, 0.5, 1, .1))
        render.setLight(self.alight)

        base.disableMouse()
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)
        base.camera.reparentTo(self.floater)
        base.camera.setPos(0, -20, 500)
        base.camera.setP(-50)
        self.bindKeys()
Esempio n. 22
0
    def __init__(self):
        __builtin__.main = self
        self.taskMgr = taskMgr
        self.base = base

        # Connect to the server
        self.cManager = ConnectionManager()
        self.startConnection()

        self.characters = dict()
        self.cpList = dict()

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Post the instructions

        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.ralphStartPos = self.environ.find("**/start_point").getPos()

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])

        # Placeholder Login
        self.name = str(raw_input("Name: "))
        factionId = int(input("Faction ID: "))
        self.cManager.sendRequest(Constants.CMSG_AUTH, [self.name, factionId])

        # Create two control points
        cp1 = ControlPoint(1, -107.575, 0.6066, 0.490075, 10, RED)
        cp2 = ControlPoint(2, -100.575, -35.6066, 0.090075, 10, BLUE)

        self.cpList[1] = cp1
        self.cpList[2] = cp2

        # Create the control point Bar UI
        self.cp_bar = ControlPointBar()
        self.resource_bar = ResourceBar()

        taskMgr.doMethodLater(0.1, self.refresh, "heartbeat")
        taskMgr.doMethodLater(1, self.CPHandler, "CPHandler")
        taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler')

        # Game state variables
        self.isMoving = False

        # Set up the camera
        base.disableMouse()
        #base.camera.setPos(self.character.actor.getX(),self.character.actor.getY()+10,2)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Esempio n. 23
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data(
            "", """
            win-size 1600 900
            window-title Render Pipeline - Roaming Ralph Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "7:40"

        # Use a special effect for rendering the scene, this is because the
        # roaming ralph model has no normals or valid materials
        self.render_pipeline.set_effect(render,
                                        "scene-effect.yaml", {},
                                        sort=250)

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        self.speed = 1.0
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Post the instructions

        self.inst1 = addInstructions(0.95, "[ESC]  Quit")
        self.inst4 = addInstructions(0.90, "[W]  Run Ralph Forward")
        self.inst4 = addInstructions(0.85, "[S]  Run Ralph Backward")
        self.inst2 = addInstructions(0.80, "[A]  Rotate Ralph Left")
        self.inst3 = addInstructions(0.75, "[D]  Rotate Ralph Right")
        self.inst6 = addInstructions(0.70, "[Left Arrow]  Rotate Camera Left")
        self.inst7 = addInstructions(0.65,
                                     "[Right Arrow]  Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("resources/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)

        # Remove wall nodes
        self.environ.find("**/wall").remove_node()

        # Create the main character, Ralph
        self.ralph = Actor("resources/ralph", {
            "run": "resources/ralph-run",
            "walk": "resources/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(Vec3(-110.9, 29.4, 1.8))

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("=", self.adjustSpeed, [0.25])
        self.accept("+", self.adjustSpeed, [0.25])
        self.accept("-", self.adjustSpeed, [-0.25])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX() + 10, self.ralph.getY() + 10, 2)
        base.camLens.setFov(80)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 1000)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Esempio n. 24
0
    def __init__(self):
        base.disableMouse()
        base.setBackgroundColor(0,0,0)
        camera.setPos(0,-50,0)
        
        # Check video card capabilities.

        if (base.win.getGsg().getSupportsBasicShaders() == 0):
            addTitle("Glow Filter: Video driver reports that shaders are not supported.")
            return

        # Post the instructions
        self.title = addTitle("Panda3D: Tutorial - Glow Filter")
        self.inst1 = addInstructions(0.95,"ESC: Quit")
        self.inst2 = addInstructions(0.90,"Space: Toggle Glow Filter On/Off")
        self.inst3 = addInstructions(0.85,"Enter: Toggle Running/Spinning")
        self.inst4 = addInstructions(0.80,"V: View the render-to-texture results")

        #create the shader that will determime what parts of the scene will glow
        glowShader=loader.loadShader("glowShader.sha")

        # load our model
        self.tron=Actor()
        self.tron.loadModel("models/tron")
        self.tron.loadAnims({"running":"models/tron_anim"})
        self.tron.reparentTo(render)
        self.interval = self.tron.hprInterval(60,Point3(360,0,0))
        self.interval.loop()
        self.isRunning=False

        #put some lighting on the tron model
        dlight = DirectionalLight('dlight')
        alight = AmbientLight('alight')
        dlnp = render.attachNewNode(dlight) 
        alnp = render.attachNewNode(alight)
        dlight.setColor(Vec4(1.0, 0.7, 0.2, 1))
        alight.setColor(Vec4(0.2, 0.2, 0.2, 1))
        dlnp.setHpr(0, -60, 0) 
        render.setLight(dlnp)
        render.setLight(alnp)

        # create the glow buffer. This buffer renders like a normal scene,
        # except that only the glowing materials should show up nonblack.
        glowBuffer=base.win.makeTextureBuffer("Glow scene", 512, 512)
        glowBuffer.setSort(-3)
        glowBuffer.setClearColor(Vec4(0,0,0,1))

        # We have to attach a camera to the glow buffer. The glow camera
        # must have the same frustum as the main camera. As long as the aspect
        # ratios match, the rest will take care of itself.
        glowCamera=base.makeCamera(glowBuffer, lens=base.cam.node().getLens())

        # Tell the glow camera to use the glow shader
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(glowShader)
        glowCamera.node().setInitialState(tempnode.getState())

        # set up the pipeline: from glow scene to blur x to blur y to main window.
        blurXBuffer=makeFilterBuffer(glowBuffer,  "Blur X", -2, "XBlurShader.sha")
        blurYBuffer=makeFilterBuffer(blurXBuffer, "Blur Y", -1, "YBlurShader.sha")
        self.finalcard = blurYBuffer.getTextureCard()
        self.finalcard.reparentTo(render2d)
        self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
        
        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.

        self.accept("v", base.bufferViewer.toggleEnable)
        self.accept("V", base.bufferViewer.toggleEnable)
        base.bufferViewer.setPosition("llcorner")
        base.bufferViewer.setLayout("hline")
        base.bufferViewer.setCardSize(0.652,0)

        # event handling
        self.accept("space", self.toggleGlow)
        self.accept("enter", self.toggleDisplay)
        self.accept("escape", sys.exit, [0])

        self.glowOn=True;
Esempio n. 25
0
    def __init__(self):
        ShowBase.__init__(self)

        self.actorBullet = 0

        self.keyMap = {
            "cam-up": False,
            "cam-down": False,
            "cam-left": False,
            "cam-right": False,
            "up": False,
            "down": False,
            "left": False,
            "right": False,
            "shoot": False
        }

        #load environment model
        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)

        #load actor
        actorStartPos = self.environ.find("**/start_point").getPos()
        self.actor = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.actor.reparentTo(render)
        self.actor.setScale(.2)
        self.actor.setPos(actorStartPos + (0, 0, 0))

        #load bullets
        for bullets in range(self.actorBullet):
            print("making bullet")
            bullet = loader.loadModel("models/smiley")
            bullet.reparentTo(render)
            bullet.setPos(self.actor.getPos())

        #load floater which is the point of focus for the camera
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.actor)
        self.floater.setZ(2.0)

        self.disableMouse()
        # base.useDrive()
        self.camera.setPos(self.actor.getX(), self.actor.getY() + 10, 2.0)
        self.camera.lookAt(self.floater)

        #event handlers
        self.accept("arrow_up", self.setKey, ["cam-up", True])
        self.accept("arrow_up-up", self.setKey, ["cam-up", False])
        self.accept("arrow_down", self.setKey, ["cam-down", True])
        self.accept("arrow_down-up", self.setKey, ["cam-down", False])
        self.accept("arrow_left", self.setKey, ["cam-left", True])
        self.accept("arrow_left-up", self.setKey, ["cam-left", False])
        self.accept("arrow_right", self.setKey, ["cam-right", True])
        self.accept("arrow_right-up", self.setKey, ["cam-right", False])
        self.accept("w", self.setKey, ["up", True])
        self.accept("w-up", self.setKey, ["up", False])
        self.accept("a", self.setKey, ["left", True])
        self.accept("a-up", self.setKey, ["left", False])
        self.accept("s", self.setKey, ["down", True])
        self.accept("s-up", self.setKey, ["down", False])
        self.accept("d", self.setKey, ["right", True])
        self.accept("d-up", self.setKey, ["right", False])
        self.accept("space", self.setKey, ["shoot", True])
        self.accept("space-up", self.setKey, ["shoot", False])

        taskMgr.add(self.moveCamera, "moveCamera")

        self.isMoving = False

        #create collision traverser which handles all the collision stuff
        self.Traverser = CollisionTraverser()

        #create solid
        self.actorGroundRay = CollisionRay()
        #set origin and direction of the collision ray
        self.actorGroundRay.setOrigin(0, 0, 9)
        self.actorGroundRay.setDirection(0, 0, -1)
        #create the collision node
        self.actorGroundCol = CollisionNode('ralphRay')
        #attach solid to node
        self.actorGroundCol.addSolid(self.actorGroundRay)
        #attach node to actor. Create the node path
        self.actorGroundColNp = self.actor.attachNewNode(self.actorGroundCol)
        #create queue
        self.actorGroundHandler = CollisionHandlerQueue()
        #add nodepath and queue to traverser
        self.Traverser.addCollider(self.actorGroundColNp,
                                   self.actorGroundHandler)
Esempio n. 26
0
    def __init__(self):
        self.switchState = True
        self.switchCam = False
        self.path_no = 1
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor((0, 0, 0, 1))
        base.cam.setPosHpr(17.79, -87.64, 90.16, 38.66, 325.36, 0)
        # Post the instructions

        addTitle("Pandai Tutorial: Roaming Ralph (Walking on Uneven Terrain) "
                 "working with pathfinding")
        addInstructions(0.95, "[ESC]: Quit")
        addInstructions(0.90, "[Space - do Only once]: Start Pathfinding")
        addInstructions(0.85, "[Enter]: Change camera view")
        addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        addInstructions(0.70, "[A]: Rotate Camera Left")
        addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(12, 0, 0)

        self.box = loader.loadModel("models/box")
        self.box.reparentTo(render)
        self.box.setPos(-29.83, 0, 0)
        self.box.setScale(1)

        self.box1 = loader.loadModel("models/box")
        self.box1.reparentTo(render)
        self.box1.setPos(-51.14, -17.90, 0)
        self.box1.setScale(1)

        # Create the main character, Ralph

        #ralphStartPos = self.environ.find("**/start_point").getPos()
        ralphStartPos = Vec3(-98.64, -20.60, 0)
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(1)
        self.ralph.setPos(ralphStartPos)

        self.ralphai = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })

        self.pointer = loader.loadModel("models/arrow")
        self.pointer.setColor(1, 0, 0)
        self.pointer.setPos(-7.5, -1.2, 0)
        self.pointer.setScale(3)
        self.pointer.reparentTo(render)

        self.pointer1 = loader.loadModel("models/arrow")
        self.pointer1.setColor(1, 0, 0)
        self.pointer1.setPos(-98.64, -20.60, 0)
        self.pointer1.setScale(3)
        #self.pointer.reparentTo(render)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("enter", self.activateCam)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])

        #taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        #base.disableMouse()
        #base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 1000)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        #Uncomment this line to show a visual representation of the
        #collisions occuring
        #self.cTrav.showCollisions(render)

        self.setAI()
Esempio n. 27
0
    def __init__(self):
        
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        
        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.  

        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
        
        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
    def update(self, task):
        
        if self.isLevel1 == True and self.characterClass != 0:
            if self.characterClass.nextLevel == True:
                self.setLevel2()
                
                
        if self.isLevel2 == True and self.characterClass != 0:
            if self.characterClass.nextLevel == True:
                self.setLevel1()
             
        
        
        
        if inputState.isSet('help'):
            if self.showHelp == True:
                self.showHelp = False
            else:
                self.showHelp = True
                
        if inputState.isSet('menu'):
            if self.showMenu == True:
                self.showMenu = False
            else:
                self.showMenu = True
                
        
        if self.showHelp == True:      
            self.inst1.show()
            self.inst2.show()
            self.inst3.show()
            self.inst4.show()
            self.inst5.show()
            self.inst6.show()
            self.inst7.show()
            self.inst8.show()
            self.inst9.show()
            self.inst10.show()
            self.inst11.show()
            self.inst12.show()
            self.inst13.show()
            self.inst14.show()

        else:
            self.inst1.hide()
            self.inst2.hide()
            self.inst3.hide()
            self.inst4.hide()
            self.inst5.hide()
            self.inst6.hide()
            self.inst7.hide()
            self.inst8.hide()
            self.inst9.hide()
            self.inst10.hide()
            self.inst11.hide()
            self.inst12.hide()
            self.inst13.hide()
            self.inst14.hide()
            
        
        if self.showMenu == True:
            self.imageObject.show()
            self.b1.show()
            self.b2.show()
            self.b3.show()
            if self.characterClass != 0:
                self.characterClass.bar.setPos(2,2,2)
                self.characterClass.frame.setPos(2,2,2)
                self.characterClass.item.setPos(2,2,2)
        else:
            self.imageObject.hide()
            self.b1.hide()
            self.b2.hide()
            self.b3.hide()
            if self.characterClass != 0:
                self.characterClass.bar.setPos(0.8,0.5,0.9)
                self.characterClass.frame.setPos(0.7,0.5,0.8)
                self.characterClass.item.setPos(0.9,0.5,0.8)



            
            
        if self.mySound.status() == self.mySound.READY:
            self.mySound.play()
            self.mySound.setVolume(0.9)
            
            
            


        if self.isLevel1 == True or self.isLevel2 == True:

            dt = globalClock.getDt()
            self.characterClass.processInput(dt)
            self.characterClass.models.world.doPhysics(dt, 100, 1./180.)
        
        
            # Create a floater object.  We use the "floater" as a temporary
            # variable in a variety of calculations.
            self.characterClass.floater = NodePath(PandaNode("floater"))
            self.characterClass.floater.reparentTo(render)
        
        


        
            if self.characterClass.characterNP.getZ() != 0:
                base.camera.setZ(self.characterClass.characterNP.getZ()+3)
            

            # If the camera is too far from ralph, move it closer.
            # If the camera is too close to ralph, move it farther.
            camvec = self.characterClass.characterNP.getPos() - base.camera.getPos()
            camvec.setZ(0)
            camdist = camvec.length()
            camvec.normalize()
            if (camdist > 15.0):
                base.camera.setPos(base.camera.getPos() + camvec*(camdist-15))
                camdist = 15.0
            if (camdist < 5.0):
                base.camera.setPos(base.camera.getPos() - camvec*(5-camdist))
                camdist = 5.0

            self.characterClass.floater.setPos(self.characterClass.characterNP.getPos())
            self.characterClass.floater.setZ(self.characterClass.characterNP.getZ() + 2.0)
            base.camera.lookAt(self.characterClass.floater)

        return task.cont
Esempio n. 29
0
    def __init__(self):
        PandaNode.__init__(self, 'margins')

        self.cells = set()
        self.visibles = set()
Esempio n. 30
0
    def __init__(self, game):

        self.game = game

        self.shipPoint = NodePath(PandaNode("shipFloaterPoint"))
        self.shipPoint.reparentTo(render)

        self.x_pos = 0
        self.z_pos = 0

        self.x_speed = 0
        self.z_speed = 0

        self.x_pid = PID(3.0, 5.0, 1.0)
        self.z_pid = PID(3.0, 5.0, 1.0)

        self.model = Actor("data/ship.egg")

        self.model.setPos(0, 0, 0)
        self.model.setHpr(0, 0, 0)

        self.normal_speed = 3.5
        self.low_speed = 2

        self.speed = self.normal_speed

        self.cool_down = 0.1
        self.last_shoot = 0

        self.keyMap = {
            "up": 0,
            "down": 0,
            "left": 0,
            "right": 0,
            "brake": 0,
            "attack": 0,
        }

        # This list will stored fired bullets.
        self.bullets = []

        self.game.accept("mouse1", self.setKey, ["attack", 1])
        self.game.accept("mouse1-up", self.setKey, ["attack", 0])

        self.game.accept("shift-mouse1", self.setKey, ["attack", 1])
        self.game.accept("shift-mouse1-up", self.setKey, ["attack", 0])

        self.game.accept("x", self.setKey, ["attack", 1])
        self.game.accept("x-up", self.setKey, ["attack", 0])

        self.game.accept("c", self.setKey, ["brake", 1])
        self.game.accept("c-up", self.setKey, ["brake", 0])

        self.game.accept("arrow_up", self.setKey, ["up", 1])
        self.game.accept("arrow_up-up", self.setKey, ["up", 0])

        self.game.accept("arrow_down", self.setKey, ["down", 1])
        self.game.accept("arrow_down-up", self.setKey, ["down", 0])

        self.game.accept("arrow_left", self.setKey, ["left", 1])
        self.game.accept("arrow_left-up", self.setKey, ["left", 0])

        self.game.accept("arrow_right", self.setKey, ["right", 1])
        self.game.accept("arrow_right-up", self.setKey, ["right", 0])
Esempio n. 31
0
        cyl.addVertex(i + circRes)
        cyl.addVertex(i)
    cyl.addVertex(circRes)
    cyl.addVertex(0)
    cyl.closePrimitive()
    geom.addPrimitive(cyl)
    node = GeomNode('geomnode')
    node.addGeom(geom)
    return node


cbm = CullBinManager.getGlobalPtr()
cbm.addBin('handles', CullBinEnums.BTFrontToBack, 35)
cbm.setBinActive('handles', True)

tempnode = NodePath(PandaNode('temp node'))
tempnode.setShaderAuto()
tempnode.setShaderInput('hi_id', Vec4(0, 0, 0, 0), 2)
tempnode.setBin('inactive', 0, 50)
tempnode.setAntialias(AntialiasAttrib.MNone, 10)
newCamera = base.makeCamera(base.win, lens=base.cam.node().getLens())
newCamera.node().setInitialState(tempnode.getState())
newCamera.node().getDisplayRegion(0).setSort(1)
newCamera.node().getDisplayRegion(0).setClearDepthActive(1)
newCamera.node().setCameraMask(BitMask32(4))
newCamera.node().setScene(render)


class RotationHandle(PandaNode, MouseEventListener):
    geomNode = makeRotationGeomNode()
Esempio n. 32
0
    def __init__(self, args):
        CosmoniumBase.__init__(self)

        if args.config is not None:
            self.config_file = args.config
        else:
            self.config_file = 'ralph-data/ralph.yaml'
        self.splash = RalphSplash()
        self.ralph_config = RalphConfigParser()
        if self.ralph_config.load_and_parse(self.config_file) is None:
            sys.exit(1)
        self.water = self.ralph_config.water

        self.has_water = True
        self.fullscreen = False
        self.shadow_caster = None
        self.light_angle = None
        self.light_dir = LVector3.up()
        self.vector_to_star = self.light_dir
        self.light_quat = LQuaternion()
        self.light_color = (1.0, 1.0, 1.0, 1.0)
        self.directionalLight = None

        self.observer = RalphCamera(self.cam, self.camLens)
        self.observer.init()

        self.distance_to_obs = 2.0  #Can not be 0 !
        self.height_under = 0.0
        self.scene_position = LVector3()
        self.scene_scale_factor = 1
        self.scene_rel_position = LVector3()
        self.scene_orientation = LQuaternion()
        self.model_body_center_offset = LVector3()
        self.world_body_center_offset = LVector3()
        self.context = self
        self.size = self.ralph_config.tile_size  #TODO: Needed by populator

        #Size of an edge seen from 4 units above
        self.edge_apparent_size = (1.0 * self.ralph_config.tile_size /
                                   self.ralph_config.tile_density) / (
                                       4.0 * self.observer.pixel_size)
        print("Apparent size:", self.edge_apparent_size)

        self.win.setClearColor((135.0 / 255, 206.0 / 255, 235.0 / 255, 1))

        # Set up the environment
        #
        # Create some lighting
        self.vector_to_obs = base.cam.get_pos()
        self.vector_to_obs.normalize()
        if True:
            self.shadow_caster = ShadowMap(1024)
            self.shadow_caster.create()
            self.shadow_caster.set_lens(
                self.ralph_config.shadow_size,
                -self.ralph_config.shadow_box_length / 2.0,
                self.ralph_config.shadow_box_length / 2.0, -self.light_dir)
            self.shadow_caster.set_pos(
                self.light_dir * self.ralph_config.shadow_box_length / 2.0)
            self.shadow_caster.bias = 0.1
        else:
            self.shadow_caster = None

        self.ambientLight = AmbientLight("ambientLight")
        self.ambientLight.setColor(
            (settings.global_ambient, settings.global_ambient,
             settings.global_ambient, 1))
        self.directionalLight = DirectionalLight("directionalLight")
        self.directionalLight.setDirection(-self.light_dir)
        self.directionalLight.setColor(self.light_color)
        self.directionalLight.setSpecularColor(self.light_color)
        render.setLight(render.attachNewNode(self.ambientLight))
        render.setLight(render.attachNewNode(self.directionalLight))

        render.setShaderAuto()
        base.setFrameRateMeter(True)

        self.create_terrain()
        for component in self.ralph_config.layers:
            self.terrain.add_component(component)
            self.terrain_shape.add_linked_object(component)

        if self.ralph_config.fog_parameters is not None:
            self.fog = Fog(**self.ralph_config.fog_parameters)
            self.terrain.add_after_effect(self.fog)
        else:
            self.fog = None
        self.surface = self.terrain_object

        self.create_instance()
        self.create_tile(0, 0)
        self.skybox_init()

        self.set_light_angle(45)

        # Create the main character, Ralph

        ralphStartPos = LPoint3()
        self.ralph = Actor(
            "ralph-data/models/ralph", {
                "run": "ralph-data/models/ralph-run",
                "walk": "ralph-data/models/ralph-walk"
            })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 0.5))
        self.ralph_shape = InstanceShape(self.ralph)
        self.ralph_shape.parent = self
        self.ralph_shape.set_owner(self)
        self.ralph_shape.create_instance()
        self.ralph_appearance = ModelAppearance(self.ralph)
        self.ralph_appearance.set_shadow(self.shadow_caster)
        self.ralph_shader = BasicShader()
        self.ralph_shader.add_shadows(ShaderShadowMap())
        self.ralph_appearance.bake()
        self.ralph_appearance.apply(self.ralph_shape, self.ralph_shader)
        self.ralph_shader.apply(self.ralph_shape, self.ralph_appearance)
        self.ralph_shader.update(self.ralph_shape, self.ralph_appearance)

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(2.0)

        self.ralph_body = NodePathHolder(self.ralph)
        self.ralph_floater = NodePathHolder(self.floater)

        self.follow_cam = FollowCam(self, self.cam, self.ralph, self.floater)

        self.nav = RalphNav(self.ralph, self.ralph_floater, self.cam,
                            self.observer, self, self.follow_cam)
        self.nav.register_events(self)

        self.accept("escape", sys.exit)
        self.accept("control-q", sys.exit)
        self.accept("w", self.toggle_water)
        self.accept("h", self.print_debug)
        self.accept("f2", self.connect_pstats)
        self.accept("f3", self.toggle_filled_wireframe)
        self.accept("shift-f3", self.toggle_wireframe)
        self.accept("f5", self.bufferViewer.toggleEnable)
        self.accept('f8', self.toggle_lod_freeze)
        self.accept("shift-f8", self.terrain_shape.dump_tree)
        self.accept('control-f8', self.toggle_split_merge_debug)
        self.accept('shift-f9', self.toggle_bb)
        self.accept('control-f9', self.toggle_frustum)
        self.accept("f10", self.save_screenshot)
        self.accept('alt-enter', self.toggle_fullscreen)
        self.accept('{', self.incr_ambient, [-0.05])
        self.accept('}', self.incr_ambient, [+0.05])

        taskMgr.add(self.move, "moveTask")

        # Set up the camera
        self.follow_cam.update()
        self.distance_to_obs = self.cam.get_z() - self.get_height(
            self.cam.getPos())
        render.set_shader_input("camera", self.cam.get_pos())

        self.terrain.update_instance(LPoint3d(*self.cam.getPos()), None)
Esempio n. 33
0
class TerrainManager (object):
	class TerrainElement():
		def __init__(self,terrain,xPos,yPos):
			self.terrain=terrain
			self.xPos=xPos
			self.yPos=yPos

	def __init__(self):
		self.terrainElements=[]#holds all terrainElements
		self.terrainGrid=[[]]#holds terrainElements as they will be displayed
		self.dirty=True # the terrainGrid should be refreshed on next update
		self.rootNode = PandaNode("terrainManager root")
		self.root = NodePath( self.rootNode )
		self.terrainSize=257  #first=textureSize
		self.scale=16
		#locatoin that whereIsCamera returned last frame
		self.lastCamearaLocation = (0,0)
		self.currentCamearaLocation = (0,0)
		self.defaultBlockSize=64

	def whereIsCamera (self):
		'''where is the camera over the terrain
		returns a tuple of (x,y) for the grid location'''
		cam = base.camera.getPos()
		cam = (int (cam[0]) /(self.scale*self.terrainSize) ,
				int(cam[1]) /(self.scale*self.terrainSize ))
		return cam


	def newTerrainPart( self, heightMap, textureMap):
		'''create a new terrain element, when update is called they will be
		reorganized into a terrain grid and displayed'''
		self.dirtyGrid=True
		newPart = TerrainClass.TerrainClass(heightMap,heightMap)
		newPart.setMonoTexture( textureMap )
		newPart = self.TerrainElement( newPart, None, None )
		self.terrainElements.append( newPart )

	def getBlockSize(self):
		return self.terrainElements[0].terrain.getBlockSize()

	def setBlockSize( self, size=None ):
		if size is None:
			print "current block size:",self.getBlockSize()
			size = int ( raw_input( " input new blockSize:") )

		for i in self.terrainElements:
			i.terrain.setBlockSize( size )

		return

	def gridsAway( self, src, dst):
		'''src==tuple of starting grid location
		dst == tuple of ending grid location
		returns an integer containing number of grids seperating
		the two locations, does not take into account differences between
		diagnal and strait distance'''
		toRet = (abs(src[0]-dst[0]), 
				abs(src[1]-dst[1]))
		toRet = abs( toRet[0]+toRet[1])
		return toRet

	def autoBlockSizes(self):
		'''set the block sizes of the terrains based on the distance from
		the camera'''
		here = self.currentCamearaLocation
		default = self.defaultBlockSize
		if here == default:
			'''don't try to update if nothing changed'''
			return

		for row in range( len( self.terrainGrid ) ):
			for col in range( len( self.terrainGrid[row] ) ):
				new = default #defalut is defaultBlockSize
				distance = self.gridsAway( here, (row,col) )
				if distance > 2:
					new = new*(2**(distance-2))
					new = min ( self.terrainSize-1 , new )

				self.terrainGrid[row][col].setBlockSize( new )



	def update( self, task=None):
		'''update the terrain elements that need it
		and generate the terrain grid if it needs to be done ( is dirty)'''
		def isPerfectSquare( x ):
			y = int( math.sqrt(x) ) **2
			return y == x
		def makeTerrainGrid():
			self.terrainGrid=[] # empty list of lists
			self.dirty=False
			if not isPerfectSquare( len(self.terrainElements) ):
				raise Exception( "can't deal with non perfect square number "+
						"of terrains")
			side = int( math.sqrt( len( self.terrainElements ) ) )
			'''make terrain grid'''
			for i in xrange(side):
				y = i*self.terrainSize
				self.terrainGrid.append([])
				for j in xrange(side):
					x = j*self.terrainSize
					element = self.terrainElements[i*side+j]
					element.x=x
					element.y=y

					self.terrainGrid[i].append( element.terrain )
					element.terrain.getRoot().setPos( element.x, element.y,0 )

					elementNode= element.terrain.getRoot().getNode(0)
					self.rootNode.addChild(elementNode)

					
		#start the update
		'''reset camera locations'''
		self.lastCamearaLocation= self.currentCamearaLocation
		self.currentCamearaLocation= self.whereIsCamera()

		if self.lastCamearaLocation!= self.currentCamearaLocation:
			self.autoBlockSizes()

		if self.dirty:
			makeTerrainGrid()

		self.root.setScale(self.scale, self.scale, self.scale)
		#update one of the terrains
		side = len( self.terrainGrid )
		updateX = random.randint(0,side-1)
		updateY = random.randint(0,side-1)
		self.terrainGrid[updateX][updateY].asyncUpdate()

		

		if task is None:
			return
		else:
			return task.cont

	
	def getRoot(self):
		return  self.root
Esempio n. 34
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0,
        }

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        self.inst5 = addInstructions(0.30, "[Down Arrow]: Walk Ralph Backward")
        self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)

        # We do not have a skybox, so we will just use a sky blue background color
        self.setBackgroundColor(0.53, 0.80, 0.92, 1)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 1.5))

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(2.0)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])

        taskMgr.add(self.move, "moveTask")

        # Set up the camera
        self.disableMouse()
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        self.cTrav = CollisionTraverser()

        # Use a CollisionHandlerPusher to handle collisions between Ralph and
        # the environment. Ralph is added as a "from" object which will be
        # "pushed" out of the environment if he walks into obstacles.
        #
        # Ralph is composed of two spheres, one around the torso and one
        # around the head.  They are slightly oversized since we want Ralph to
        # keep some distance from obstacles.
        self.ralphCol = CollisionNode('ralph')
        self.ralphCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5))
        self.ralphCol.addSolid(
            CollisionSphere(center=(0, -0.25, 4), radius=1.5))
        self.ralphCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphColNp = self.ralph.attachNewNode(self.ralphCol)
        self.ralphPusher = CollisionHandlerPusher()
        self.ralphPusher.horizontal = True

        # Note that we need to add ralph both to the pusher and to the
        # traverser; the pusher needs to know which node to push back when a
        # collision occurs!
        self.ralphPusher.addCollider(self.ralphColNp, self.ralph)
        self.cTrav.addCollider(self.ralphColNp, self.ralphPusher)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.
        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((-5, -5, -5))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
    def __init__(self):

        # Set up the window, camera, etc.
        base.destroy()
        ShowBase.__init__(self)
        self.ser = serial.Serial('/dev/tty.usbmodem1421', 9600)
        # Set the background color to black
        self.win.setClearColor((0, 0, 0, 1))

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "reverse": 0,
            "cam-left": 0,
            "cam-right": 0
        }

        #Initialize Track
        self.track = self.loader.loadModel("All_Tracks/luigi_circuit")
        self.track.setScale(1.5)
        self.track.reparentTo(render)

        #Intitial where Mario needs to be
        #marioStartPos = self.track.find("**/start_point").getPos()
        marioStartPos = Vec3(50, -29,
                             0.35)  #Actual start possition for Luigi_Circuit
        # marioStartPos = Vec3(20, -40, 31)
        #Using ralph because the model is made with correct collision masking and animation
        self.marioActor = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.marioActor.setScale(0.1, 0.1, 0.1)
        self.marioActor.setH(self.marioActor, 270)
        self.marioActor.reparentTo(self.render)
        self.marioActor.setPos(marioStartPos + (0, 0, 0.5))

        #Floater above so Camera has something to look at
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.marioActor)
        self.floater.setZ(2.0)

        taskMgr.add(self.move, "moveTask")
        # Game state variables
        self.isMoving = False

        # Set up the camera
        self.disableMouse()
        self.camera.setPos(self.marioActor.getX() + 100,
                           self.marioActor.getY(), 1)

        #Collision Rays
        self.cTrav = CollisionTraverser()

        self.marioGroundRay = CollisionRay()
        self.marioGroundRay.setOrigin(0, 0, 9)
        self.marioGroundRay.setDirection(0, 0, -1)
        self.marioGroundCol = CollisionNode('marioRay')
        self.marioGroundCol.addSolid(self.marioGroundRay)
        self.marioGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.marioGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.marioGroundColNp = self.marioActor.attachNewNode(
            self.marioGroundCol)
        self.marioGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.marioGroundColNp, self.marioGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
Esempio n. 36
0
    def move(self, task):

        # Get the time that elapsed since last frame.  We multiply this with
        # the desired speed in order to find out with which distance to move
        # in order to achieve that desired speed.
        dt = globalClock.getDt()

        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        if self.keyMap["cam-left"]:
            self.camera.setX(self.camera, -20 * dt)
        if self.keyMap["cam-right"]:
            self.camera.setX(self.camera, +20 * dt)

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        # add rotate left right up down
        if self.keyMap["left"]:
            self.ralph.setX(self.ralph, 200 * dt)
            #self.ralph.setH(self.ralph.getH() + 200 * dt)
        if self.keyMap["right"]:
            self.ralph.setX(self.ralph, -200 * dt)
            #self.ralph.setH(self.ralph.getH() - 200 * dt)
        if self.keyMap["forward"]:
            self.ralph.setY(self.ralph, -200 * dt)
        if self.keyMap["backward"]:
            self.ralph.setY(self.ralph, 200 * dt)

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap[
                "right"]:
            if self.isMoving is False:
                self.ralph.loop("run")
                self.isMoving = True
        else:
            if self.isMoving:
                self.ralph.stop()
                self.ralph.pose("walk", 5)
                self.isMoving = False

        # Normally, we would have to call traverse() to check for collisions.
        # However, the class ShowBase that we inherit from has a task to do
        # this for us, if we assign a CollisionTraverser to self.cTrav.
        #self.cTrav.traverse(render)

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.

        #todo: pick a good camera angle
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(2)

        self.camera.setPos(0, -3, 3)
        self.camera.setH(180)
        #self.camera.lookAt(self.ralph)

        return task.cont
Esempio n. 37
0
 def __set_toon():
     tempnode = NodePath(PandaNode('temp node'))
     tempnode.setAttrib(LightRampAttrib.make_single_threshold(.5, .4))
     tempnode.set_shader_auto()
     base.cam.node().set_initial_state(tempnode.get_state())
     CommonFilters(base.win, base.cam).set_cartoon_ink(separation=1)
Esempio n. 38
0
def test_nodepath_transform_composition():
    """Tests that NodePath composes transform states according to the path it holds."""
    from panda3d.core import PandaNode, NodePath, LPoint3, LVector3

    # Create 3 PandaNodes, and give each some interesting transform state:
    node1 = PandaNode('node1')
    node2 = PandaNode('node2')
    node3 = PandaNode('node3')

    node1.set_transform(node1.get_transform().set_pos(LPoint3(0, 0, 1)).set_hpr(LVector3(90, 0, -90)))
    node2.set_transform(node2.get_transform().set_pos(LPoint3(0, 1, 0)).set_hpr(LVector3(180, 180, 0)))
    node3.set_transform(node3.get_transform().set_pos(LPoint3(1, 0, 0)).set_hpr(LVector3(270, 0, 270)))

    # node3 is going to be attached under both node1 and node2 and we will
    # hold a path both ways:
    node1.add_child(node3)
    node2.add_child(node3)

    assert len(node1.children) == 1
    assert len(node2.children) == 1
    assert len(node3.children) == 0
    assert len(node1.parents) == 0
    assert len(node2.parents) == 0
    assert len(node3.parents) == 2

    # np1 is the path to node3 via node1:
    np1 = NodePath(node1).children[0]
    # np2 is the path to node3 via node2:
    np2 = NodePath(node2).children[0]

    # Both should point to node3:
    assert np1.node() == node3
    assert np2.node() == node3

    # However if we ask for the net transform to node3, it should compose:
    assert np1.get_transform(NodePath()) == node1.get_transform().compose(node3.get_transform())
    assert np2.get_transform(NodePath()) == node2.get_transform().compose(node3.get_transform())

    # If we ask for np1 RELATIVE to np2, it should compose like so:
    leg1 = node2.get_transform().compose(node3.get_transform())
    leg2 = node1.get_transform().compose(node3.get_transform())
    relative_transform = leg1.get_inverse().compose(leg2)
    assert np1.get_transform(np2) == relative_transform
Esempio n. 39
0
class NametagGroup:
    CHAT_TIMEOUT_MIN = 4.0
    CHAT_TIMEOUT_MAX = 12.0
    CHAT_STOMP_DELAY = 0.2

    def __init__(self):
        self.avatar = None
        self.active = True
        self.objectCode = None
        self.chatButton = NametagGlobals.noButton
        self.chatReversed = False
        self.font = None
        self.chatFont = None
        self.shadow = None
        self.marginManager = None
        self.visible3d = True
        self.chatType = NametagGlobals.CHAT
        self.chatBalloonType = NametagGlobals.CHAT_BALLOON
        self.nametagColor = NametagGlobals.NametagColors[
            NametagGlobals.CCNormal]
        self.chatColor = NametagGlobals.ChatColors[NametagGlobals.CCNormal]
        self.speedChatColor = VBase4(1, 1, 1, 1)
        self.wordWrap = 8
        self.chatWordWrap = 12
        self.text = ''
        self.name = ''
        self.chatPages = []
        self.chatPageIndex = 0
        self.chatTimeoutTask = None
        self.chatTimeoutTaskName = self.getUniqueName() + '-timeout'
        self.stompChatText = ''
        self.stompTask = None
        self.stompTaskName = self.getUniqueName() + '-stomp'
        self.icon = PandaNode('icon')
        self.nametag2d = Nametag2d()
        self.nametag3d = Nametag3d()
        self.nametags = set()
        self.add(self.nametag2d)
        self.add(self.nametag3d)
        self.tickTaskName = self.getUniqueName() + '-tick'
        self.tickTask = taskMgr.add(self.tick, self.tickTaskName, sort=45)

    def destroy(self):
        if self.marginManager is not None:
            self.unmanage(self.marginManager)
        if self.tickTask is not None:
            taskMgr.remove(self.tickTask)
            self.tickTask = None
        self.clearChatText()
        for nametag in list(self.nametags):
            self.remove(nametag)

        self.nametag2d = None
        self.nametag3d = None
        if self.icon is not None:
            self.icon.removeAllChildren()
            self.icon = None
        self.chatFont = None
        self.font = None
        self.chatButton = NametagGlobals.noButton
        self.avatar = None

    def getUniqueName(self):
        return 'NametagGroup-%s' % id(self)

    def getNameIcon(self):
        return self.icon

    def tick(self, task):
        if self.avatar is None or self.avatar.isEmpty():
            return Task.cont
        chatText = self.getChatText()
        if NametagGlobals.forceOnscreenChat and chatText and self.chatBalloonType == NametagGlobals.CHAT_BALLOON:
            visible3d = False
        elif self.avatar == NametagGlobals.me:
            if chatText and self.chatBalloonType == NametagGlobals.CHAT_BALLOON and not base.cam.node(
            ).isInView(self.avatar.getPos(base.cam)):
                visible3d = False
            else:
                visible3d = True
        elif NametagGlobals.force2dNametags:
            visible3d = False
        elif not NametagGlobals.want2dNametags and (
                not chatText
                or self.chatBalloonType != NametagGlobals.CHAT_BALLOON):
            visible3d = True
        elif self.avatar.isHidden():
            visible3d = False
        else:
            visible3d = base.cam.node().isInView(self.avatar.getPos(base.cam))
        if visible3d != self.visible3d:
            self.visible3d = visible3d
            if self.nametag2d is not None:
                self.nametag2d.setVisible(not visible3d)
        return Task.cont

    def setAvatar(self, avatar):
        self.avatar = avatar
        for nametag in self.nametags:
            nametag.setAvatar(self.avatar)

    def getAvatar(self):
        return self.avatar

    def setActive(self, active):
        self.active = active
        for nametag in self.nametags:
            nametag.setActive(self.active)

    def getActive(self):
        return self.active

    def setObjectCode(self, objectCode):
        self.objectCode = objectCode

    def getObjectCode(self):
        return self.objectCode

    def setChatButton(self, chatButton):
        self.chatButton = chatButton
        for nametag in self.nametags:
            nametag.setChatButton(self.chatButton)

    def getChatButton(self):
        return self.chatButton

    def hasChatButton(self):
        return self.chatButton != NametagGlobals.noButton

    def setChatReversed(self, reversed):
        self.chatReversed = reversed
        for nametag in self.nametags:
            nametag.setChatReversed(reversed)

    def getChatReversed(self):
        return self.chatReversed

    def setFont(self, font):
        self.font = font
        for nametag in self.nametags:
            nametag.setFont(self.font)

    def getFont(self):
        return self.font

    def setChatFont(self, chatFont):
        self.chatFont = chatFont
        for nametag in self.nametags:
            nametag.setChatFont(self.chatFont)

    def getChatFont(self):
        return self.chatFont

    def setShadow(self, shadow):
        self.shadow = shadow
        for nametag in self.nametags:
            nametag.setShadow(self.shadow)

    def getShadow(self):
        return self.shadow

    def clearShadow(self):
        self.shadow = None
        for nametag in self.nametags:
            nametag.clearShadow()

    def setChatType(self, chatType):
        self.chatType = chatType
        for nametag in self.nametags:
            nametag.setChatType(self.chatType)

    def getChatType(self):
        return self.chatType

    def setChatBalloonType(self, chatBalloonType):
        self.chatBalloonType = chatBalloonType
        for nametag in self.nametags:
            nametag.setChatBalloonType(self.chatBalloonType)

    def getChatBalloonType(self):
        return self.chatBalloonType

    def setNametagColor(self, nametagColor):
        self.nametagColor = nametagColor
        for nametag in self.nametags:
            nametag.setNametagColor(self.nametagColor)

    def getNametagColor(self):
        return self.nametagColor

    def setChatColor(self, chatColor):
        self.chatColor = chatColor
        for nametag in self.nametags:
            nametag.setChatColor(self.chatColor)

    def getChatColor(self):
        return self.chatColor

    def setSpeedChatColor(self, speedChatColor):
        self.speedChatColor = speedChatColor
        for nametag in self.nametags:
            nametag.setSpeedChatColor(self.speedChatColor)

    def getSpeedChatColor(self):
        return self.speedChatColor

    def setWordWrap(self, wordWrap):
        self.wordWrap = wordWrap
        for nametag in self.nametags:
            nametag.setWordWrap(self.wordWrap)

    def getWordWrap(self):
        return self.wordWrap

    def setChatWordWrap(self, chatWordWrap):
        self.chatWordWrap = chatWordWrap
        for nametag in self.nametags:
            nametag.setChatWordWrap(self.chatWordWrap)

    def getChatWordWrap(self):
        return self.chatWordWrap

    def setText(self, text):
        self.text = text
        for nametag in self.nametags:
            nametag.setText(self.text)
            nametag.update()

    def getText(self):
        return self.text

    def getNumChatPages(self):
        return len(self.chatPages)

    def setChatPageIndex(self, chatPageIndex):
        if chatPageIndex >= self.getNumChatPages():
            return
        self.chatPageIndex = chatPageIndex
        for nametag in self.nametags:
            nametag.setChatText(self.chatPages[self.chatPageIndex])
            nametag.update()

    def getChatPageIndex(self):
        return self.chatPageIndex

    def setChatText(self, chatText, timeout=False):
        if self.getChatText():
            self.clearChatText()
            self.stompChatText = chatText
            self.stompTask = taskMgr.doMethodLater(self.CHAT_STOMP_DELAY,
                                                   self.__chatStomp,
                                                   self.stompTaskName,
                                                   extraArgs=[timeout])
            return
        self.clearChatText()
        self.chatPages = chatText.split('\x07')
        self.setChatPageIndex(0)
        if timeout:
            delay = len(self.getChatText()) * 0.5
            if delay < self.CHAT_TIMEOUT_MIN:
                delay = self.CHAT_TIMEOUT_MIN
            elif delay > self.CHAT_TIMEOUT_MAX:
                delay = self.CHAT_TIMEOUT_MAX
            self.chatTimeoutTask = taskMgr.doMethodLater(
                delay, self.clearChatText, self.chatTimeoutTaskName)

    def getChatText(self):
        if self.chatPageIndex >= self.getNumChatPages():
            return ''
        return self.chatPages[self.chatPageIndex]

    def clearChatText(self, task=None):
        if self.stompTask is not None:
            taskMgr.remove(self.stompTask)
            self.stompTask = None
        self.stompChatText = ''
        if self.chatTimeoutTask is not None:
            taskMgr.remove(self.chatTimeoutTask)
            self.chatTimeoutTask = None
        self.chatPages = []
        self.chatPageIndex = 0
        for nametag in self.nametags:
            nametag.setChatText('')
            nametag.update()

        if task is not None:
            return Task.done

    def getStompChatText(self):
        return self.stompChatText

    def setIcon(self, icon):
        self.icon = icon
        for nametag in self.nametags:
            nametag.setIcon(self.icon)

    def getIcon(self):
        return self.icon

    def setNametag2d(self, nametag2d):
        if self.nametag2d is not None:
            self.remove(self.nametag2d)
            self.nametag2d = None
        if nametag2d is None:
            return
        self.nametag2d = nametag2d
        self.add(self.nametag2d)

    def getNametag2d(self):
        return self.nametag2d

    def setNametag3d(self, nametag3d):
        if self.nametag3d is not None:
            self.remove(self.nametag3d)
            self.nametag3d = None
        if nametag3d is None:
            return
        self.nametag3d = nametag3d
        self.add(self.nametag3d)

    def getNametag3d(self):
        return self.nametag3d

    def add(self, nametag):
        self.nametags.add(nametag)
        nametag.setAvatar(self.avatar)
        nametag.setActive(self.active)
        nametag.setClickEvent(self.getUniqueName())
        nametag.setChatButton(self.chatButton)
        nametag.setFont(self.font)
        nametag.setChatFont(self.chatFont)
        nametag.setChatType(self.chatType)
        nametag.setChatBalloonType(self.chatBalloonType)
        nametag.setNametagColor(self.nametagColor)
        nametag.setChatColor(self.chatColor)
        nametag.setSpeedChatColor(self.speedChatColor)
        nametag.setWordWrap(self.wordWrap)
        nametag.setChatWordWrap(self.chatWordWrap)
        nametag.setText(self.text)
        nametag.setChatText(self.getChatText())
        nametag.setIcon(self.icon)
        nametag.update()

    def remove(self, nametag):
        nametag.destroy()
        self.nametags.remove(nametag)

    def updateAll(self):
        for nametag in self.nametags:
            nametag.update()

    def manage(self, marginManager):
        if self.marginManager is not None:
            self.unmanage(self.marginManager)
        self.marginManager = marginManager
        for nametag in self.nametags:
            if isinstance(nametag, MarginVisible):
                nametag.manage(self.marginManager)

    def unmanage(self, marginManager):
        if marginManager != self.marginManager:
            return
        if self.marginManager is None:
            return
        self.marginManager = marginManager
        for nametag in self.nametags:
            if isinstance(nametag, MarginVisible):
                nametag.unmanage(self.marginManager)

    def hideNametag(self):
        for nametag in self.nametags:
            nametag.hideNametag()

    def showNametag(self):
        for nametag in self.nametags:
            nametag.showNametag()

    def hideChat(self):
        for nametag in self.nametags:
            nametag.hideChat()

    def showChat(self):
        for nametag in self.nametags:
            nametag.showChat()

    def hideThought(self):
        for nametag in self.nametags:
            nametag.hideThought()

    def showThought(self):
        for nametag in self.nametags:
            nametag.showThought()

    def __chatStomp(self, timeout=False):
        self.setChatText(self.stompChatText, timeout=timeout)
        self.stompChatText = ''
Esempio n. 40
0
    def __init__(self):

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0,
            "grab": 0,
            "jump": 0,
            "run": 0,
            "walk": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Post the instructions

        self.title = addTitle("RC-Soft: Catch the butterfly")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        self.inst8 = addInstructions(0.60, "[G]: Grab")
        self.inst9 = addInstructions(0.55, "[J]: Jump [R]: Run [W]:Walk")
        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor(
            "models/ralph", {
                "run": "models/ralph-run",
                "walk": "models/ralph-walk",
                "grab": "models/ralph-run"
            })  ## TODO : create model grab action
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        #show my fly
        self.fly = Actor("models/fluture", {
            "run": "models/fluture-anim1",
            "walk": "models/fluture-anim1"
        })
        self.fly.reparentTo(render)
        self.fly.setScale(.08)
        self.fly.setPos(ralphStartPos)
        self.fly.loop("run")  #start fly animation

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])
        self.accept('1', self.setObject, [0])
        self.accept('2', self.setObject, [1])
        self.accept('3', self.setObject, [2])
        self.accept('4', self.setObject, [3])
        self.accept('g', self.setKey, ["grab", 1])
        self.accept('j', self.setKey, ["jump", 1])
        self.accept('j-up', self.setKey, ["jump", 0])
        self.accept('r', self.setKey, ["run", 1])
        self.accept('w', self.setKey, ["walk", 1])
        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 1000)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

        # show an object in Ralph's hand
        #Now we will expose the joint the hand joint. ExposeJoint allows us to
        #get the position of a joint while it is animating. This is different than
        #controlJonit which stops that joint from animating but lets us move it.
        #This is particularly usefull for putting an object (like a weapon) in an
        #actor's hand
        self.rightHand = self.ralph.exposeJoint(None, 'modelRoot', 'RightHand')

        #This is a table with models, positions, rotations, and scales of objects to
        #be attached to our exposed joint. These are stock models and so they needed
        #to be repositioned to look right.
        positions = [("models/net", (0, -.66, -.95), (90, 0, 90), .4),
                     ("models/fluture", (.15, -.99, -.22), (90, 0, 90), .5),
                     ("models/banana", (.08, -.1, .09), (0, -90, 0), 1.75),
                     ("models/sword", (.11, .19, .06), (0, 0, 90), 1)]
        self.models = []  #A list that will store our models objects
        for row in positions:
            np = loader.loadModel(row[0])  #Load the model
            np.setPos(row[1][0], row[1][1], row[1][2])  #Position it
            np.setHpr(row[2][0], row[2][1], row[2][2])  #Rotate it
            np.setScale(row[3])  #Scale it
            #Reparent the model to the exposed joint. That way when the joint moves,
            #the model we just loaded will move with it.
            np.reparentTo(self.rightHand)
            self.models.append(np)  #Add it to our models list

        self.setObject(0)
Esempio n. 41
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0, 0, 0, 1))

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0}

        # Post the instructions
        self.title = addTitle(
            "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                           {"run": "models/ralph-run",
                            "walk": "models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos + (0, 0, 0.5))

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(2.0)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        self.disableMouse()
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)
Esempio n. 42
0
 def __init__(self, name, fromFile=None):
     PandaNode.__init__(self, name)
     self.elements = []
     self.fromFile = fromFile
Esempio n. 43
0
    def __init__(self):
        global speed
        global maxspeed

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "accelerate": 0,
            "decelerate": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # Post the instructions
        self.title = addTitle(
            "HW2: Roaming Ralph Modified (Walking on the Moon) with friends")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[W]: Move Ralph Forward")
        self.inst5 = addInstructions(0.75,
                                     "[P]: Increase Ralph Velocity (Run)")
        self.inst6 = addInstructions(0.70,
                                     "[O]: Decrease Ralph Velocity (Walk)")
        self.inst7 = addInstructions(0.60, "[Left Arrow]: Rotate Camera Left")
        self.inst8 = addInstructions(0.55,
                                     "[Right Arrow]: Rotate Camera Right")

        # Set up the environment
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.environ.setScale(100, 100, 1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        # Create the main character, Ralph

        if (v == [0]):
            print(model)
            self.ralph = Actor("models/ralph", {
                "run": "models/ralph-run",
                "walk": "models/ralph-walk"
            })
            self.ralph.setScale(.2)
        elif (v == [1]):
            print(model)
            self.ralph = Actor("models/panda-model",
                               {"walk": "models/panda-walk4"})
            speed = 100
            maxspeed = 10000
            self.ralph.setScale(0.0001, 0.00015, 0.0005)
            self.ralph.setScale(.002)

            self.ralph.setPlayRate(100.0, "models/panda-walk4")
            speed = 100
            maxspeed = 10000
            self.ralph.setScale(.0035)
        else:
            print(model)
            self.ralph = Actor("models/GroundRoamer.egg")
            self.ralph.setScale(.15)
            self.ralph.setHpr(180, 0, 0)
            self.Groundroamer_texture = loader.loadTexture(
                "models/Groundroamer.tif")
            self.ralph.setTexture(self.Groundroamer_texture)

        self.ralph.reparentTo(render)
        self.ralph.setPos(0, 0, 0)

        #creates Earth
        self.earth = Actor("models/planet_sphere.egg.pz")
        self.earth.reparentTo(render)
        self.earth.setScale(6.0)
        self.earth.setPos(40, 25, 6)
        self.earth_texture = loader.loadTexture("models/earth_1k_tex.jpg")
        self.earth.setTexture(self.earth_texture)

        #creates Mercury
        self.mercury = Actor("models/planet_sphere.egg.pz")
        self.mercury.reparentTo(render)
        self.mercury.setScale(2.0)
        self.mercury.setPos(-40, -25, 2)
        self.mercury_texture = loader.loadTexture("models/mercury_1k_tex.jpg")
        self.mercury.setTexture(self.mercury_texture)

        #creates Venus
        self.venus = Actor("models/planet_sphere.egg.pz")
        self.venus.reparentTo(render)
        self.venus.setScale(4.0)
        self.venus.setPos(40, -30, 4)
        self.venus_texture = loader.loadTexture("models/venus_1k_tex.jpg")
        self.venus.setTexture(self.venus_texture)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation
        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("s", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("p", self.setKey, ["accelerate", 1])
        self.accept("o", self.setKey, ["decelerate", 1])
        self.accept("p-up", self.setKey, ["accelerate", 0])
        self.accept("o-up", self.setKey, ["decelerate", 0])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        #self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        #self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
    def __init__(self):

        ShowBase.__init__(self)
        self.win.setClearColor((0.455, 0.816, 0.945, 1))

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "jump": 0,
            "action": 0
        }

        # Mise en place des instructions
        self.title = addTitle("Project : 'Escape the forest'")
        self.inst1 = addInstructions(0.06, "[ECHAP]: Quit")
        self.inst2 = addInstructions(0.12, "[Left arrow]: Turn Freddy left")
        self.inst3 = addInstructions(0.18, "[Right arrow]: Turn Freddy right")
        self.inst4 = addInstructions(0.24,
                                     "[Top arrow]: Make Freddy move forward")
        self.inst5 = addInstructions(0.30,
                                     "Bottom arrow]: Make Freddy move back")
        self.inst6 = addInstructions(0.36, "[Space]: Make Freddy jump")
        self.inst7 = addInstructions(0.42, "[A]: Operate the lever")

        # 3D objects
        self.map = loader.loadModel("obj/Map.egg.pz")
        self.map.reparentTo(render)

        self.walls = loader.loadModel("obj/Wall.egg")
        self.walls.reparentTo(render)

        self.bridge = Actor("obj/Bridge.egg", {"Drop": "obj/Bridge.egg"})
        self.bridge.reparentTo(render)
        self.bridge.pose("Drop", 0)

        self.lever = Actor("obj/Lever.egg", {"OnOff": "obj/Lever.egg"})
        self.lever.reparentTo(render)
        self.lever.setPos(0, 12, 1)
        self.lever.pose("OnOff", 0)

        self.lever1 = Actor("obj/Lever.egg", {"OnOff": "obj/Lever.egg"})
        self.lever1.reparentTo(render)
        self.lever1.setPos(50, 16, 1)
        self.lever1.pose("OnOff", 0)

        self.lever2 = Actor("obj/Lever.egg", {"OnOff": "obj/Lever.egg"})
        self.lever2.reparentTo(render)
        self.lever2.setPos(22, 92, 1)
        self.lever2.pose("OnOff", 0)

        self.dirt = Actor("obj/Dirt.egg", {"Up": "obj/Dirt.egg"})
        self.dirt.reparentTo(render)

        self.stone = Actor("obj/Stone.egg", {"Fall": "obj/Stone.egg"})
        self.stone.reparentTo(render)

        # Creation of the main character, Freddy
        FreddyStartPos = (8, -8, 1.5)
        self.Freddy = Actor("obj/Freddy.egg", {
            "Run": "obj/Run.egg",
            "Pose": "obj/Pose.egg"
        })
        self.Freddy.reparentTo(render)
        self.Freddy.setScale(1.4)
        self.Freddy.setPos(FreddyStartPos)
        self.Freddy.setH(180)

        winsound.PlaySound("sound/music.wav", winsound.SND_ASYNC)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.Freddy)
        self.floater.setZ(0)

        # Controls for move and interact

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["backward", True])
        self.accept("space", self.setKey, ["jump", True])
        self.accept("a", self.setKey, ["action", True])

        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["backward", False])
        self.accept("space-up", self.setKey, ["jump", False])
        self.accept("a-up", self.setKey, ["action", False])

        taskMgr.add(self.movement, "Movement")

        self.moving = False

        self.disableMouse()

        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))

        # Collisions
        self.cTrav = CollisionTraverser()
        self.pusher = CollisionHandlerPusher()
        self.FreddyGroundHandler = CollisionHandlerQueue()
        self.FreddyGroundSphere = CollisionSphere(
            0, 0, 0.5, 0.3)  #Coordinates of the center and radius
        self.FreddyGroundCol = CollisionNode('freddySphere')
        self.FreddyGroundCol.addSolid(self.FreddyGroundSphere)
        self.FreddyGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.FreddyGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.FreddyGroundColNp = self.Freddy.attachNewNode(
            self.FreddyGroundCol)
        self.cTrav.addCollider(self.FreddyGroundColNp,
                               self.FreddyGroundHandler)

        self.BridgeHandler = CollisionHandlerQueue()
        self.BridgeBox = CollisionBox((1, 17, 0), (5, 16.8, 10))
        self.BridgeCol = CollisionNode('bridgeBox')
        self.BridgeCol.addSolid(self.BridgeBox)
        self.BridgeCol.setFromCollideMask(BitMask32.allOff())
        self.BridgeCol.setIntoCollideMask(BitMask32.bit(0))
        self.BridgeColNp = self.bridge.attachNewNode(self.BridgeCol)
        self.cTrav.addCollider(self.BridgeColNp, self.BridgeHandler)
        self.pusher.addCollider(self.FreddyGroundColNp, self.BridgeColNp)

        self.StoneHandler = CollisionHandlerQueue()
        self.StoneBox = CollisionBox((39, 27, 0), (41, 31, 3))
        self.StoneCol = CollisionNode('stoneBox')
        self.StoneCol.addSolid(self.StoneBox)
        self.StoneCol.setFromCollideMask(BitMask32.allOff())
        self.StoneCol.setIntoCollideMask(BitMask32.bit(0))
        self.StoneColNp = self.stone.attachNewNode(self.StoneCol)
        self.cTrav.addCollider(self.StoneColNp, self.StoneHandler)
        self.pusher.addCollider(self.FreddyGroundColNp, self.StoneColNp)

        self.DirtHandler = CollisionHandlerQueue()
        self.DirtBox = CollisionBox((15, 83, 0), (13, 82.5, 5))
        self.DirtCol = CollisionNode('dirtBox')
        self.DirtCol.addSolid(self.DirtBox)
        self.DirtCol.setFromCollideMask(BitMask32.allOff())
        self.DirtCol.setIntoCollideMask(BitMask32.bit(0))
        self.DirtColNp = self.dirt.attachNewNode(self.DirtCol)
        self.cTrav.addCollider(self.DirtColNp, self.DirtHandler)
        self.pusher.addCollider(self.FreddyGroundColNp, self.DirtColNp)
Esempio n. 45
0
 def __resetPrevTransform(self, state):
     PandaNode.resetAllPrevTransform()
     return Task.cont