Esempio n. 1
0
class beastGlobals(DirectObject):
	def __init__(self, base):
		DirectObject.__init__(self)
		self.base = base

        '''
            Setup point2d NodePath
        '''
		self.point2d = NodePath(PGTop('point2d'))
		self.point2d.node().setMouseWatcher(self.base.mouseWatcherNode)
		self.point2d.setDepthTest(False)
		self.point2d.setDepthWrite(False)
		self.point2d.setMaterialOff(True)
		self.point2d.setTwoSided(True)

		self.p2dTopLeft = self.point2d.attachNewNode('p2dTopLeft')
		self.p2dTopRight = self.point2d.attachNewNode('p2dTopRight')
		self.p2dTopCenter = self.point2d.attachNewNode('p2dTopCenter')

		self.p2dCenterLeft = self.point2d.attachNewNode('p2dCenterLeft')
		self.p2dCenterRight = self.point2d.attachNewNode('p2dCenterRight')

		self.p2dBottomLeft = self.point2d.attachNewNode('p2dBottomLeft')
		self.p2dBottomRight = self.point2d.attachNewNode('p2dBottomRight')
		self.p2dBottomCenter = self.point2d.attachNewNode('p2dBottomCenter')

		self.beastPointSize = ConfigVariableDouble('beast-point-size', 1.0).getValue()
		self.beastPointSizeAuto = ConfigVariableBool('beast-point-size-auto', False).getValue()
		self.beastRenderCache = ConfigVariableBool('beast-render-cache', True).getValue()
		self.beastRenderDebug = ConfigVariableBool('beast-render-debug', False).getValue()

		self.setPointSize(self.beastPointSize, update = False)
		self.setPointSizeAuto(self.beastPointSizeAuto, update = False)
		self.accept('window-event', self.windowEvent)
		self.originalResolution = (float(self.base.win.getXSize()), float(self.base.win.getYSize()))
Esempio n. 2
0
    def __init__(self, taskMgr, base):
        DirectObject.__init__(self)
        self.taskMgr = taskMgr
        self.base = base
        self.setupPoint2d()

        self.beastPointSize = ConfigVariableDouble('beast-point-size',
                                                   1.0).getValue()
        self.beastPointSizeAuto = ConfigVariableBool('beast-point-size-auto',
                                                     False).getValue()
        self.beastRenderBruteForce = ConfigVariableBool(
            'beast-render-brute-force', False).getValue()
        self.beastRenderDebug = ConfigVariableBool('beast-render-debug',
                                                   False).getValue()

        self.setPointSize(self.beastPointSize, update=False)
        self.setPointSizeAuto(self.beastPointSizeAuto, update=False)
        self.accept('window-event', self.windowEvent)
        self.originalResolution = (float(self.base.win.getXSize()),
                                   float(self.base.win.getYSize()))

        self.buffer = None
        #- If bruteForce == False then we will setup beast frame rendering system
        if self.beastRenderBruteForce == False:
            self._setupTextureBuffer()
            taskMgr.add(self.renderTask, 'beastRender', sort=-100000000)

        self.windowEvent()
Esempio n. 3
0
    def __init__(self, name, dynamic=False):
        NodePath.__init__(self, PGTop(name))
        DirectObject.__init__(self)
        self.setPythonTag('SpriteCollection', self)

        global SpriteCollectionCounter
        SpriteCollectionCounter += 1
        self.__id = int(SpriteCollectionCounter)

        self.node().setMouseWatcher(base.mouseWatcherNode)
        self.setDepthTest(False)
        self.setDepthWrite(False)
        self.setMaterialOff(True)
        self.setTwoSided(True)

        self.__lastRender = globalClock.getFrameCount()
        self.buffer = None
        self.__dynamic = dynamic
        self.__beastRenderCache = ConfigVariableBool('beast-render-cache',
                                                     True).getValue()
        self.__beastForceNewFrame = ConfigVariableBool('beast-force-new-frame',
                                                       True).getValue()
        self.__beastDebug = ConfigVariableBool('beast-debug', False).getValue()
        if self.__dynamic == False and self.__beastRenderCache == True:
            self.fakeRender2d = NodePath('fakeRender2d-%s-%s' %
                                         (self.__id, self.getName()))
            self.reparentTo(self.fakeRender2d)

            self._setupTextureBuffer()
            self.accept('beastCollectionUpdate', self._update)
            base.taskMgr.add(self._update,
                             'updateTask-%s-%s' % (self.__id, self.getName()),
                             sort=-1000)
        else:
            self.reparentTo(render2d)
Esempio n. 4
0
 def setFullscreen():
     """Helper function to set the window fullscreen
     with width and height set to the screens size"""
     # set window properties
     # clear all properties not previously set
     base.win.clearRejectedProperties()
     # setup new window properties
     props = WindowProperties()
     # Fullscreen
     props.setFullscreen(True)
     # set the window size to the screen resolution
     props.setSize(self.dispWidth, self.dispHeight)
     # request the new properties
     base.win.requestProperties(props)
     # Set the config variables so we correctly store the
     # new size and fullscreen setting later
     winSize = ConfigVariableString("win-size")
     winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
     fullscreen = ConfigVariableBool("fullscreen")
     fullscreen.setValue(True)
     # Render a frame to make sure the fullscreen is applied
     # before we do anything else
     self.taskMgr.step()
     # make sure to propagate the new aspect ratio properly so
     # the GUI and other things will be scaled appropriately
     aspectRatio = self.dispWidth / self.dispHeight
     self.adjustWindowAspectRatio(aspectRatio)
Esempio n. 5
0
class TwoDWalker(GravityWalker):
    """
    The TwoDWalker is primarily for a 2D Scroller game environment. Eg - Toon Blitz minigame.
    TODO: This class is still work in progress.
    Currently Toon Blitz is using this only for jumping.
    Moving the Toon left to right is handled by toontown/src/minigame/TwoDDrive.py.
    I eventually want this class to control all the 2 D movements, possibly with a
    customizable input list.
    """
    notify = directNotify.newCategory("TwoDWalker")
    wantDebugIndicator = ConfigVariableBool('want-avatar-physics-indicator',
                                            False)
    wantFloorSphere = ConfigVariableBool('want-floor-sphere', False)
    earlyEventSphere = ConfigVariableBool('early-event-sphere', False)

    # special methods
    def __init__(self,
                 gravity=-32.1740,
                 standableGround=0.707,
                 hardLandingForce=16.0):
        assert self.notify.debugStateCall(self)
        self.notify.debug('Constructing TwoDWalker')
        GravityWalker.__init__(self)

    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        # get the button states:
        jump = inputState.isSet("forward")
        if self.lifter.isOnGround():
            if self.isAirborne:
                self.isAirborne = 0
                assert self.debugPrint("isAirborne 0 due to isOnGround() true")
                impact = self.lifter.getImpactVelocity()
                messenger.send("jumpLand")
            assert self.isAirborne == 0
            self.priorParent = Vec3.zero()
        else:
            if self.isAirborne == 0:
                assert self.debugPrint(
                    "isAirborne 1 due to isOnGround() false")
            self.isAirborne = 1

        return Task.cont

    def jumpPressed(self):
        """This function should be called from TwoDDrive when the jump key is pressed."""
        if self.lifter.isOnGround():
            if self.isAirborne == 0:
                if self.mayJump:
                    # The jump button is down and we're close enough to the ground to jump.
                    self.lifter.addVelocity(self.avatarControlJumpForce)
                    messenger.send("jumpStart")
                    self.isAirborne = 1
                    assert self.debugPrint("isAirborne 1 due to jump")
Esempio n. 6
0
    def __init__(self):
        self.loadDefaultConfig()
        self.loadLocalConfig()

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        # Set up some global objects
        self.globalClock = ClockObject.getGlobalClock()
        # We will manually manage the clock
        self.globalClock.setMode(ClockObject.MSlave)
        builtins.globalClock = self.globalClock

        self.vfs = VirtualFileSystem.getGlobalPtr()

        # For tasks that run every application frame
        self.taskMgr = TaskManagerGlobal.taskMgr
        builtins.taskMgr = self.taskMgr

        # For tasks that run every simulation tick
        self.simTaskMgr = Task.TaskManager()
        self.simTaskMgr.mgr = AsyncTaskManager("sim")
        builtins.simTaskmgr = self.simTaskMgr

        self.eventMgr = EventManagerGlobal.eventMgr
        builtins.eventMgr = self.eventMgr

        self.messenger = MessengerGlobal.messenger
        builtins.messenger = self.messenger

        self.loader = Loader(self)
        builtins.loader = self.loader

        builtins.base = self

        # What is the current frame number?
        self.frameCount = 0
        # Time at beginning of current frame
        self.frameTime = self.globalClock.getRealTime()
        # How long did the last frame take.
        self.deltaTime = 0

        #
        # Variables pertaining to simulation ticks.
        #

        self.prevRemainder = 0
        self.remainder = 0
        # What is the current overall simulation tick?
        self.tickCount = 0
        # How many ticks are we going to run this frame?
        self.totalTicksThisFrame = 0
        # How many ticks have we run so far this frame?
        self.currentTicksThisFrame = 0
        # What tick are we currently on this frame?
        self.currentFrameTick = 0
        # How many simulations ticks are we running per-second?
        self.ticksPerSec = 60
        self.intervalPerTick = 1.0 / self.ticksPerSec
Esempio n. 7
0
 def __init__(self, parent):
     DirectObject.DirectObject.__init__(self)
     self.parent = parent
     self.state = False
     self.model = None
     self.wheel = None
     self.snapshot = None
     self.snapshotFrame = None
     self.snapshotFrameBasic = None
     self.currentTime = 0
     self.lastUpdateTime = globalClock.getRealTime()
     self.locationLabel = None
     self.locationText = None
     self.hintLabel = None
     self.hintText = None
     self.adImage = None
     self.allowLiveFlatten = ConfigVariableBool('allow-live-flatten')
     self.title_art = []
     self.tempVolume = []
Esempio n. 8
0
    def __init__(self, eventQueue=None):
        """
        Create a C++ event queue and handler
        """
        # Make a notify category for this class (unless there already is one)
        if EventManager.notify is None:
            EventManager.notify = directNotify.newCategory("EventManager")

        self.eventQueue = eventQueue
        self.eventHandler = None

        self._wantPstats = ConfigVariableBool('pstats-eventmanager', False)
    def readerPollUntilEmpty(self, task):
        while self.readerPollOnce():
            pass

        if not metadata.IS_PRODUCTION:
            if ConfigVariableBool('simulated-latency', False).getValue():
                latency = random.uniform(
                    ConfigVariableDouble('simulated-latency-min',
                                         0.125).getValue(),
                    ConfigVariableDouble('simulated-latency-max',
                                         0.15).getValue())
                task.delayTime = latency
                return task.again

        return task.cont
Esempio n. 10
0
    def __init__(self, eventQueue = None, messenger = None, taskMgr = None):
        """
        Create a C++ event queue and handler
        """
        # Make a notify category for this class (unless there already is one)
        if EventManager.notify is None:
            EventManager.notify = directNotify.newCategory("EventManager")

        self.eventQueue = eventQueue
        self.eventHandler = None

        if not messenger:
            messenger = MessengerGlobal.messenger
        self.messenger = messenger

        if not taskMgr:
            taskMgr = TaskManagerGlobal.taskMgr
        self.taskMgr = taskMgr

        self._wantPstats = ConfigVariableBool('pstats-eventmanager', False)
Esempio n. 11
0
 def __init__(self):
     Hour = FrameProfiler.Hour
     # how long to wait between frame profiles
     frequent_profiles = ConfigVariableBool('frequent-frame-profiles',
                                            False)
     self._period = 2 * FrameProfiler.Minute
     if frequent_profiles:
         self._period = 1 * FrameProfiler.Minute
     # used to prevent profile from being taken exactly every 'period' seconds
     self._jitterMagnitude = self._period * .75
     # when to log output
     # each entry must be an integer multiple of all previous entries
     # as well as an integer multiple of the period
     self._logSchedule = [
         1 * FrameProfiler.Hour,
         4 * FrameProfiler.Hour,
         12 * FrameProfiler.Hour,
         1 * FrameProfiler.Day,
     ]  # day schedule proceeds as 1, 2, 4, 8 days, etc.
     if frequent_profiles:
         self._logSchedule = [
             1 * FrameProfiler.Minute,
             4 * FrameProfiler.Minute,
             12 * FrameProfiler.Minute,
             24 * FrameProfiler.Minute,
         ]
     for t in self._logSchedule:
         #assert isInteger(t)
         # make sure the period is evenly divisible into each element of the log schedule
         assert (t % self._period) == 0
     # make sure each element of the schedule is evenly divisible into each subsequent element
     for i in range(len(self._logSchedule)):
         e = self._logSchedule[i]
         for j in range(i, len(self._logSchedule)):
             assert (self._logSchedule[j] % e) == 0
     #assert isInteger(self._period)
     self._enableFC = FunctionCall(self._setEnabled,
                                   taskMgr.getProfileFramesSV())
     self._enableFC.pushCurrentState()
Esempio n. 12
0
    def networkToLocalTime(self,
                           networkTime,
                           now=None,
                           bits=16,
                           ticksPerSec=NetworkTimePrecision):
        """networkToLocalTime(self, int networkTime)

        Converts the indicated networkTime to the corresponding
        localTime value.  The time is assumed to be within +/- 5
        minutes of the current local time given in now, or
        getRealTime() if now is not specified.
        """
        if now is None:
            now = self.globalClock.getRealTime()

        # Are we in non-real-time mode (i.e. filming a movie)?  If you
        # set movie-network-time 1, then we'll circumvent this logic
        # and always return now.
        if self.globalClock.getMode() == ClockObject.MNonRealTime and \
           ConfigVariableBool('movie-network-time', False):
            return now

        # First, determine what network time we have for 'now'.
        ntime = int(math.floor(((now - self.delta) * ticksPerSec) + 0.5))

        # The signed difference between these is the number of ticks
        # by which the network time differs from 'now'.
        if bits == 16:
            diff = self.__signExtend(networkTime - ntime)
        else:
            # Assume the bits is either 16 or 32.  If it's 32, no need
            # to sign-extend.  32 bits gives us about 227 days of
            # continuous timestamp.

            diff = networkTime - ntime

        return now + float(diff) / ticksPerSec
Esempio n. 13
0
(and not just assert for it).

If you want to be a super keen software engineer then avoid using
:func:`verify()`.  If you want to be, or already are, a super keen software
engineer, but you don't always have the time to write proper error handling,
go ahead and use :func:`verify()` -- that's what it's for.

Please use assert (properly) and do proper error handling; and use
:func:`verify()` only when debugging (i.e. when it won't be checked-in) or
where it helps you resist using assert for error handling.
"""

from panda3d.core import ConfigVariableBool

# Set to true to load pdb on failure.
wantVerifyPdb = ConfigVariableBool('want-verify-pdb', False)


def verify(assertion):
    """
    verify() is intended to be used in place of assert where you
    wish to have the assertion checked, even in release (-O) code.
    """
    if not assertion:
        print("\n\nverify failed:")
        import sys
        print("    File \"%s\", line %d" % (
                sys._getframe(1).f_code.co_filename,
                sys._getframe(1).f_lineno))
        if wantVerifyPdb:
            import pdb
Esempio n. 14
0
class Avatar(ToonTalker.ToonTalker, Actor, AvatarShared):
    """
    Client side implementation of the base Avatar.

    An Avatar is an animatable character, playable or non-playable, that can be involved
    in combat. Also has the ability to chat, have a nametag, hitbox, and more.
    """

    RealShadows = ConfigVariableBool('want-real-shadows', False)
    AvatarMovedEpsilon = 0.05

    def __init__(self, mat=0):
        try:
            self.Avatar_initialized
            return
        except:
            self.Avatar_initialized = 1

        ToonTalker.ToonTalker.__init__(self)
        #BasePhysicsObject.__init__(self)
        AvatarShared.__init__(self)
        Actor.__init__(self, None, None, None, flattenable=0, setFinal=1)

        # All avatars should be ambient boosted to help them stand out more in BSP levels.
        self.setAmbientBoost()

        self.shapeGroup = CIGlobals.WallGroup | CIGlobals.CharacterGroup

        #self.getGeomNode().showThrough(CIGlobals.ShadowCameraBitmask)

        self.usedAnims = []

        self.moveAnimProperties = {}

        self.mat = mat
        self.chat = ''

        self.nametagNodePath = None
        self.__nameVisible = 1
        self.nametag = NametagGroup()
        self.nametag.setAvatar(self)
        font = CIGlobals.getToonFont()
        self.nametag.setFont(font)
        self.nametag.setChatFont(font)
        self.nametag3d = self.attachNewNode('nametag3d')
        self.nametag3d.setTag('cam', 'nametag')

        self.setTwoSided(False)

        self.forwardSpeed = 0.0
        self.rotateSpeed = 0.0
        self.strafeSpeed = 0.0
        self.currentSpeed = 0.0
        self.standWalkRunReverse = None
        self.currentMoveAction = None

        self.enableBlend()

        self.showNametagInMargins = True
        self.avatarType = None
        self.charName = None
        self.tag = None

        self.splashEffect = None
        self.splashSound = None

        self.shadow = None

        self.prevPos = Point3(0)
        self.wake = None
        self.lastWakeTime = 0.0

        self.thoughtInProg = False

        self.shadowFloorToggle = False
        self.avatarFloorToggle = False
        self.floorTask = taskMgr.add(self.__keepOnFloorTask,
                                     "Avatar.keepOnFloor",
                                     sort=30)

        self.ragdoll = None
        self.ragdollMode = False

        self.healthLabel = None
        self.healthLabelTrack = None
        self.dmgFadeIval = None

        self.forcedTorsoAnim = None
        self.lastForcedTorsoAnim = None

        self.activityTrack = None
        self.wasDoingActivity = False

        self.fadeTrack = None

        self.playedAnims = None

        self.chatSoundTable = {}

        return

    def doScaleUp(self):
        self.scaleInterval(2.0, (1, 1, 1), (0.01, 0.01, 0.01)).start()

    def recordUsedAnim(self, animName):
        if not animName in self.usedAnims:
            self.usedAnims.append(animName)

    def clearFadeTrack(self):
        if self.fadeTrack:
            self.fadeTrack.finish()
        self.fadeTrack = None

    def fadeOut(self, time=1.0):
        self.clearFadeTrack()
        self.fadeTrack = Sequence(
            Func(self.setTransparency, 1),
            LerpColorScaleInterval(self, time, (1, 1, 1, 0), (1, 1, 1, 1)),
            Func(self.hide))
        self.fadeTrack.start()

    def fadeIn(self, time=1.0):
        self.clearFadeTrack()
        self.fadeTrack = Sequence(
            Func(self.setTransparency, 1),
            LerpColorScaleInterval(self, time, (1, 1, 1, 1), (1, 1, 1, 0)),
            Func(self.setTransparency, 0))
        self.fadeTrack.start()

    def getAttackMgr(self):
        return base.cr.attackMgr

    def stopActivity(self):
        if self.activityTrack:
            self.activityTrack.finish()
        self.activityTrack = None
        self.doingActivity = False

    def setActivity(self, activity, timestamp):
        AvatarShared.setActivity(self, activity, timestamp)

        self.stopActivity()

        if activity == -1 or activity not in self.activities:
            return

        self.doingActivity = True
        ts = globalClockDelta.localElapsedTime(timestamp)
        act = self.activities[activity]
        loop = act.shouldLoop()
        self.activityTrack = act.doActivity()
        self.activityTrack.start()
        #if loop:
        #    self.activityTrack.loop()
        #else:
        #    self.activityTrack.start()

    def setForcedTorsoAnim(self, anim):
        self.forcedTorsoAnim = anim

    def hasForcedTorsoAnim(self):
        return self.forcedTorsoAnim is not None

    def getForcedTorsoAnim(self):
        return self.forcedTorsoAnim

    def clearForcedTorsoAnim(self):

        if not self.forcedTorsoAnim is None:
            # Let's switch our current torso and head animation to the
            # animation the legs are running.
            legs = self.getLowerBodySubpart()[0]
            legAnimation = self.getCurrentAnim(partName=legs)
            frame = self.getCurrentFrame(partName=legs, animName=legAnimation)

            def __anim(partName):
                self.stop(partName=partName)
                self.play(animName=legAnimation,
                          partName=partName,
                          fromFrame=frame)

            parts = self.getUpperBodySubpart()
            for part in parts:
                __anim(part)

        self.forcedTorsoAnim = None

    def setPlayRate(self, rate, animName, partName=None):
        if partName or not self.forcedTorsoAnim:
            Actor.setPlayRate(self, rate, animName, partName)
        else:
            parts = self.getLowerBodySubpart() + self.getUpperBodySubpart()
            for part in parts:
                Actor.setPlayRate(self, rate, animName, part)

    def play(self, animName, partName=None, fromFrame=None, toFrame=None):
        self.recordUsedAnim(animName)

        lowerHalfNames = self.getLowerBodySubpart()
        if self.forcedTorsoAnim is None or (not (partName in lowerHalfNames)):
            Actor.play(self,
                       animName,
                       partName=partName,
                       fromFrame=fromFrame,
                       toFrame=toFrame)
        else:
            # The torso and the head must stay in its current animation.
            # Let's only update the pants and the legs animation.
            for part in lowerHalfNames:
                Actor.play(self,
                           animName,
                           partName=part,
                           fromFrame=fromFrame,
                           toFrame=toFrame)

    def loop(self,
             animName,
             restart=1,
             partName=None,
             fromFrame=None,
             toFrame=None):
        self.recordUsedAnim(animName)

        lowerHalfNames = self.getLowerBodySubpart()
        if self.forcedTorsoAnim is None or (not (partName in lowerHalfNames)):
            return Actor.loop(self,
                              animName,
                              restart=restart,
                              partName=partName,
                              fromFrame=fromFrame,
                              toFrame=toFrame)
        else:
            # The torso and the head must stay in its current animation.
            # Let's only update the pants and the legs animation.
            for index, part in enumerate(lowerHalfNames):
                output = Actor.loop(self,
                                    animName,
                                    restart=restart,
                                    partName=part,
                                    fromFrame=fromFrame,
                                    toFrame=toFrame)

    def pingpong(self,
                 animName,
                 restart=1,
                 partName=None,
                 fromFrame=None,
                 toFrame=None):
        self.recordUsedAnim(animName)

        lowerHalfNames = self.getLowerBodySubpart()
        if self.forcedTorsoAnim is None or (not (partName in lowerHalfNames)):
            Actor.pingpong(self,
                           animName,
                           restart=restart,
                           partName=partName,
                           fromFrame=fromFrame,
                           toFrame=toFrame)
        else:
            # The torso and the head must stay in its current animation.
            # Let's only update the pants and the legs animation.
            for part in lowerHalfNames:
                Actor.pingpong(self,
                               animName,
                               restart=restart,
                               partName=part,
                               fromFrame=fromFrame,
                               toFrame=toFrame)

    def getMoveAction(self, forward, rotate, strafe):
        return 0

    def performAnim(self, anim, partName=None, animInfo=None):
        if not animInfo:
            self.loop(anim, partName=partName)
        else:
            extraArgs = animInfo.get('args', {})
            meth = animInfo.get('method', 'loop')
            if meth == 'loop':
                self.loop(anim, **extraArgs)
            elif meth == 'pingpong':
                self.pingpong(anim, **extraArgs)

    def resetMoveAnims(self, anim=None, anim2=None):
        self.resetAnimBlends()
        if self.forcedTorsoAnim is None:
            self.disableBlend()
            self.stop()
            if anim and anim2:
                self.enableBlend()
                self.performAnim(anim, None,
                                 self.moveAnimProperties.get(anim, None))
                self.performAnim(anim2, None,
                                 self.moveAnimProperties.get(anim2, None))
        else:
            parts = self.getLowerBodySubpart()
            for part in parts:
                self.disableBlend(partName=part)
                self.stop(partName=part)
                if anim and anim2:
                    self.enableBlend(partName=part)
                    self.performAnim(anim, part,
                                     self.moveAnimProperties.get(anim, None))
                    self.performAnim(anim2, part,
                                     self.moveAnimProperties.get(anim2, None))

    def resetAnimBlends(self):
        for animName in self.usedAnims:
            self.setControlEffect(animName, 0.0)
        self.usedAnims = []

    def setSpeed(self, forwardSpeed, rotateSpeed, strafeSpeed=0.0):
        if self.ragdollMode:
            return

        self.forwardSpeed = forwardSpeed
        self.rotateSpeed = rotateSpeed
        self.strafeSpeed = strafeSpeed

        action = None
        if self.standWalkRunReverse != None and not self.doingActivity:
            action = self.getMoveAction(forwardSpeed, rotateSpeed, strafeSpeed)
            anim, anim2, minSpeed, maxSpeed, rate, rate2 = self.standWalkRunReverse[
                action]
            if self.currentMoveAction != action or self.lastForcedTorsoAnim != self.forcedTorsoAnim or self.wasDoingActivity:
                self.playingAnim = anim
                self.lastForcedTorsoAnim = self.forcedTorsoAnim
                self.currentMoveAction = action
                self.resetMoveAnims(anim, anim2)

            speed = max(
                Vec3(forwardSpeed, strafeSpeed, rotateSpeed / 15.0).length(),
                minSpeed)
            self.currentSpeed = speed
            ratio = speed / maxSpeed
            ratioClamped = CIGlobals.clamp(ratio, 0, 1)
            self.setControlEffect(anim, 1 - ratioClamped)
            self.setControlEffect(anim2, ratioClamped)

            if ratio > 1:
                self.setPlayRate(rate * ratio, anim)
                self.setPlayRate(rate2 * ratio, anim2)
            else:
                self.setPlayRate(rate, anim)
                self.setPlayRate(rate2, anim2)

            self.wasDoingActivity = False
        elif self.doingActivity and not self.wasDoingActivity:
            self.wasDoingActivity = True
            self.resetMoveAnims()

        return action

    def getRightHandNode(self):
        return NodePath("rightHand")

    def getLeftHandNode(self):
        return NodePath("leftHand")

    def getHeadNode(self):
        return NodePath("head")

    def handleHitByToon(self, player, gagId, distance):
        pass

    def handleHitByEnemy(self, enemy, weaponId, distance):
        pass

    def getLowerBodySubpart(self):
        return ["legs"]

    def getUpperBodySubpart(self):
        return ["torso"]

    def taskName(self, name):
        return name + "-" + str(id(self))

    def uniqueName(self, name):
        return name + "-" + str(id(self))

    def setupHealthLabel(self):
        self.healthLabel = DirectLabel(text="",
                                       text_fg=CIGlobals.PositiveTextColor,
                                       scale=0.9,
                                       relief=None,
                                       text_decal=True,
                                       text_font=CIGlobals.getMickeyFont(),
                                       text_align=TextNode.ACenter)
        self.healthLabel.reparentTo(self)
        self.healthLabel.setBillboardPointEye()
        self.healthLabel.stash()
        self.healthLabel.setLightOff(1)
        self.healthLabel.hide(CIGlobals.ShadowCameraBitmask
                              | CIGlobals.ReflectionCameraBitmask)

    def showAndMoveHealthLabel(self, zoffset=0.5, stashWaitTime=1.0):
        self.unstashHpLabel()
        self.stopMovingHealthLabel()
        x = self.nametag3d.getX()
        y = self.nametag3d.getY()
        z = self.nametag3d.getZ()
        moveTrack = LerpPosInterval(self.healthLabel,
                                    duration=0.5,
                                    pos=(x, y, z + zoffset),
                                    startPos=(x, y, z - 2),
                                    blendType='easeOut')
        self.healthLabelTrack = Sequence(moveTrack, Wait(stashWaitTime),
                                         Func(self.stashHpLabel))
        self.healthLabelTrack.start()

    def stopMovingHealthLabel(self):
        if self.healthLabelTrack != None:
            self.healthLabelTrack.pause()
            self.healthLabelTrack = None

    def stashHpLabel(self):
        self.healthLabel.stash()

    def unstashHpLabel(self):
        self.healthLabel.unstash()

    def doDamageFade(self):
        # Stop the current fade interval if it exists.
        if self.dmgFadeIval:
            self.dmgFadeIval.finish()
            self.dmgFadeIval = None

        geomNode = self.getGeomNode()
        # Do a fade effect when we get hit so we are more aware that we were damaged.
        self.dmgFadeIval = Sequence(
            Func(geomNode.setTransparency, 1),
            LerpColorScaleInterval(geomNode,
                                   0.3, (1, 1, 1, 0.5), (1, 1, 1, 1),
                                   blendType='easeOut'),
            LerpColorScaleInterval(geomNode,
                                   0.3, (1, 1, 1, 1), (1, 1, 1, 0.5),
                                   blendType='easeIn'),
            Func(geomNode.setTransparency, 0))
        self.dmgFadeIval.start()

    def announceHealth(self, level, hp, extraId):
        if not self.healthLabel:
            return

        if hp > 0:
            prefix = "+"
        else:
            prefix = ""

        if extraId != -1:
            prefix = self.EXTRAS[extraId] + "\n" + prefix

        if level == 1:
            self.healthLabel["text_fg"] = CIGlobals.PositiveTextColor
            self.healthLabel['text'] = prefix + str(hp)
        else:
            textFg = CIGlobals.NegativeTextColor
            if level == 2:
                textFg = CIGlobals.OrangeTextColor
            elif level == 3:
                textFg = CIGlobals.YellowTextColor
            self.healthLabel["text_fg"] = textFg
            self.healthLabel['text'] = prefix + str(hp)

        self.showAndMoveHealthLabel(1.0 if extraId != -1 else 0.5)

    def doRagdollMode(self,
                      forceX=0,
                      forceY=0,
                      forceZ=0,
                      forcePosX=0,
                      forcePosY=0,
                      forcePosZ=0):
        if self.ragdollMode:
            return

        forceVec = Vec3(forceX, forceY, forceZ)
        forcePos = Vec3(forcePosX, forcePosY, forcePosZ)

        self.stop()
        self.disableRay()
        self.disableShadowRay()
        if self.shadow:
            self.shadow.hide()
        self.disableBodyCollisions()
        if self.ragdoll:
            self.ragdoll.mode = self.ragdoll.RMRagdoll
            self.ragdoll.setEnabled(True)
            self.ragdoll.attachActor()
            self.ragdoll.applyForce(forceVec, forcePos)

        self.ragdollMode = True

    def getSplash(self):
        if not self.splashEffect:
            self.splashEffect = Splash(render)
            self.splashSound = base.loadSfxOnNode(
                "phase_5.5/audio/sfx/AV_jump_in_water.ogg", self.splashEffect)

        return self.splashEffect

    def getWake(self):
        if not self.wake:
            self.wake = Wake(render, self)

        return self.wake

    def splash(self, x, y, z):
        spl = self.getSplash()
        spl.setPos(x, y, z)
        spl.setScale(2)
        spl.play()

        self.splashSound.play()

    def isLocalAvatar(self):
        if not hasattr(base, 'localAvatar'):
            return False
        return self == base.localAvatar

    def initializeRay(self, *args, **kwargs):
        pass

    def enableShadowRay(self):
        self.shadowFloorToggle = True

    def disableShadowRay(self):
        self.shadowFloorToggle = False

    def enableRay(self):
        self.avatarFloorToggle = True

    def disableRay(self):
        self.avatarFloorToggle = False

    def updateFloorHeight(self, z):
        if self.avatarFloorToggle:
            self.setZ(render, z)
        if self.shadowFloorToggle and self.shadow:
            self.shadow.setZ(render, z)

    def __keepOnFloorTask(self, task):
        # First, check if we are above a ground.
        # If so, go onto that.

        if self.isEmpty():
            return task.done

        # Create water ripples
        time = globalClock.getFrameTime()
        delta = time - self.lastWakeTime
        dt = globalClock.getDt()
        pos = self.getPos(render)
        posDelta = (pos - self.prevPos).lengthSquared()
        moveMag = posDelta / dt
        if moveMag > 5.0 and delta > 0.1:
            if hasattr(base, 'waterReflectionMgr'):
                result = base.waterReflectionMgr.isTouchingAnyWater(
                    pos, pos + (0, 0, self.getHeight()))
                if result[0]:
                    self.getWake().createRipple(result[1],
                                                rate=1,
                                                startFrame=4)
                    self.lastWakeTime = time
        self.prevPos = pos

        # Position is updated from server, don't need to move avatar on client
        return task.cont

        if (not self.avatarFloorToggle and not self.shadowFloorToggle
                or moveMag < self.AvatarMovedEpsilon):

            # Avoid unnecessary ray casting.
            return task.cont

        pFrom = self.getPos(render) + (0, 0, 0.1)

        z = None

        pTo = pFrom - (0, 0, 2000)
        aboveResult = base.physicsWorld.rayTestAll(
            pFrom, pTo, CIGlobals.WallGroup | CIGlobals.FloorGroup
            | CIGlobals.StreetVisGroup)
        aboveGround = False
        if aboveResult.hasHits():
            sortedHits = sorted(aboveResult.getHits(),
                                key=lambda hit:
                                (pFrom - hit.getHitPos()).lengthSquared())
            for i in range(len(sortedHits)):
                hit = sortedHits[i]
                node = hit.getNode()
                np = NodePath(node)
                if self.isAncestorOf(np):
                    continue
                z = hit.getHitPos().getZ()
                break

        if z is not None:
            self.updateFloorHeight(z)
            return task.cont

        # We're not above a ground, check above?
        pTo = pFrom + (0, 0, 2000)
        belowResult = base.physicsWorld.rayTestAll(
            pFrom, pTo, CIGlobals.WallGroup | CIGlobals.FloorGroup
            | CIGlobals.StreetVisGroup)
        if belowResult.hasHits():
            sortedHits = sorted(belowResult.getHits(),
                                key=lambda hit:
                                (pFrom - hit.getHitPos()).lengthSquared())
            for i in range(len(sortedHits)):
                hit = sortedHits[i]
                node = hit.getNode()
                np = NodePath(node)
                if self.isAncestorOf(np):
                    continue
                z = hit.getHitPos().getZ()
                break

        if z is not None:
            self.updateFloorHeight(z)

        return task.cont

    def setupPhysics(self, radius=None, height=None):
        if not radius:
            radius = self.getWidth()
        if not height:
            height = self.getHeight()
        self.notify.debug("setupPhysics(r{0}, h{1}) hitboxData: {2}".format(
            radius, height, self.hitboxData))

        # When the height is passed into BulletCapsuleShape, it's
        # talking about the height only of the cylinder part.
        # But what we want is the height of the entire capsule.
        #height -= (radius * 2)
        # The middle of the capsule is the origin by default. Push the capsule shape up
        # so the very bottom of the capsule is the origin.
        zOfs = (height / 2.0) + radius

        capsule = BulletCapsuleShape(radius, height)
        bodyNode = BulletRigidBodyNode('avatarBodyNode')
        bodyNode.addShape(capsule, TransformState.makePos(Point3(0, 0, zOfs)))
        bodyNode.setKinematic(True)
        bodyNode.setPythonTag("avatar", self)

        BasePhysicsObject.setupPhysics(self, bodyNode, True)

        self.stopWaterCheck()

    def isDistributed(self):
        return hasattr(self, 'doId')

    def chatStompComplete(self, text):
        chatType = CHAT_LONG

        if "ooo" in text.lower():
            chatType = CHAT_HOWL
        elif "!" in text.lower():
            chatType = CHAT_EXCLAIM
        elif "?" in text.lower():
            chatType = CHAT_QUESTION
        elif len(text) <= 9:
            chatType = CHAT_SHORT
        elif 10 <= len(text) <= 19:
            chatType = CHAT_MEDIUM
        elif len(text) >= 20:
            chatType = CHAT_LONG

        snd = self.chatSoundTable.get(chatType, None)
        if isinstance(snd, list):
            snd = random.choice(snd)

        if snd:
            self.playSound(snd)

    def deleteNameTag(self):
        self.deleteNametag3d()

    def disableBodyCollisions(self):
        self.cleanupPhysics()

    def loadAvatar(self):
        self.setupHealthLabel()
        self.setBlend(
            frameBlend=base.config.GetBool("interpolate-frames", False))
        base.avatars.append(self)

    def disable(self):
        try:
            self.Avatar_disabled
        except:
            self.Avatar_disabled = 1
            if self.ragdoll:
                self.ragdoll.cleanup()
            self.ragdoll = None
            self.clearFadeTrack()
            if self in base.avatars:
                base.avatars.remove(self)
            if self.dmgFadeIval:
                self.dmgFadeIval.finish()
            self.stopActivity()
            self.dmgFadeIval = None
            self.stopMovingHealthLabel()
            if self.healthLabel:
                self.healthLabel.removeNode()
            self.healthLabel = None
            self.healthLabelTrack = None
            if self.floorTask:
                self.floorTask.remove()
            self.floorTask = None
            self.disableRay()
            self.deleteNametag3d()
            self.nametag.destroy()
            del self.nametag
            self.nametag3d.removeNode()
            self.nametag3d = None
            self.deleteShadow()
            self.removeLoopTask()
            self.mat = None
            self.tag = None
            self.chat = None
            self.avatarType = None
            self.charName = None
            self.nameTag = None
            self.cleanupPhysics()
            self.moveAnimProperties = None
            self.chatSoundTable = None

            self.lastWakeTime = None
            self.prevPos = None

            if self.wake:
                self.wake.destroy()
                self.wake = None

            if self.splashEffect:
                self.splashEffect.destroy()
                self.splashEffect = None

            self.splashSound = None

            self.avatarFloorToggle = None
            self.shadowFloorToggle = None

            Actor.cleanup(self)

    def delete(self):
        try:
            self.Avatar_deleted
        except:
            self.Avatar_deleted = 1
            self.removeLoopTask()
            AvatarShared.delete(self)
            Actor.delete(self)

    def getNameTag(self):
        return self.nametag3d

    def getNametagJoints(self):
        return []

    def setChat(self, chatString=None):
        print("setChat on", self.__class__.__name__)
        self.nametag.setChatType(NametagGlobals.CHAT)
        shouldClear = self.autoClearChat
        if self.isThought(chatString):
            self.thoughtInProg = True
            chatString = self.removeThoughtPrefix(chatString)
            self.nametag.setChatBalloonType(NametagGlobals.THOUGHT_BALLOON)
            shouldClear = False
        else:
            self.thoughtInProg = False
            self.nametag.setChatBalloonType(NametagGlobals.CHAT_BALLOON)
        self.nametag.setChatText(chatString, timeout=shouldClear)

    def setName(self, nameString=None, charName=None, createNow=0):
        if not nameString:
            return
        AvatarShared.setName(self, nameString)
        if charName:
            self.charName = charName
        if createNow:
            self.setupNameTag()

    def getName(self):
        return AvatarShared.getName(self)

    def setupNameTag(self, tempName=None):
        if not self._name and not tempName:
            return
        if tempName:
            name = tempName
        else:
            name = self._name
        offset = 0.0
        z = 0.0
        if self.avatarType:
            if self.avatarType in [CIGlobals.Suit]:
                offset = 1.0
                z = self.getHeight()
            elif self.avatarType == CIGlobals.Toon:
                offset = 0.5

        self.deleteNametag3d()
        self.initializeNametag3d()

        if self.avatarType == CIGlobals.Toon:
            self.nametag3d.setZ(self.getHeight() + offset)
        elif self.avatarType == CIGlobals.Suit or self.avatarType == CIGlobals.CChar:
            self.nametag3d.setZ(z + offset)

        if self.avatarType == CIGlobals.Suit:
            self.nametag.setFont(CIGlobals.getSuitFont())
            self.nametag.setChatFont(CIGlobals.getSuitFont())
            self.nametag.setNametagColor(
                NametagGlobals.NametagColors[NametagGlobals.CCSuit])
            self.nametag.setActive(0)
        else:
            self.nametag.setFont(CIGlobals.getToonFont())
            self.nametag.setChatFont(CIGlobals.getToonFont())
            self.nametag.setNametagColor(
                NametagGlobals.NametagColors[NametagGlobals.CCOtherPlayer])
        self.nametag.setText(name)
        if self.showNametagInMargins:
            self.nametag.manage(base.marginManager)
        self.nametag.updateAll()

    def setAvatarScale(self, scale):
        self.getGeomNode().setScale(scale)

    def getShadow(self):
        if hasattr(self, 'shadow'):
            if self.shadow:
                return self.shadow
        return None

    def initShadow(self):
        if metadata.USE_REAL_SHADOWS:
            self.shadow = None
        else:
            self.shadow = loader.loadModel(
                "phase_3/models/props/drop_shadow.bam")
            self.shadow.setScale(CIGlobals.ShadowScales[self.avatarType])
            self.shadow.flattenMedium()
            self.shadow.setBillboardAxis(4)
            self.shadow.setColor(0, 0, 0, 0.5, 1)
            if self.avatarType == CIGlobals.Toon:
                self.shadow.reparentTo(
                    self.getPart('legs').find('**/joint_shadow'))
            elif self.avatarType == CIGlobals.Suit:
                self.shadow.reparentTo(self)
            else:
                self.shadow.reparentTo(self)

        self.enableShadowRay()

    def deleteShadow(self):
        if hasattr(self, 'shadow'):
            if self.shadow:
                self.shadow.removeNode()
                self.shadow = None

    def loopFromFrameToZero(self,
                            animName,
                            restart=1,
                            partName=None,
                            fromFrame=None):
        # Loop an animation from a frame, restarting at 0.
        # This is only used in Make A Toon, but could be used in other things,
        # that are not distributed.
        dur = self.getDuration(animName, fromFrame=fromFrame)
        self.play(animName, partName=partName, fromFrame=fromFrame)
        taskName = self.uniqueName('loopTask')
        taskMgr.doMethodLater(dur,
                              self.loopTask,
                              taskName,
                              extraArgs=[animName, restart, partName],
                              appendTask=True)

    def removeLoopTask(self):
        taskMgr.remove(self.uniqueName('loopTask'))

    def removePart(self, partName, lodName="lodRoot"):
        self.removeLoopTask()
        part = Actor.getPart(self, partName, lodName)

        if part:
            Actor.removePart(self, partName, lodName=lodName)

    def loopTask(self, animName, restart, partName, task):
        self.loop(animName, restart, partName)
        return task.done

    def getGhost(self):
        return 0

    def hideName(self):
        nametag3d = self.nametag.getNametag3d()
        nametag3d.hideNametag()
        nametag3d.showChat()
        nametag3d.showThought()
        nametag3d.update()

    def showName(self):
        if self.__nameVisible and not self.getGhost():
            nametag3d = self.nametag.getNametag3d()
            nametag3d.showNametag()
            nametag3d.showChat()
            nametag3d.showThought()
            nametag3d.update()

    def hideNametag2d(self):
        nametag2d = self.nametag.getNametag2d()
        nametag2d.hideNametag()
        nametag2d.hideChat()
        nametag2d.update()

    def showNametag2d(self):
        nametag2d = self.nametag.getNametag2d()
        if not self.getGhost():
            nametag2d.showNametag()
            nametag2d.showChat()
        else:
            nametag2d.hideNametag()
            nametag2d.hideChat()
        nametag2d.update()

    def hideNametag3d(self):
        nametag3d = self.nametag.getNametag3d()
        nametag3d.hideNametag()
        nametag3d.hideChat()
        nametag3d.hideThought()
        nametag3d.update()

    def showNametag3d(self):
        nametag3d = self.nametag.getNametag3d()
        if self.__nameVisible and (not self.getGhost()):
            nametag3d.showNametag()
            nametag3d.showChat()
            nametag3d.showThought()
        else:
            nametag3d.hideNametag()
            nametag3d.hideChat()
            nametag3d.hideThought()
        nametag3d.update()

    def setPickable(self, flag):
        self.nametag.setActive(flag)

    def clickedNametag(self):
        if self.nametag.getActive():
            messenger.send('clickedNametag', [self])

    def initializeNametag3d(self):
        self.deleteNametag3d()
        nametagNode = self.nametag.getNametag3d()
        self.nametagNodePath = self.nametag3d.attachNewNode(nametagNode)

        for cJoint in self.getNametagJoints():
            cJoint.clearNetTransforms()
            cJoint.addNetTransform(nametagNode)

    def deleteNametag3d(self):
        if self.nametagNodePath:
            self.nametagNodePath.removeNode()
            self.nametagNodePath = None

    def getNameVisible(self):
        return self.__nameVisible

    def setNameVisible(self, visible):
        self.__nameVisible = visible
        if visible:
            self.showName()
        else:
            self.hideName()
Esempio n. 15
0
class graphica :
    elements = None #drawing elements
    map_zoom = 1
    map_pos = (0, 0)
    width = 0
    height = 0
    
    title_update_time = 0.5
    
    p3d = None #Panda Engine
    flat = None #floor of the world
    screen = None #screen surface
    
    def __init__(self, params, pipe, dir):
        self.game_directory = dir
        self.game_pipe = pipe
        self.gs_window = ConfigVariableString('win-size')
        self.gs_window.setValue(str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        
        self.gs_multi = ConfigVariableBool('framebuffer-multisample')
        self.gs_multi.setValue(params.get('multisample', 1))
        
        self.gs_sync = ConfigVariableBool('sync-video', str(params.get('sync', 1)))
        self.gs_sync.setValue(params.get('sync', 1))

        loadPrcFileData('', 'win-size '+ str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        loadPrcFileData('', 'win-fixed-size 1')
        loadPrcFileData('', 'text-default-font data/HanZi.ttf')
        loadPrcFileData('', 'multisamples ' + str(params.get('samples', 0)))

        #loadPrcFileData('', 'fullscreen 1')
        #loadPrcFileData('', 'textures-power-2 pad')
        #loadPrcFileData('', 'notify-level spam')
        #loadPrcFileData('', 'default-directnotify-level spam')
        #loadPrcFileData('', 'notify-output I:\\Users\\User\\My Documents\\Aptana Studio 3 Workspace\\sg\\out2.txt')
        #nout = MultiplexStream()
        #Notify.ptr().setOstreamPtr(nout, 0)
        #nout.addFile(Filename("out.txt"))

        '''for i in xrange(ConfigVariableManager.getGlobalPtr().getNumVariables()):
            if ConfigVariableManager.getGlobalPtr().isVariableUsed(i) :
                name = ConfigVariableManager.getGlobalPtr().getVariableName(i)
                v = ConfigVariable(name)
        '''

        self.p3d = ShowBase.ShowBase()
        self.p3d.buttonThrowers[0].node().setButtonDownEvent('buttonDown') 
        self.p3d.buttonThrowers[0].node().setButtonRepeatEvent('buttonRep')
        self.p3d.buttonThrowers[0].node().setButtonUpEvent('buttonUp')
        self.p3d.accept('buttonDown', self.keyboard, [0,])
        self.p3d.accept('buttonRep', self.keyboard, [2,])
        self.p3d.accept('buttonUp', self.keyboard, [1,])

        self.p3d.disableMouse()       #Disable default mouse-based camera control

        self.screen = render2d.attachNewNode("Screen Coord Node")
        self.screen.setBin("fixed", 100)
        self.flat = render.attachNewNode("2d Objects in 3d world")
        self.flat.setBin('background', 0)
        self.flat.setDepthTest(False)
        self.flat.setDepthWrite(False)
        
        render.setAntialias(AntialiasAttrib.MAuto)
        
        self.props = WindowProperties(self.p3d.win.getProperties())

        #Screen size
        self.width = params['width']
        self.height = params['height']
        self.aratio = float(self.width)/self.height #aspect ratio
        self.p3d.camera.setZ(1000)
        self.p3d.camera.lookAt(0,0,0)
        self.p3d.camLens.setFov(80)
        #self.props.setSize(size[0],size[1])

        self.screen.setScale(2.0/self.width,1,2.0/self.height)
        
        self.dt = 0.0
        self.fps = 0
        
        self.title_last_update_time = 0
        
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
        
        self.elements = {}
        
        #self.MModel = self.create_model_xt((0,0,0), 'models\\chinesegfx_city_1_1.x', 'models\\houses_chinesegfx.tga', (3,3))[1]
        #self.MModel.reparentTo(hidden)
        #sys.stdout.flush()
        #self.p3d.taskMgr.run()
        #self.myShader = Shader.load(Shader.SLGLSL, "modules\\myvertexshader.glsl", "modules\\myfragmentshader.glsl")
        
        #self.plane2.setShader(self.myShader)

        self.mouse_pos = (0, 0)
        self.mouse_on_map_pos = (0, 0)
        self.p3d.accept('wheel_up',self.zoom_in)
        self.p3d.accept('wheel_down',self.zoom_out)
        self.p3d.accept('mouse1',self.mouse_click_left)
        self.p3d.accept('mouse3',self.mouse_click_right)
        
        self.parents = {}
        
        self.gui_surface = aspect2d.attachNewNode("GUI Node")
        self.gui_surface.setScale(2.0/self.height,1,2.0/self.height)
        self.gui_surface.setBin("fixed", 50)
        
        self.map_node = self.add_node('map_node', 'background', 0, self.flat)
        self.paths_node = self.add_node('paths_node', 'background', 3, self.flat)
        self.paths_all_node = self.add_node('paths_all_node', 'background', 3, self.flat)
        self.map_mode_node = self.add_node('map_mode_node', 'background', 1, self.map_node)
        self.selecties_node = self.add_node('selecties_node', 'background', 2, self.map_node)

        self.parents['render'] = render
        self.parents['gui_surface'] = self.gui_surface
        
        self.elements['city_map_model'] = self.create_model_xt(fname = 'models\\chinesegfx_city_1_1.x', texname = 'models\\houses_chinesegfx.tga', size = (3, 3), name = 'city_map_model')
        
        self.minimap = Minimap(self.width, self.height, self)
    
    def add_node(self, name, mode1, mode2, parent = None):
        node = None
        if parent == None :
            node = render.attachNewNode(name)
        else :
            node = parent.attachNewNode(name)
        if (mode1 <> None) and (mode2 <> None ): node.setBin(mode1, mode2)
        self.parents[name] = node
        self.elements[name] = node
        return node
        
    def get_parent(self, p):
        if p in self.parents :
            return self.parents[p]
        elif p in self.elements :
            return self.elements[p]
        else :
            return render
    
    def gr_loop(self):
        self.mouse_control()
        self.frame()
            
    def Start(self):
        print 'Starting graphic loop'
        sys.stdout.flush()
        while(1):
            #считывает отправленные данные
            start_time = globalClock.getRealTime()

            try:
                while self.game_pipe.poll(False) and ((globalClock.getRealTime() - start_time) < 0.5) :
                    m = self.game_pipe.recv()
                    
                    
                    try:
                        if m[0] == 'setitem' :
                            if m[1]['key'] == 'pos' : self.elements[m[1]['name']].setPos(m[1]['value'])
                            elif m[1]['key'] == 'image' : 
                                self.elements[m[1]['name']]['image'] = textures.get(m[1]['value'], None)
                            elif m[1]['key'] == 'scale' : self.elements[m[1]['name']].setScale(m[1]['value'])
                            else : self.elements[m[1]['name']][m[1]['key']] = m[1]['value']
                        
                        elif m[0] == 'set_map_pos' : self.set_map_pos(m[1][0], m[1][1])
                        
                        elif m[0] == 'set_map_zoom' : self.set_map_zoom(m[1])
    
                        elif m[0] == 'draw_image2d' : self.draw_image2d(**m[1])
                        
                        elif m[0] == 'draw_image' : self.draw_image(**m[1])
                        
                        elif m[0] == 'draw_line' : 
                            self.draw_line(**m[1])
                            #continue
                        
                        elif m[0] == 'draw_line2d' : 
                            self.draw_line2d(**m[1])
                        
                        elif m[0] == 'draw_circle' : self.draw_circle(**m[1])
                        
                        elif m[0] == 'draw_triangles' : self.draw_triangles(**m[1])
                        
                        elif m[0] == 'delete_el_mask' : self.delete_el_mask(m[1])
                        
                        elif m[0] == 'delete_el' : self.delete_el(m[1])
                        
                        elif m[0] == 'gui_hide' :
                            self.elements[m[1]].hide()
                            
                        elif m[0] == 'gui_show' :
                            self.elements[m[1]].show()
                            
                        elif m[0] == 'gui_removeAndDestroyAllItems' :
                            self.elements[m[1]].removeAndDestroyAllItems()
                            
                        elif m[0] == 'reparentTo' :
                            self.elements[m[1]].reparentTo( self.elements[m[2]] )
                            
                        elif m[0] == 'setTexture' :
                            self.elements[m[1]].setTexture(textures[m[2]])
                            
                        elif m[0] == 'setPos' :
                            self.elements[m[1]].setPos(m[2][0], m[2][1], m[2][2])
                            
                        elif m[0] == 'setHpr' :
                            self.elements[m[1]].setHpr(m[2][0], m[2][1], m[2][2])
                            
                        elif m[0] == 'instanceTo' :
                            self.elements[m[2]] = render.attachNewNode('Placeholder')
                            self.elements[m[1]].instanceTo(self.elements[m[2]])
                        
                            
                        elif m[0] == 'resetFrameSize' :
                            self.elements[m[1]].resetFrameSize()
                            
                        elif m[0] == 'setTransparency' :
                            self.elements[m[1]].setTransparency(TransparencyAttrib.MAlpha)
                            
                        elif m[0] == 'RemoveGuiElement' :
                            try:
                                self.elements[m[1]].destroy()
                            except:
                                self.elements[m[1]].removeNode()
                                
                        elif m[0] == 'removeNode' :
                            self.elements[m[1]].removeNode()
                            
                        elif m[0] == 'removeAllChildren' :
                            self.elements[m[1]].node().removeAllChildren()
                                
                        elif m[0] == 'gui_addItem' :
                            self.elements[m[1]].addItem(self.elements[m[2]])
                            
                        
                        elif m[0] == 'DirectLabel' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent(params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectLabel(**params)
                        
                        elif m[0] == 'DirectButton' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent(params.get('parent', 'render') )
                            params['command'] = self.GUI_pressed
                            params['extraArgs'] = (m[2]['name'],)
                            self.elements[m[2]['name']] = DirectButton(**params)
                        
                        elif m[0] == 'DirectFrame' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectFrame(**params)
                            
                        
                        elif m[0] == 'DirectScrolledList' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectScrolledList(**params)
                            
                        elif m[0] == 'DirectCheckButton' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectCheckButton(**params)
                            
                        elif m[0] == 'DirectWaitBar' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectWaitBar(**params)
                            
                        elif m[0] == 'create_actor_egg' :
                            self.create_actor_egg(**m[1])
                            
                        elif m[0] == 'anim_loop' :
                            if len(m) == 3 : 
                                m = list(m)
                                m.append({})
                            self.elements[m[1]].loop(m[2], **m[3])
                            
                            
                        elif m[0] == 'image_data_new' :
                            t = PNMImage()
                            #print 'RECV', m[2]
                            sys.stdout.flush()
                            if t.read(StringStream(m[2])) :
                                pass
                            else :
                                raise ValueError()
                            sys.stdout.flush()
                            tex = Texture()
                            tex.load(t)
                            textures[m[1]] = tex 
                            
                        elif m[0] == 'create_minimap' :
                            im = PNMImage()
                            self.elements['phyz'].getTexture().store(im)
                            self.minimap.create_minimap(im, m[1], m[2])
                            self.draw_image2d(pos = (self.width/2 - 200, -self.height/2), texname = 'minimap_tex', name = 'minimap_image', parent = 'gui_surface' )
                            
                        
                        else :
                            print 'Unknown command:', m
                            sys.stdout.flush()
                        #print m
                        #sys.stdout.flush()
                        
                        
                    except:
                        print m
                        print 'error1', sys.exc_info()
                        sys.stdout.flush()
                
            except:
                print 'error2', sys.exc_info()
                sys.stdout.flush()    
                
            try:
                self.gr_loop()
            except Exception:
                print 'error3', sys.exc_info() 
                sys.stdout.flush()  
            
            try:
                pass
                #if not(self.game_queue.full()):
                #    self.game_queue.put(('mouse_pos', self.mouse_pos))
                #    self.game_queue.put(('mouse_on_map_pos', self.mouse_on_map_pos))
                #else :
                #    print 'game full'
                #    sys.stdout.flush()
                    
            except:
                print 'error4', sys.exc_info()
                sys.stdout.flush()   
                

            sys.stdout.flush()
            #time.sleep(0.01)

    def GUI_pressed(self, name):
        self.game_pipe.send(('gui_pressed',name))
    
    def mouse_control(self):
        if self.p3d.mouseWatcherNode.hasMouse():
            mp = (self.p3d.mouseWatcherNode.getMouse()[0], 0, self.p3d.mouseWatcherNode.getMouse()[1])
            self.mouse_pos[0] =  self.screen.getRelativePoint(render2d, mp)[0]
            self.mouse_pos[1] = self.screen.getRelativePoint(render2d, mp)[2]

            self.ttt = globalClock.getRealTime()
            mpos = self.p3d.mouseWatcherNode.getMouse()
            tmp = self.scr_to_map(mpos)
            self.mouse_on_map_pos[0] = tmp[0]
            self.mouse_on_map_pos[1] = tmp[1]
            X_ = self.p3d.camera.getX()
            Y_ = self.p3d.camera.getY()
            C = 0.5*self.dt
            if self.mouse_pos[0] < self.width * -0.47 :
                X_ -= self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            if self.mouse_pos[0] > self.width * 0.47 :  
                X_ += self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            if self.mouse_pos[1] < self.height * -0.47 :  
                Y_ -= self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            if self.mouse_pos[1] > self.height * 0.47 : 
                Y_ += self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            self.p3d.camera.setX( X_ )
            self.p3d.camera.setY( Y_ )
    
    def mouse_click_left(self):
        self.game_pipe.send(('mouse_click_left',))
    
    def mouse_click_right(self):
        self.game_pipe.send(('mouse_click_right',))
    
    def frame(self):
        self.p3d.taskMgr.step()
        self.dt = globalClock.getDt()
        
        if globalClock.getRealTime() - self.title_last_update_time > self.title_update_time :
            self.props = WindowProperties(self.p3d.win.getProperties())
            self.title_last_update_time = globalClock.getRealTime()
            self.fps = globalClock.getAverageFrameRate()
            title = str(self.fps) + str(self.mouse_pos[:]) + str(self.mouse_on_map_pos[:])
            self.props.setTitle(title)
            self.p3d.win.requestProperties(self.props)

    def draw_line(self, **kwargs):
        ps = kwargs.get('points',[])
        name = ''
        if 'name' in kwargs.keys() :
            name = kwargs['name']
            if self.check_name(name) :
                #print 'draw_line name duplicated', name
                return None
        else :
            name = self.generate_name()
            
        ls = LineSegs()
        if 'width' in kwargs.keys() : ls.setThickness( kwargs['width'] ) 
        if 'color' in kwargs.keys() : ls.setColor( (kwargs['color'][0], kwargs['color'][1], kwargs['color'][2], kwargs['color'][3]) )
        
        for i in ps :
            ls.drawTo(i[0], i[1], i[2])
        node = ls.create()
        np = NodePath(node)
        
        if 'parent' in kwargs.keys() and kwargs['parent'] <> None :
            self.get_parent(kwargs['parent']).attachNewNode(np.node())
        else :
            render.attachNewNode(np.node())
            
        
        self.elements[ name ] = np
        
        return name, np

    def draw_line2d(self, **kwargs):
        ps = None
        if 'points' in kwargs.keys():
            ps = kwargs['points']
        else :
            return None
        
        name = ''
        if 'name' in kwargs.keys() :
            name = kwargs['name']
            if self.check_name(name) :
                #print 'draw_line name duplicated', name
                return None
        else :
            name = self.generate_name()
            
        ls = LineSegs()
        if 'width' in kwargs.keys() : ls.setThickness( kwargs['width'] ) 
        if 'color' in kwargs.keys() : ls.setColor( Vec4(kwargs['color'][0], kwargs['color'][1], kwargs['color'][2], kwargs['color'][3]) )
        
        for i in ps :
            ls.drawTo(i[0], 0, i[1])
        node = ls.create()
        np = NodePath(node)

        if 'parent' in kwargs.keys() and kwargs['parent'] <> None :
            self.get_parent(kwargs['parent']).attachNewNode(np.node())
        else :
            self.screen.attachNewNode(np.node())

        self.elements[ name ] = np
        
        return name, np
    
    def draw_circle(self, **kw):#x, color, r, width, name, prec = 10, parent = None, hpr = None):
        x = kw.get('pos',(0,0,0))
        color = kw.get('color',(0,0,0,255))
        r = kw.get('radius',5)
        width = kw.get('width',1)
        prec = kw.get('prec', 10)
        parent = self.get_parent(kw.get('parent', None))
        hpr = kw.get('hpr', None)
        name = kw.get('name', self.generate_name())
        if self.check_name(name) :
                #print 'draw_circle name duplicated', name
                return None
        ls = LineSegs()
        ls.setThickness( width ) 
        ls.setColor( Vec4(float(color[0])/256,float(color[1])/256,float(color[2])/256,float(color[3])/256) )
        
        for i in xrange(prec) :
            angle = math.pi*i*2/prec
            ls.drawTo(x[0] + math.sin(angle) * r, x[1] + math.cos(angle) * r,0)
        
        ls.drawTo(x[0] + math.sin(math.pi*i*2/1) * r, x[1] + math.cos(math.pi*i*2/1) * r, 0)
        
        node = ls.create()
        np = NodePath(node)
        if color[3] <> 255 : np.setTransparency(TransparencyAttrib.MAlpha)
        if hpr <> None : np.setHpr(hpr[0],hpr[1],hpr[2])
        
        if parent == None :
            self.flat.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        
        self.elements[name] = np
    
    def draw_circle2d(self, x, color, r, width, name, prec = 10, parent = None):
        ls = LineSegs()
        ls.setThickness( width ) 
        ls.setColor( Vec4(float(color[0])/256,float(color[1])/256,float(color[2])/256,float(color[3])/256) )
        for i in xrange(prec) :
            angle = math.pi*i*2/prec
            ls.drawTo(x[0] + math.sin(angle) * r, 0, x[1] + math.cos(angle) * r)
        
        ls.drawTo(x[0] + math.sin(math.pi*i*2/1) * r, 0, x[1] + math.cos(math.pi*i*2/1) * r)
        
        node = ls.create()
        np = NodePath(node)
        
        if parent == None :
            self.screen.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        
        self.elements[name] = np

    def draw_text(self,msg,x,rgba,size,font = 'HanZi.ttf', surface = None):
        pass
    
    def draw_image(self,pos = (0,0,0), fname = '', name = None, scale = (1,1), size = None, parent = None, image = None, **kw):
        if name == None :
            name = self.generate_name()
            
        
        tex = Texture()
        texname = kw.get('texname', None)
        if texname <> None :
            if texname in textures.keys() :
                tex.load(textures[texname])
            else :
                tex = loader.loadTexture(texname)
        else : return None, None

        xframe = tex.getXSize()
        if tex.getOrigFileXSize() <> 0 : xframe = tex.getOrigFileXSize()

        yframe = tex.getYSize()
        if tex.getOrigFileYSize() <> 0 : yframe = tex.getOrigFileYSize()
        
        if size <> None :
            scale = (float(scale[0]) * size[0]/tex.getOrigFileXSize(), float(scale[1]) * size[1]/tex.getOrigFileYSize() )
        cm = CardMaker('card')
        cm.setFrame(0,xframe*scale[0],0,yframe*scale[1])
        
        card = None
        if parent == None :
            card = render.attachNewNode(cm.generate())
        else :
            card = self.get_parent(parent).attachNewNode(cm.generate())
        
        card.setTexture(tex)
        card.setPos(pos[0],pos[1],pos[2])
        card.setHpr(0,-90,0)

        self.elements[name] = card
        
        return name, card 
    
    def draw_polygon(self,ps,color,name):
        color = ( float(color[0])/255, float(color[1])/255, float(color[2])/255, float(color[3])/255)
        
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        #cwriter = GeomVertexWriter(vdata, 'color')
        
        trig = Triangulator()
        
        for i in ps :
            vi = trig.addVertex(i[0], i[1])
            vwriter.addData3f(i[0], i[2], i[1])
            #cwriter.addData4f(color[0], color[1], color[2], color[3])
            trig.addPolygonVertex(vi)

        trig.triangulate()
        
        prim = GeomTriangles(Geom.UHStatic)
        
        for i in range(trig.getNumTriangles()): 
            prim.addVertices(trig.getTriangleV0(i), 
                             trig.getTriangleV1(i), 
                             trig.getTriangleV2(i)) 
            prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        np.reparentTo(render)
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
    
    def draw_tristrips(self, ps, color, name, parent = None):
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        
        for i in ps :
            vwriter.addData3f(i[0], i[1], i[0])

        prim = GeomTristrips(Geom.UHStatic)
        
        for i in range(len(ps)) :
            prim.addVertex(i) 
        prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        
        if parent == None :
            render.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
        
    def draw_triangles(self, points = None, color = None, name = None, parent = None):
        
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3c4(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        cwriter = GeomVertexWriter(vdata, 'color')
        
        for i in points :
            vwriter.addData3f(i[0], i[1], i[2])
            cwriter.addData4f(color[0], color[1], color[2], color[3])
        
        geom = Geom(vdata)
        
        prim = GeomTriangles(Geom.UHStatic)
        for i in range(len(points)) :            
            prim.addVertex(i)
        prim.closePrimitive()
        geom.addPrimitive(prim) 
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        
        if parent == None :
            render.attachNewNode(np.node())
        else :
            self.get_parent(parent).attachNewNode(np.node())

        np.setTransparency(TransparencyAttrib.MAlpha)
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        
        self.elements[name] = np
        
        return np
    
    def draw_trianglefan(self, ps, color, name, parent = None):
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        
        for i in ps :
            vwriter.addData3f(i[0], i[1], i[2])

        prim = GeomTrifans(Geom.UHStatic)
        
        for i in range(len(ps)) :
            prim.addVertex(i) 
        prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        
        if parent == None :
            render.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
    
    def draw_polygon2d(self,ps,color,name):
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        
        trig = Triangulator()
        
        for i in ps :
            vi = trig.addVertex(i[0], i[1])
            vwriter.addData3f(i[0], 0, i[1])
            trig.addPolygonVertex(vi)

        trig.triangulate()
        
        prim = GeomTriangles(Geom.UHStatic)
        
        for i in range(trig.getNumTriangles()): 
            prim.addVertices(trig.getTriangleV0(i), 
                             trig.getTriangleV1(i), 
                             trig.getTriangleV2(i)) 
            prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        np.reparentTo(self.screen)
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
          
    def draw_image2d(self, **kw):
        '''
        tex = loader.loadTexture(texname)
        
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3t2(), Geom.UHStatic)
        vwriter = GeomVertexWriter(vdata, 'vertex')
        twriter = GeomVertexWriter(vdata, 'texcoord')
        
        vwriter.addData3f(i[0], 0, i[1])
        vwriter.addData3f(i[0], 0, i[1])
            
        twriter.addData2f(0, 0)
        twriter.addData2f(0, 1)
        twriter.addData2f(1, 1)
        twriter.addData2f(1, 0)
        
        geom = Geom(vdata)
        tris = GeomTristrips(Geom.UHStatic)
        tris.addVertex(0)
        tris.addVertex(1)
        tris.addVertex(3)
        tris.addVertex(2)
        tris.closePrimitive()
        geom.addPrimitive(tris)
        node = GeomNode(name)
        node.addGeom(geom)
        
        np = self.screen.attachNewNode(node)
        
        np.setTexture(tex)
        np.getTexture().setMinfilter(Texture.FTLinearMipmapLinear)
        
        self.elements[name] = node
        '''
        pos = kw.get('pos', (0, 0))
        size = kw.get('size', None)
        texname = kw.get('texname', None)
        scaleX = kw.get('scaleX', 1)
        scaleY = kw.get('scaleY', 1)
        parent = self.get_parent( kw.get('parent', 'gui_surface') )
        name = kw.get('name', self.generate_name())
        
        tex = Texture()
        if texname <> None :
            if texname in textures.keys() :
                tex = textures[texname]
            else :
                tex = loader.loadTexture(texname)
        

        cm = CardMaker('card')
        xframe = tex.getXSize()
        if tex.getOrigFileXSize() <> 0 : xframe = tex.getOrigFileXSize()

        yframe = tex.getYSize()
        if tex.getOrigFileYSize() <> 0 : yframe = tex.getOrigFileYSize()
        
        if size == None :            
            size = (tex.getXSize(), tex.getYSize())
        cm.setFrame(0,size[0]*scaleX,0,size[1]*scaleY)
        
        card = None
        if parent == None :
            card = self.screen.attachNewNode(cm.generate())
        else :
            card = parent.attachNewNode(cm.generate())
        
        if texname <> None :
            card.setTexture(tex)
        card.setDepthTest(False)
        card.setPos(pos[0],0,pos[1])
        
        #card.setHpr(0,-90,0)

        self.elements[name] = card
        
        return card
    
    def create_image2d(self, **kwargs):
        pos = kwargs.get('pos', (0, 0))
        size = kwargs.get('size', None)
        texname = kwargs.get('texname', None)
        UVmap = kwargs.get('UVmap', 0)
        name = kwargs.get('name', self.generate_name())
        rotate = 0
        for i in kwargs.keys() :
            if i == 'rotate' : rotate = kwargs['rotate']
        cm = CardMaker('card')
        tex = None
        if texname <> None : 
            tex = loader.loadTexture(texname)
            
        if size == None and texname <> None :            
            size = (tex.getOrigFileXSize(), tex.getOrigFileYSize())
            
        cm.setFrame(-float(size[0])/2,float(size[0])/2,-float(size[1])/2,float(size[1])/2)
        
        if tex <> None and UVmap :
            fU, fV = 1, 1 
            if UVmap == 3 or UVmap == 1: fU = float(size[0])/tex.getOrigFileXSize()
            if UVmap == 3 or UVmap == 2: fV = float(size[1])/tex.getOrigFileYSize()
            cm.setUvRange((0, 0),(fU, fV))

        card = NodePath(cm.generate())
        
        if texname <> None :
            card.setTexture(tex)

        card.setDepthTest(False)
        card.setPos(pos[0]+float(size[0])/2,0,pos[1]+float(size[1])/2)
        card.setHpr(0,0,rotate)
        card.setTransparency(TransparencyAttrib.MAlpha)
        
        return card

    def create_model_xt(self, **kw):#pos, model, texture, size, name = None):
        pos = kw.get('pos', (0, 0, 0))
        model = kw.get('fname', None)
        texture = kw.get('texname', None)
        size = kw.get('size', (1, 1))
        name = kw.get('name', self.generate_name())
        if self.check_name(name) :
                #print 'create_model_xt name duplicated', name
                return None
        
        model = self.game_directory + Filename.fromOsSpecific('\\' + model).getFullpath()
        
        a = loader.loadModel(model)
        texture = self.game_directory + Filename.fromOsSpecific('\\' + texture).getFullpath()
        a.setTexture(loader.loadTexture(texture))
        a.reparentTo(render)
        cmin, cmax = a.getTightBounds()
        smax = 0
        
        sx = size[0]/(cmax[0] - cmin[0])
        sy = size[1]/(cmax[1] - cmin[1])
        if sx > sy : smax = sx
        else : smax = sy
        a.setScale(smax)
        
        shiftx = ( (cmax[0] + cmin[0])/2 ) * smax
        shifty = ( (cmax[1] + cmin[1])/2 ) * smax
        
        a.setPos(pos[0] - shiftx,pos[1] - shifty,pos[2])
        
        #m.flattenLight()
        #a.analyze()
        
        if name == None : name = self.generate_name()        
        self.elements[name] = a
        
        return a
    
    def create_model_egg(self, pos, model, texture, size, name = None):
        model = self.game_directory + Filename.fromOsSpecific('\\' + model).getFullpath()
        a = loader.loadModel(model)
        a.reparentTo(render)
        cmin, cmax = a.getTightBounds()
        smax = 0
        sx = size[0]/(cmax[0] - cmin[0])
        sy = size[1]/(cmax[1] - cmin[1])
        if sx > sy : smax = sx
        else : smax = sy
        a.setScale(smax)
        
        shiftx = ( (cmax[0] + cmin[0])/2 ) * smax
        shifty = ( (cmax[1] + cmin[1])/2 ) * smax

        a.setPos(pos[0] - shiftx,pos[1] - shifty,pos[2])
        
        #m.flattenLight()
        #a.analyze()
        
        if name == None : name = self.generate_name()        
        self.elements[name] = a
        print '!!!'
        
        return name
    
    def create_actor_egg(self, **kw):
        model = self.game_directory + Filename.fromOsSpecific('\\' + kw['model']).getFullpath()
        m = loader.loadModel(model)
        a = Actor(m, kw['anims'])
        a.reparentTo(render)
        cmin, cmax = a.getTightBounds()
        smax = 0
        size = kw['size']
        sx = size[0]/(cmax[0] - cmin[0])
        sy = size[1]/(cmax[1] - cmin[1])
        if sx > sy : smax = sx
        else : smax = sy
        a.setScale(smax)
        
        shiftx = ( (cmax[0] + cmin[0])/2 ) * smax
        shifty = ( (cmax[1] + cmin[1])/2 ) * smax
        pos = kw['pos']
        a.setPos(pos[0] - shiftx,pos[1] - shifty,pos[2])
        
        #m.flattenLight()
        #a.analyze()
        name = kw.get('name', None)
        if name == None : name = self.generate_name()
        self.elements[name] = a
        
        return name

    def map_to_scr(self, a):
        #print 'mts', self.map_pos, a, [ (a[0] - self.map_pos[0])*self.map_zoom, (a[1] - self.map_pos[1])*self.map_zoom ], self.width, self.height
        return [ (a[0] - self.map_pos[0])*self.map_zoom, (a[1] - self.map_pos[1])*self.map_zoom ]
    
    def scr_to_map(self, a):
        #a is (-1,-1) to (1,1)
        pos3d = Point3() 
        nearPoint = Point3() 
        farPoint = Point3() 
        self.p3d.camLens.extrude(a, nearPoint, farPoint)
        self.plane.intersectsLine(pos3d, 
                                     render.getRelativePoint(self.p3d.camera, nearPoint), 
                                     render.getRelativePoint(self.p3d.camera, farPoint))
        return pos3d[0],pos3d[1]

    def set_map_pos(self, posx, posy):
        self.p3d.camera.setX(posx)
        self.p3d.camera.setY(posy)
        #self.gr.p3d.camera.lookAt(250,0,550)
        self.map_pos = (posx, posy)

    def set_map_zoom(self, zoom):
        self.p3d.camera.setZ( zoom )

    def zoom_in(self):
        self.p3d.camera.setZ( self.p3d.camera.getZ()*0.9 )
        self.minimap.update_pos(True)
        
        if self.p3d.camera.getZ() < 200 :
            self.paths_all_node.show()

    def zoom_out(self):
        self.p3d.camera.setZ( self.p3d.camera.getZ()*1.1 )
        self.minimap.update_pos(True)
        
        if self.p3d.camera.getZ() > 200 :
            self.paths_all_node.hide()

    def generate_name(self):
        name = str(RANDINT(0,9))
        while name in self.elements.keys() :
            name += str(RANDINT(0,9))
        return name

    def delete_el(self, name):
        if name in self.elements.keys() :
            self.elements[name].removeNode()
            self.elements.pop(name)
    
    def delete_el_mask(self,mask):
        for i in self.elements.keys() :
            if mask in i :
                self.delete_el(i)
                
    def get_num_nodes_rec(self, a):
        x = 0
        l = len(a.getChildren())
        if l == 0 : 
            return 1
        else : 
            for c in a.getChildren() : 
                x += self.get_num_nodes_rec(c)
        return x
    
    def get_num_nodes(self):
        a = self.get_num_nodes_rec(render)
        b = self.get_num_nodes_rec(render2d)
        c = self.get_num_nodes_rec(aspect2d)
        print 'render', a, 'render2d', b, 'aspect2d', c
        
    def check_name(self, name):
        if name in self.elements.keys() : return True
        else : return False

    def keyboard(self, st, keyname):
        if st == 0 : self.game_pipe.send(('key_down', keyname))
        elif st == 1 : self.game_pipe.send(('key_up', keyname))
        elif st == 2 : self.game_pipe.send(('key_rep', keyname))
Esempio n. 16
0
try:     
    f = open(path+'config.txt', 'r')
    for line in f:        
        if not line.startswith('#'):        
            loadPrcFileData('',line)
except IOError:
    print "No custom config file" 
    
from panda3d.core import WindowProperties
from panda3d.core import ConfigVariableInt
from panda3d.core import ConfigVariableBool
from panda3d.core import ConfigVariableString 
config_nude=ConfigVariableInt('loverslab', 0)   
config_aa=ConfigVariableInt('multisamples', 0)
buff_size=ConfigVariableInt('buffer-size', 1024)
config_fulscreen=ConfigVariableBool('fullscreen')
config_win_size=ConfigVariableInt('win-size', '640 480') 
config_autoshader=ConfigVariableBool('use-shaders', 0)
config_bloom=ConfigVariableBool('bloom', 1)
config_music=ConfigVariableInt('music-volume', '30') 
config_sfx=ConfigVariableInt('sound-volume', '100') 
config_safemode=ConfigVariableBool('safemode', 0)
#keys
config_forward=ConfigVariableString('key_forward', 'w|arrow_up') 
config_back=ConfigVariableString('key_back', 's|arrow_down')
config_left=ConfigVariableString('key_left', 'a|arrow_left')
config_right=ConfigVariableString('key_right', 'd|arrow_right')
config_camera_left=ConfigVariableString('key_cam_left', 'q|delete')
config_camera_right=ConfigVariableString('key_cam_right', 'e|page_down')
config_action1=ConfigVariableString('key_action1', 'mouse1|enter')
config_action2=ConfigVariableString('key_action2', 'mouse3|space')
Esempio n. 17
0
    def __init__(self):
        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        #render.setShaderAuto()
        # Enhance font readability
        font = loader.loadFont("assets/fonts/OldaniaADFStd-Regular.otf")
        DGG.setDefaultFont(font)
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # get the displays width and height for later usage
        self.dispWidth = self.pipe.getDisplayWidth()
        self.dispHeight = self.pipe.getDisplayHeight()

        base.serverHost = ConfigVariableString("server-host", "127.0.0.1:4400")

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if particles should be enabled
        # NOTE: If you use the internal physics engine, this always has
        #       to be enabled!
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(self.dispWidth, self.dispHeight)
            # request the new properties
            base.win.requestProperties(props)
            # Set the config variables so we correctly store the
            # new size and fullscreen setting later
            winSize = ConfigVariableString("win-size")
            winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
            fullscreen = ConfigVariableBool("fullscreen")
            fullscreen.setValue(True)
            # Render a frame to make sure the fullscreen is applied
            # before we do anything else
            self.taskMgr.step()
            # make sure to propagate the new aspect ratio properly so
            # the GUI and other things will be scaled appropriately
            aspectRatio = self.dispWidth / self.dispHeight
            self.adjustWindowAspectRatio(aspectRatio)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()

        # automatically safe configuration at application exit
        base.exitFunc = self.writeConfig
Esempio n. 18
0
needs to handle an error or throw an exception, you should do that
(and not just assert for it).

If you want to be a super keen software engineer then avoid using verify().
If you want to be, or already are, a super keen software engineer, but
you don't always have the time to write proper error handling, go ahead
and use verify() -- that's what it's for.

Please use assert (properly) and do proper error handling; and use verify()
only when debugging (i.e. when it won't be checked-in) or where it helps
you resist using assert for error handling.
"""

from panda3d.core import ConfigVariableBool

wantVerifyPdb = ConfigVariableBool(
    'want-verify-pdb', False)  # Set to true to load pdb on failure.


def verify(assertion):
    """
    verify() is intended to be used in place of assert where you
    wish to have the assertion checked, even in release (-O) code.
    """
    if not assertion:
        print("\n\nverify failed:")
        import sys
        print("    File \"%s\", line %d" %
              (sys._getframe(1).f_code.co_filename, sys._getframe(1).f_lineno))
        if wantVerifyPdb:
            import pdb
            pdb.set_trace()
Esempio n. 19
0
"""MsgTypes module: contains distributed object message types"""

from panda3d.core import ConfigVariableBool

from direct.showbase.PythonUtil import invertDictLossless

if ConfigVariableBool('astron-support', True):
    MsgName2Id = {
        'CLIENT_HELLO': 1,
        'CLIENT_HELLO_RESP': 2,

        # Sent by the client when it's leaving.
        'CLIENT_DISCONNECT': 3,

        # Sent by the server when it is dropping the connection deliberately.
        'CLIENT_EJECT': 4,
        'CLIENT_HEARTBEAT': 5,
        'CLIENT_OBJECT_SET_FIELD': 120,
        'CLIENT_OBJECT_SET_FIELDS': 121,
        'CLIENT_OBJECT_LEAVING': 132,
        'CLIENT_OBJECT_LEAVING_OWNER': 161,
        'CLIENT_ENTER_OBJECT_REQUIRED': 142,
        'CLIENT_ENTER_OBJECT_REQUIRED_OTHER': 143,
        'CLIENT_ENTER_OBJECT_REQUIRED_OWNER': 172,
        'CLIENT_ENTER_OBJECT_REQUIRED_OTHER_OWNER': 173,
        'CLIENT_DONE_INTEREST_RESP': 204,
        'CLIENT_ADD_INTEREST': 200,
        'CLIENT_ADD_INTEREST_MULTIPLE': 201,
        'CLIENT_REMOVE_INTEREST': 203,
        'CLIENT_OBJECT_LOCATION': 140,
Esempio n. 20
0
from panda3d.core import ConfigVariableBool, ConfigVariableString, ConfigVariableInt

# Server related config variables
sv_max_clients = ConfigVariableInt("sv_max_clients", 24)
sv_password = ConfigVariableString("sv_password", "")
sv_minupdaterate = ConfigVariableInt("sv_minupdaterate", 1)
sv_maxupdaterate = ConfigVariableInt("sv_maxupdaterate", 255)
sv_tickrate = ConfigVariableInt("sv_tickrate", 66)
# How many past snapshots do we save?
sv_snapshot_history = ConfigVariableInt("sv_snapshot_history", 50)
sv_port = ConfigVariableInt("sv_port", 27015)
sv_alternateticks = ConfigVariableBool("sv_alternateticks", False)
Esempio n. 21
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((0.0, 0.0, 0.0, 1.0))
     # Set up lights.
     self.lights = NodePath("lights")
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2**11, 2**11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {
         "physics": ("p", ),
         "repel": ("t", ),
         "bump": ("f", ),
         "rotate": ("r", 20),
         "rotate90": ("h", ),
         "ss_task": ("s", ),
         "ssa_task": ("w", ),
         "bp": ("b", )
     }
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [
         task.getName() for task in self.taskMgr.getAllTasks()
     ]
     self.start_time = -1
     self.old_elapsed = 0
Esempio n. 22
0
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set background color to black
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        helper.hide_cursor()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if audio should be muted
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(w, h)
            # request the new properties
            base.win.requestProperties(props)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        elif base.appRunner:
            # When the application is started as appRunner instance, it
            # doesn't respect our loadPrcFiles configurations specific
            # to the window as the window is already created, hence we
            # need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                # check if we have the fullscreen variable
                if mainConfig.getVariableName(dec) == "fullscreen":
                    setFullscreen()
        # automatically safe configuration at application exit
        base.exitFunc = self.__writeConfig

        # due to the delayed window resizing and switch to fullscreen
        # we wait some time until everything is set so we can savely
        # proceed with other setups like the menus
        if base.appRunner:
            # this behaviour only happens if run from p3d files and
            # hence the appRunner is enabled
            taskMgr.doMethodLater(0.5,
                                  self.postInit,
                                  "post initialization",
                                  extraArgs=[])
        else:
            self.postInit()
Esempio n. 23
0
    f = open(path + 'autoconfig.txt', 'r')
    for line in f:
        if not line.startswith('#'):
            loadPrcFileData('', line)
except IOError:
    print("No config file, using default")

loadPrcFileData('', 'show-frame-rate-meter  #f')
#loadPrcFileData('','win-origin -2 -2')

from panda3d.core import ConfigVariableInt
from panda3d.core import ConfigVariableBool
from panda3d.core import ConfigVariableString

config_aa = ConfigVariableInt('multisamples', 0)
config_fulscreen = ConfigVariableBool('fullscreen')
config_win_size = ConfigVariableInt('win-size', '640 480')
config_bloom = ConfigVariableBool('bloom', 1)
config_safemode = ConfigVariableBool('safemode', 0)
config_eye_enabled = ConfigVariableBool('eye_enabled', 0)
config_music = ConfigVariableInt('music-volume', '30')
config_sfx = ConfigVariableInt('sound-volume', '100')
#keys
config_forward = ConfigVariableString('key_forward', 'w|arrow_up')
config_back = ConfigVariableString('key_back', 's|arrow_down')
config_left = ConfigVariableString('key_left', 'a|arrow_left')
config_right = ConfigVariableString('key_right', 'd|arrow_right')
config_camera_left = ConfigVariableString('key_cam_left', 'q|delete')
config_camera_right = ConfigVariableString('key_cam_right', 'e|page_down')
config_action1 = ConfigVariableString('key_action1', 'mouse1|left_eye')
config_action2 = ConfigVariableString('key_action2', 'mouse3|right_eye')
Esempio n. 24
0
    def __init__(self):
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        self.disableMouse()
        self.setBackgroundColor(0, 0, 0)
        self.camLens.setFov(75)
        self.camLens.setNear(0.8)

        # check if the config file hasn't been created
        base.textWriteSpeed = 0.05
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()
        base.textWriteSpeed = ConfigVariableDouble("text-write-speed",0.05).getValue()
        base.controlType = ConfigVariableString("control-type", "Gamepad").getValue()
        base.mouseSensitivity = ConfigVariableDouble("mouse-sensitivity",1.0).getValue()
        if not os.path.exists(prcFile):
            self.__writeConfig()
            # set window properties
            # clear all properties not previously set
            self.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # window icon
            print props.hasIconFilename()
            props.setIconFilename(windowicon)
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set the window size to the screen resolution
            props.setSize(w, h)
            # request the new properties
            self.win.requestProperties(props)
        atexit.register(self.__writeConfig)

        # enable collision handling
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        base.pusher.addInPattern('%fn-in-%in')
        base.pusher.addOutPattern('%fn-out-%in')

        self.menu = Menu()
        self.options = OptionsMenu()

        self.musicMenu = loader.loadMusic("MayanJingle6_Menu.ogg")
        self.musicMenu.setLoop(True)

        cm = CardMaker("menuFade")
        cm.setFrameFullscreenQuad()
        self.menuCoverFade = NodePath(cm.generate())
        self.menuCoverFade.setTransparency(TransparencyAttrib.MAlpha)
        self.menuCoverFade.setBin("fixed", 1000)
        self.menuCoverFade.reparentTo(render2d)
        self.menuCoverFade.hide()
        self.menuCoverFadeOutInterval = Sequence(
            Func(self.menuCoverFade.show),
            LerpColorScaleInterval(
                self.menuCoverFade,
                1,
                LVecBase4f(0.0,0.0,0.0,1.0),
                LVecBase4f(0.0,0.0,0.0,0.0)),
            Func(self.menuCoverFade.hide))
        self.menuCoverFadeInInterval = Sequence(
            Func(self.menuCoverFade.show),
            LerpColorScaleInterval(
                self.menuCoverFade,
                1,
                LVecBase4f(0.0,0.0,0.0,0.0),
                LVecBase4f(0.0,0.0,0.0,1.0)),
            Func(self.menuCoverFade.hide))
        self.lerpAudioFadeOut = LerpFunc(
            self.audioFade,
            fromData=1.0,
            toData=0.0,
            duration=0.25,
            extraArgs=[self.musicMenu])
        self.fadeMusicOut = Sequence(
            self.lerpAudioFadeOut,
            Func(self.musicMenu.stop))
        self.lerpAudioFadeIn = LerpFunc(
            self.audioFade,
            fromData=0.0,
            toData=1.0,
            duration=1,
            extraArgs=[self.musicMenu])
        self.fadeMusicIn = Sequence(
                Func(self.musicMenu.play),
                self.lerpAudioFadeIn)

        self.seqFade = None
        self.acceptAll()

        self.request("Intro")
Esempio n. 25
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((1,1,1,1))
     # Set up lights.
     ablight = AmbientLight("ambientlight")
     ablight.setColor(Vec4(0.5, 0.5, 0.5, 1))
     ablightnode = self.render.attachNewNode(ablight)
     self.render.setLight(ablightnode)
     ptlight0 = PointLight("pointlight0")
     ptlight0.setColor(VBase4(1, 1, 1, 1))
     ptlightnode0 = self.render.attachNewNode(ptlight0)
     ptlightnode0.setPos(500, 0, 500)
     base.render.setLight(ptlightnode0)
     ptlight1 = PointLight("pointlight1")
     ptlight1.setColor(VBase4(1, 1, 1, 1))
     ptlightnode1 = base.render.attachNewNode(ptlight1)
     ptlightnode1.setPos(0, 500, 500)
     base.render.setLight(ptlightnode1)
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2 ** 11, 2 ** 11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {"physics": ("p",),
               "repel": ("t",),
               "bump": ("f",),
               "rotate": ("r", 20),
               "rotate90": ("h",),
               "ss_task": ("s",),
               "ssa_task": ("w",),
               "bp": ("b",)}
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [task.getName()
                             for task in self.taskMgr.getAllTasks()]
     self.start_time = -1
     self.old_elapsed = 0
Esempio n. 26
0
class ControlManager:
    notify = DirectNotifyGlobal.directNotify.newCategory("ControlManager")
    wantWASD = ConfigVariableBool('want-WASD', False)

    def __init__(self, enable=True, passMessagesThrough = False):
        assert self.notify.debug("init control manager %s" % (passMessagesThrough))
        assert self.notify.debugCall(id(self))
        self.passMessagesThrough = passMessagesThrough
        self.inputStateTokens = []
        # Used to switch between strafe and turn. We will reset to whatever was last set.
        self.WASDTurnTokens = []
        self.__WASDTurn = True
        self.controls = {}
        self.currentControls = None
        self.currentControlsName = None
        self.isEnabled = 0
        if enable:
            self.enable()
        #self.monitorTask = taskMgr.add(self.monitor, "ControlManager-%s"%(id(self)), priority=-1)
        self.forceAvJumpToken = None



        if self.passMessagesThrough: # for not breaking toontown
            ist=self.inputStateTokens
            ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watchWithModifiers("reverse", "arrow_down", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))


    def __str__(self):
        return 'ControlManager: using \'%s\'' % self.currentControlsName

    def add(self, controls, name="basic"):
        """
        controls is an avatar control system.
        name is any key that you want to use to refer to the
            the controls later (e.g. using the use(<name>) call).

        Add a control instance to the list of available control systems.

        See also: use().
        """
        assert self.notify.debugCall(id(self))
        assert controls is not None
        oldControls = self.controls.get(name)
        if oldControls is not None:
            assert self.notify.debug("Replacing controls: %s" % name)
            oldControls.disableAvatarControls()
            oldControls.setCollisionsActive(0)
            oldControls.delete()
        controls.disableAvatarControls()
        controls.setCollisionsActive(0)
        self.controls[name] = controls

    def get(self, name):
        return self.controls.get(name)

    def remove(self, name):
        """
        name is any key that was used to refer to the
            the controls when they were added (e.g.
            using the add(<controls>, <name>) call).

        Remove a control instance from the list of
        available control systems.

        See also: add().
        """
        assert self.notify.debugCall(id(self))
        oldControls = self.controls.pop(name,None)
        if oldControls is not None:
            assert self.notify.debug("Removing controls: %s" % name)
            oldControls.disableAvatarControls()
            oldControls.setCollisionsActive(0)

    if __debug__:
        def lockControls(self):
            self.ignoreUse=True

        def unlockControls(self):
            if hasattr(self, "ignoreUse"):
                del self.ignoreUse

    def use(self, name, avatar):
        """
        name is a key (string) that was previously passed to add().

        Use a previously added control system.

        See also: add().
        """
        assert self.notify.debugCall(id(self))
        if __debug__ and hasattr(self, "ignoreUse"):
            return
        controls = self.controls.get(name)

        if controls is not None:
            if controls is not self.currentControls:
                if self.currentControls is not None:
                    self.currentControls.disableAvatarControls()
                    self.currentControls.setCollisionsActive(0)
                    self.currentControls.setAvatar(None)
                self.currentControls = controls
                self.currentControlsName = name
                self.currentControls.setAvatar(avatar)
                self.currentControls.setCollisionsActive(1)
                if self.isEnabled:
                    self.currentControls.enableAvatarControls()
                messenger.send('use-%s-controls'%(name,), [avatar])
            #else:
            #    print "Controls are already", name
        else:
            assert self.notify.debug("Unkown controls: %s" % name)

    def setSpeeds(self, forwardSpeed, jumpForce,
            reverseSpeed, rotateSpeed, strafeLeft=0, strafeRight=0):
        assert self.notify.debugCall(id(self))
        for controls in self.controls.values():
            controls.setWalkSpeed(
                forwardSpeed, jumpForce, reverseSpeed, rotateSpeed)

    def delete(self):
        assert self.notify.debugCall(id(self))
        self.disable()
        for controls in list(self.controls.keys()):
            self.remove(controls)
        del self.controls
        del self.currentControls

        for token in self.inputStateTokens:
            token.release()

        for token in self.WASDTurnTokens:
            token.release()
        self.WASDTurnTokens = []

        #self.monitorTask.remove()

    def getSpeeds(self):
        if self.currentControls:
            return self.currentControls.getSpeeds()
        return None

    def getIsAirborne(self):
        if self.currentControls:
            return self.currentControls.getIsAirborne()
        return False

    def setTag(self, key, value):
        assert self.notify.debugCall(id(self))
        for controls in self.controls.values():
            controls.setTag(key, value)

    def deleteCollisions(self):
        assert self.notify.debugCall(id(self))
        for controls in self.controls.values():
            controls.deleteCollisions()

    def collisionsOn(self):
        assert self.notify.debugCall(id(self))
        if self.currentControls:
            self.currentControls.setCollisionsActive(1)

    def collisionsOff(self):
        assert self.notify.debugCall(id(self))
        if self.currentControls:
            self.currentControls.setCollisionsActive(0)

    def placeOnFloor(self):
        assert self.notify.debugCall(id(self))
        if self.currentControls:
            self.currentControls.placeOnFloor()

    def enable(self):
        assert self.notify.debugCall(id(self))

        if self.isEnabled:
            assert self.notify.debug('already isEnabled')
            return

        self.isEnabled = 1

        # keep track of what we do on the inputState so we can undo it later on
        #self.inputStateTokens = []
        ist = self.inputStateTokens
        ist.append(inputState.watch("run", 'runningEvent', "running-on", "running-off"))

        ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys))
        ist.append(inputState.watch("forward", "force-forward", "force-forward-stop"))

        ist.append(inputState.watchWithModifiers("reverse", "arrow_down", inputSource=inputState.ArrowKeys))
        ist.append(inputState.watchWithModifiers("reverse", "mouse4", inputSource=inputState.Mouse))

        if self.wantWASD:
            ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watch("turnLeft", "mouse-look_left", "mouse-look_left-done"))
            ist.append(inputState.watch("turnLeft", "force-turnLeft", "force-turnLeft-stop"))

            ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watch("turnRight", "mouse-look_right", "mouse-look_right-done"))
            ist.append(inputState.watch("turnRight", "force-turnRight", "force-turnRight-stop"))

            ist.append(inputState.watchWithModifiers("forward", "w", inputSource=inputState.WASD))
            ist.append(inputState.watchWithModifiers("reverse", "s", inputSource=inputState.WASD))

            ist.append(inputState.watchWithModifiers("slideLeft", "q", inputSource=inputState.QE))
            ist.append(inputState.watchWithModifiers("slideRight", "e", inputSource=inputState.QE))

            self.setWASDTurn(self.__WASDTurn)
        else:
            ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watch("turnLeft", "mouse-look_left", "mouse-look_left-done"))
            ist.append(inputState.watch("turnLeft", "force-turnLeft", "force-turnLeft-stop"))

            ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watch("turnRight", "mouse-look_right", "mouse-look_right-done"))
            ist.append(inputState.watch("turnRight", "force-turnRight", "force-turnRight-stop"))

        # Jump controls
        if self.wantWASD:
            ist.append(inputState.watchWithModifiers("jump", "space"))
        else:
            ist.append(inputState.watch("jump", "control", "control-up"))

        if self.currentControls:
            self.currentControls.enableAvatarControls()

    def disable(self):
        assert self.notify.debugCall(id(self))
        self.isEnabled = 0

        for token in self.inputStateTokens:
            token.release()
        self.inputStateTokens = []

        for token in self.WASDTurnTokens:
            token.release()
        self.WASDTurnTokens = []

        if self.currentControls:
            self.currentControls.disableAvatarControls()

        if self.passMessagesThrough: # for not breaking toontown
            ist=self.inputStateTokens
            ist.append(inputState.watchWithModifiers("forward", "arrow_up", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watchWithModifiers("reverse", "arrow_down", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watchWithModifiers("turnLeft", "arrow_left", inputSource=inputState.ArrowKeys))
            ist.append(inputState.watchWithModifiers("turnRight", "arrow_right", inputSource=inputState.ArrowKeys))

    def stop(self):
        self.disable()
        if self.currentControls:
            self.currentControls.setCollisionsActive(0)
            self.currentControls.setAvatar(None)
        self.currentControls = None

    def disableAvatarJump(self):
        """
        prevent
        """
        assert self.forceAvJumpToken is None
        self.forceAvJumpToken=inputState.force(
            "jump", 0, 'ControlManager.disableAvatarJump')

    def enableAvatarJump(self):
        """
        Stop forcing the ctrl key to return 0's
        """
        assert self.forceAvJumpToken is not None
        self.forceAvJumpToken.release()
        self.forceAvJumpToken = None

    def monitor(self, foo):
        #assert self.debugPrint("monitor()")
        #if 1:
        #    airborneHeight=self.avatar.getAirborneHeight()
        #    onScreenDebug.add("airborneHeight", "% 10.4f"%(airborneHeight,))
        if 0:
            onScreenDebug.add("InputState forward", "%d"%(inputState.isSet("forward")))
            onScreenDebug.add("InputState reverse", "%d"%(inputState.isSet("reverse")))
            onScreenDebug.add("InputState turnLeft", "%d"%(inputState.isSet("turnLeft")))
            onScreenDebug.add("InputState turnRight", "%d"%(inputState.isSet("turnRight")))
            onScreenDebug.add("InputState slideLeft", "%d"%(inputState.isSet("slideLeft")))
            onScreenDebug.add("InputState slideRight", "%d"%(inputState.isSet("slideRight")))
        return Task.cont

    def setWASDTurn(self, turn):
        self.__WASDTurn = turn

        if not self.isEnabled:
            return

        turnLeftWASDSet = inputState.isSet("turnLeft", inputSource=inputState.WASD)
        turnRightWASDSet = inputState.isSet("turnRight", inputSource=inputState.WASD)
        slideLeftWASDSet = inputState.isSet("slideLeft", inputSource=inputState.WASD)
        slideRightWASDSet = inputState.isSet("slideRight", inputSource=inputState.WASD)

        for token in self.WASDTurnTokens:
            token.release()

        if turn:
            self.WASDTurnTokens = (
                inputState.watchWithModifiers("turnLeft", "a", inputSource=inputState.WASD),
                inputState.watchWithModifiers("turnRight", "d", inputSource=inputState.WASD),
                )

            inputState.set("turnLeft", slideLeftWASDSet, inputSource=inputState.WASD)
            inputState.set("turnRight", slideRightWASDSet, inputSource=inputState.WASD)

            inputState.set("slideLeft", False, inputSource=inputState.WASD)
            inputState.set("slideRight", False, inputSource=inputState.WASD)

        else:
            self.WASDTurnTokens = (
                inputState.watchWithModifiers("slideLeft", "a", inputSource=inputState.WASD),
                inputState.watchWithModifiers("slideRight", "d", inputSource=inputState.WASD),
                )

            inputState.set("slideLeft", turnLeftWASDSet, inputSource=inputState.WASD)
            inputState.set("slideRight", turnRightWASDSet, inputSource=inputState.WASD)

            inputState.set("turnLeft", False, inputSource=inputState.WASD)
            inputState.set("turnRight", False, inputSource=inputState.WASD)
Esempio n. 27
0
def GetBool(sym, default=False):
    return ConfigVariableBool(sym, default, "DConfig", ConfigFlags.F_dconfig).value
Esempio n. 28
0
#from otp.ai.AIBaseGlobal import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.DirectObject import DirectObject
from .ConnectionRepository import *
from panda3d.core import ConfigVariableDouble, ConfigVariableInt, ConfigVariableBool

ASYNC_REQUEST_DEFAULT_TIMEOUT_IN_SECONDS = 8.0
ASYNC_REQUEST_INFINITE_RETRIES = -1
ASYNC_REQUEST_DEFAULT_NUM_RETRIES = 0

if __debug__:
    _overrideTimeoutTimeForAllAsyncRequests = ConfigVariableDouble(
        "async-request-timeout", -1.0)
    _overrideNumRetriesForAllAsyncRequests = ConfigVariableInt(
        "async-request-num-retries", -1)
    _breakOnTimeout = ConfigVariableBool("async-request-break-on-timeout",
                                         False)


class AsyncRequest(DirectObject):
    """
    This class is used to make asynchronos reads and creates to a database.

    You can create a list of self.neededObjects and then ask for each to be
    read or created, or if you only have one object that you need you can
    skip the self.neededObjects because calling askForObject or createObject
    will set the self.neededObjects value for you.

    Once all the objects have been read or created, the self.finish() method
    will be called.  You may override this function to run your code in a
    derived class.
Esempio n. 29
0
try:
    f = open(path+'config.txt', 'r')
    for line in f:
        if not line.startswith('#'):
            loadPrcFileData('',line)
except IOError:
    print("No custom config file")


from panda3d.core import WindowProperties
from panda3d.core import ConfigVariableInt
from panda3d.core import ConfigVariableBool
from panda3d.core import ConfigVariableString
config_aa=ConfigVariableInt('multisamples', 0)
buff_size=ConfigVariableInt('buffer-size', 1024)
config_fulscreen=ConfigVariableBool('fullscreen')
config_win_size=ConfigVariableInt('win-size', '640 480')
config_autoshader=ConfigVariableBool('use-shaders', 0)
config_bloom=ConfigVariableBool('bloom', 1)
config_music=ConfigVariableInt('music-volume', '10')
config_sfx=ConfigVariableInt('sound-volume', '100')
config_safemode=ConfigVariableBool('safemode', 0)
#keys
config_menuitems=ConfigVariableString('key_menuitems', 'v')
config_useitem=ConfigVariableString('key_useitem', 'u')
config_nextitem=ConfigVariableString('key_nextitem', 'i')
config_forward=ConfigVariableString('key_forward', 'w|arrow_up')
config_back=ConfigVariableString('key_back', 's|arrow_down')
config_left=ConfigVariableString('key_left', 'a|arrow_left')
config_right=ConfigVariableString('key_right', 'd|arrow_right')
config_camera_left=ConfigVariableString('key_cam_left', 'q|delete')
Esempio n. 30
0
    def writeConfig(self):
        """Save current config in the prc file or if no prc file exists
        create one. The prc file is set in the prcFile variable"""
        page = None

        #
        #TODO: add any configuration variable names that you have added
        #      to the dictionaries in the next lines. Set the current
        #      configurations value as value in this dictionary and it's
        #      name as key.
        configVariables = {
            # set the window size in the config file
            "win-size":
            ConfigVariableString(
                "win-size", "{} {}".format(self.dispWidth,
                                           self.dispHeight)).getValue(),
            # set the default to fullscreen in the config file
            "fullscreen":
            "#t"
            if ConfigVariableBool("fullscreen", True).getValue() else "#f",
            # particles
            "particles-enabled":
            "#t" if self.particleMgrEnabled else "#f",
            # audio
            "audio-volume":
            str(round(self.musicManager.getVolume(), 2)),
            "audio-music-active":
            "#t" if self.musicActive else "#f",
            "audio-sfx-active":
            "#t" if self.sfxActive else "#f",
            # logging
            "notify-output":
            os.path.join(basedir, "game.log"),
            # window
            "framebuffer-multisample":
            "#t" if ConfigVariableBool("framebuffer-multisample").getValue()
            else "#f",
            "multisamples":
            str(ConfigVariableInt("multisamples", 8).getValue()),
            "texture-anisotropic-degree":
            str(ConfigVariableInt("texture-anisotropic-degree").getValue()),
            "textures-auto-power-2":
            "#t" if ConfigVariableBool("textures-auto-power-2",
                                       True).getValue() else "#f",
            # server connection
            "server-host":
            base.serverHost.getValue(),
        }

        page = None
        # Check if we have an existing configuration file
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(prcFile))
            removeDecls = []
            for dec in range(page.getNumDeclarations()):
                # Check if our variables are given.
                # NOTE: This check has to be done to not loose our base
                #       or other manual config changes by the user
                if page.getVariableName(dec) in configVariables.keys():
                    removeDecls.append(page.modifyDeclaration(dec))
            for dec in removeDecls:
                page.deleteDeclaration(dec)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("Application Config")

        # always write custom configurations
        for key, value in configVariables.items():
            page.makeDeclaration(key, value)
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
Esempio n. 31
0
class DataStore:
    QueryTypes = []
    QueryTypes = dict(zip(QueryTypes, range(len(QueryTypes))))

    @classmethod
    def addQueryTypes(cls, typeStrings):
        superTypes = zip(cls.QueryTypes.values(), cls.QueryTypes.keys())
        superTypes.sort()
        newTypes = [item[1] for item in superTypes] + typeStrings
        newTypes = dict(zip(newTypes, range(1 + len(newTypes))))
        return newTypes

    notify = DirectNotifyGlobal.directNotify.newCategory('DataStore')
    wantAnyDbm = ConfigVariableBool('want-ds-anydbm', 1).getValue()

    def __init__(self, filepath, writePeriod=300, writeCountTrigger=100):
        self.filepath = filepath
        self.writePeriod = writePeriod
        self.writeCountTrigger = writeCountTrigger
        self.writeCount = 0
        self.data = None
        self.className = self.__class__.__name__
        if self.wantAnyDbm:
            self.filepath += '-anydbm'
            self.notify.debug('anydbm default module used: %s ' %
                              anydbm._defaultmod.__name__)
        self.open()
        return

    def readDataFromFile(self):
        if self.wantAnyDbm:
            try:
                if os.path.exists(self.filepath):
                    self.data = anydbm.open(self.filepath, 'w')
                    self.notify.debug(
                        'Opening existing anydbm database at: %s.' %
                        (self.filepath, ))
                else:
                    self.data = anydbm.open(self.filepath, 'c')
                    self.notify.debug('Creating new anydbm database at: %s.' %
                                      (self.filepath, ))
            except anydbm.error:
                self.notify.warning('Cannot open anydbm database at: %s.' %
                                    (self.filepath, ))

        else:
            try:
                file = open(self.filepath + '.bu', 'r')
                self.notify.debug('Opening backup pickle data file at %s.' %
                                  (self.filepath + '.bu', ))
                if os.path.exists(self.filepath):
                    os.remove(self.filepath)
            except IOError:
                try:
                    file = open(self.filepath, 'r')
                    self.notify.debug('Opening old pickle data file at %s..' %
                                      (self.filepath, ))
                except IOError:
                    file = None
                    self.notify.debug(
                        'New pickle data file will be written to %s.' %
                        (self.filepath, ))

            if file:
                data = cPickle.load(file)
                file.close()
                self.data = data
            else:
                self.data = {}
        return

    def writeDataToFile(self):
        if self.data is not None:
            self.notify.debug('Data is now synced with disk at %s' %
                              self.filepath)
            if self.wantAnyDbm:
                self.data.sync()
            else:
                try:
                    backuppath = self.filepath + '.bu'
                    if os.path.exists(self.filepath):
                        os.rename(self.filepath, backuppath)
                    outfile = open(self.filepath, 'w')
                    cPickle.dump(self.data, outfile)
                    outfile.close()
                    if os.path.exists(backuppath):
                        os.remove(backuppath)
                except EnvironmentError:
                    self.notify.warning(str(sys.exc_info()[1]))

        else:
            self.notify.warning('No data to write. Aborting sync.')
        return

    def syncTask(self, task):
        task.timeElapsed += globalClock.getDt()
        if task.timeElapsed > self.writePeriod:
            if self.writeCount:
                self.writeDataToFile()
                self.resetWriteCount()
            task.timeElapsed = 0.0
        if self.writeCount > self.writeCountTrigger:
            self.writeDataToFile()
            self.resetWriteCount()
            task.timeElapsed = 0.0
        return Task.cont

    def incrementWriteCount(self):
        self.writeCount += 1

    def resetWriteCount(self):
        self.writeCount = 0

    def close(self):
        if self.data is not None:
            self.writeDataToFile()
            if self.wantAnyDbm:
                self.data.close()
            taskMgr.remove('%s-syncTask' % (self.className, ))
            self.data = None
        return

    def open(self):
        self.close()
        self.readDataFromFile()
        self.resetWriteCount()
        taskMgr.remove('%s-syncTask' % (self.className, ))
        t = taskMgr.add(self.syncTask, '%s-syncTask' % (self.className, ))
        t.timeElapsed = 0.0

    def reset(self):
        self.destroy()
        self.open()

    def destroy(self):
        self.close()
        if self.wantAnyDbm:
            lt = time.asctime(time.localtime())
            trans = maketrans(': ', '__')
            t = lt.translate(trans)
            head, tail = os.path.split(self.filepath)
            newFileName = 'UDStoreBak' + t
            if os.path.exists(self.filepath):
                try:
                    os.rename(tail, newFileName)
                    uber.air.writeServerEvent(
                        'Uberdog data store Info', 0,
                        'Creating backup of file: %s saving as: %s' %
                        (tail, newFileName))
                except:
                    uber.air.writeServerEvent(
                        'Uberdog data store Info', 0,
                        'Unable to create backup of file: %s ' % tail)

            else:
                files = os.listdir(head)
                for file in files:
                    if file.find(tail) > -1:
                        filename, ext = os.path.splitext(file)
                        try:
                            os.rename(file, newFileName + ext)
                            uber.air.writeServerEvent(
                                'Uberdog data store Info', 0,
                                'Creating backup of file: %s saving as: %s' %
                                (file, newFileName + ext))
                        except:
                            uber.air.writeServerEvent(
                                'Uberdog data store Info', 0,
                                'Unable to create backup of file: %s ' %
                                newFileName + ext)

        else:
            if os.path.exists(self.filepath + '.bu'):
                os.remove(self.filepath + '.bu')
            if os.path.exists(self.filepath):
                os.remove(self.filepath)

    def query(self, query):
        if self.data is not None:
            qData = cPickle.loads(query)
            results = self.handleQuery(qData)
            qResults = cPickle.dumps(results)
        else:
            results = None
            qResults = cPickle.dumps(results)
        return qResults

    def handleQuery(self, query):
        results = None
        return results
DODGEBLUE = (0.11, 0.53, 0.93, 1)
DARKGRAIN = (0.5, 0.5, 0.5, 0.5)
OLIVE = (0.33, 0.42, 0.18, 1)
YELLOWGREEN = (0.60, 0.80, 0.20, 1)
KHAKI = (0.74, 0.72, 0.42, 1)
FIREBRICK = (0.70, 0.13, 0.13, 1)
MARRON = (0.69, 0.19, 0.38, 1)
VIOLET = (0.78, 0.08, 0.52, 1)
BROWN = (0.55, 0.27, 0.07, 1)
SNOW = (0.55, 0.27, 0.07, 1)
GOLD = (1, 0.84, 0, 1)
RED = (1, 0, 0, 1)
GREEN = (0, 1, 0, 1)
BLUE = (0, 0, 1, 1)
BLACK = (0, 0, 0, 1)
WHITE = (1, 1, 1, 1)

#PANDA
#www.panda3d.org/manual/index.php/List_of_all_config_variables
ConfigVariableString("window-title",
                     'Panda').setStringValue(PROJECT_NAME + ' - ' + VERSION)

ConfigVariableBool('fullscreen', 0).setValue(FULLSCREEN)
ConfigVariableString(
    'win-size', '640 480').setValue(str(WINSIZE[0]) + ' ' + str(WINSIZE[1]))
ConfigVariableBool('show-frame-rate-meter', '').setValue(DEBUG)

#ConfigVariableString('load-display', 'pandagl').setValue('pandagl') #pandagl, pandadx9, pandadx8, tinydisplay
#ConfigVariableString ('aux-display', 'pandagl').setValue('pandagl')  #pandagl, pandadx9, pandadx8, tinydisplay
#ConfigVariableBool  ('undecorated', '').setValue(True)
Esempio n. 33
0
    def __init__(self, params, pipe, dir):
        self.game_directory = dir
        self.game_pipe = pipe
        self.gs_window = ConfigVariableString('win-size')
        self.gs_window.setValue(str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        
        self.gs_multi = ConfigVariableBool('framebuffer-multisample')
        self.gs_multi.setValue(params.get('multisample', 1))
        
        self.gs_sync = ConfigVariableBool('sync-video', str(params.get('sync', 1)))
        self.gs_sync.setValue(params.get('sync', 1))

        loadPrcFileData('', 'win-size '+ str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        loadPrcFileData('', 'win-fixed-size 1')
        loadPrcFileData('', 'text-default-font data/HanZi.ttf')
        loadPrcFileData('', 'multisamples ' + str(params.get('samples', 0)))

        #loadPrcFileData('', 'fullscreen 1')
        #loadPrcFileData('', 'textures-power-2 pad')
        #loadPrcFileData('', 'notify-level spam')
        #loadPrcFileData('', 'default-directnotify-level spam')
        #loadPrcFileData('', 'notify-output I:\\Users\\User\\My Documents\\Aptana Studio 3 Workspace\\sg\\out2.txt')
        #nout = MultiplexStream()
        #Notify.ptr().setOstreamPtr(nout, 0)
        #nout.addFile(Filename("out.txt"))

        '''for i in xrange(ConfigVariableManager.getGlobalPtr().getNumVariables()):
            if ConfigVariableManager.getGlobalPtr().isVariableUsed(i) :
                name = ConfigVariableManager.getGlobalPtr().getVariableName(i)
                v = ConfigVariable(name)
        '''

        self.p3d = ShowBase.ShowBase()
        self.p3d.buttonThrowers[0].node().setButtonDownEvent('buttonDown') 
        self.p3d.buttonThrowers[0].node().setButtonRepeatEvent('buttonRep')
        self.p3d.buttonThrowers[0].node().setButtonUpEvent('buttonUp')
        self.p3d.accept('buttonDown', self.keyboard, [0,])
        self.p3d.accept('buttonRep', self.keyboard, [2,])
        self.p3d.accept('buttonUp', self.keyboard, [1,])

        self.p3d.disableMouse()       #Disable default mouse-based camera control

        self.screen = render2d.attachNewNode("Screen Coord Node")
        self.screen.setBin("fixed", 100)
        self.flat = render.attachNewNode("2d Objects in 3d world")
        self.flat.setBin('background', 0)
        self.flat.setDepthTest(False)
        self.flat.setDepthWrite(False)
        
        render.setAntialias(AntialiasAttrib.MAuto)
        
        self.props = WindowProperties(self.p3d.win.getProperties())

        #Screen size
        self.width = params['width']
        self.height = params['height']
        self.aratio = float(self.width)/self.height #aspect ratio
        self.p3d.camera.setZ(1000)
        self.p3d.camera.lookAt(0,0,0)
        self.p3d.camLens.setFov(80)
        #self.props.setSize(size[0],size[1])

        self.screen.setScale(2.0/self.width,1,2.0/self.height)
        
        self.dt = 0.0
        self.fps = 0
        
        self.title_last_update_time = 0
        
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
        
        self.elements = {}
        
        #self.MModel = self.create_model_xt((0,0,0), 'models\\chinesegfx_city_1_1.x', 'models\\houses_chinesegfx.tga', (3,3))[1]
        #self.MModel.reparentTo(hidden)
        #sys.stdout.flush()
        #self.p3d.taskMgr.run()
        #self.myShader = Shader.load(Shader.SLGLSL, "modules\\myvertexshader.glsl", "modules\\myfragmentshader.glsl")
        
        #self.plane2.setShader(self.myShader)

        self.mouse_pos = (0, 0)
        self.mouse_on_map_pos = (0, 0)
        self.p3d.accept('wheel_up',self.zoom_in)
        self.p3d.accept('wheel_down',self.zoom_out)
        self.p3d.accept('mouse1',self.mouse_click_left)
        self.p3d.accept('mouse3',self.mouse_click_right)
        
        self.parents = {}
        
        self.gui_surface = aspect2d.attachNewNode("GUI Node")
        self.gui_surface.setScale(2.0/self.height,1,2.0/self.height)
        self.gui_surface.setBin("fixed", 50)
        
        self.map_node = self.add_node('map_node', 'background', 0, self.flat)
        self.paths_node = self.add_node('paths_node', 'background', 3, self.flat)
        self.paths_all_node = self.add_node('paths_all_node', 'background', 3, self.flat)
        self.map_mode_node = self.add_node('map_mode_node', 'background', 1, self.map_node)
        self.selecties_node = self.add_node('selecties_node', 'background', 2, self.map_node)

        self.parents['render'] = render
        self.parents['gui_surface'] = self.gui_surface
        
        self.elements['city_map_model'] = self.create_model_xt(fname = 'models\\chinesegfx_city_1_1.x', texname = 'models\\houses_chinesegfx.tga', size = (3, 3), name = 'city_map_model')
        
        self.minimap = Minimap(self.width, self.height, self)
Esempio n. 34
0
class Notifier:
    serverDelta = 0

    # If this object is set to something, it is used to print output
    # messages instead of writing them to the console.  This is
    # particularly useful for integrating the Python notify system
    # with the C++ notify system.
    streamWriter = None
    if ConfigVariableBool('notify-integrate', True):
        streamWriter = StreamWriter(Notify.out(), False)

    showTime = ConfigVariableBool('notify-timestamp', False)

    def __init__(self, name, logger=None):
        """
        name is a string
        logger is a Logger

        Create a new instance of the Notifier class with a given name
        and an optional Logger class for piping output to. If no logger
        specified, use the global default
        """
        self.__name = name

        if (logger==None):
            self.__logger = defaultLogger
        else:
            self.__logger = logger

        # Global default levels are initialized here
        self.__info = 1
        self.__warning = 1
        self.__debug = 0
        self.__logging = 0

    def setServerDelta(self, delta, timezone):
        """
        Call this method on any Notify object to globally change the
        timestamp printed for each line of all Notify objects.

        This synchronizes the timestamp with the server's known time
        of day, and also switches into the server's timezone.
        """
        delta = int(round(delta))
        Notifier.serverDelta = delta + time.timezone - timezone

        # The following call is necessary to make the output from C++
        # notify messages show the same timestamp as those generated
        # from Python-level notify messages.
        NotifyCategory.setServerDelta(self.serverDelta)

        self.info("Notify clock adjusted by %s (and timezone adjusted by %s hours) to synchronize with server." % (PythonUtil.formatElapsedSeconds(delta), (time.timezone - timezone) / 3600))

    def getTime(self):
        """
        Return the time as a string suitable for printing at the
        head of any notify message
        """
        # for some strange reason, time.time() updates only once/minute if
        # the task is out of focus on win32.  time.clock doesn't have this problem.
        return time.strftime(":%m-%d-%Y %H:%M:%S ", time.localtime(time.time() + self.serverDelta))

    def getOnlyTime(self):
        """
        Return the time as a string.
        The Only in the name is referring to not showing the date.
        """
        return time.strftime("%H:%M:%S", time.localtime(time.time() + self.serverDelta))

    def __str__(self):
        """
        Print handling routine
        """
        return "%s: info = %d, warning = %d, debug = %d, logging = %d" % \
               (self.__name, self.__info, self.__warning, self.__debug, self.__logging)

    # Severity funcs
    def setSeverity(self, severity):
        from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
        if severity >= NSError:
            self.setWarning(0)
            self.setInfo(0)
            self.setDebug(0)
        elif severity == NSWarning:
            self.setWarning(1)
            self.setInfo(0)
            self.setDebug(0)
        elif severity == NSInfo:
            self.setWarning(1)
            self.setInfo(1)
            self.setDebug(0)
        elif severity <= NSDebug:
            self.setWarning(1)
            self.setInfo(1)
            self.setDebug(1)

    def getSeverity(self):
        from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
        if self.getDebug():
            return NSDebug
        elif self.getInfo():
            return NSInfo
        elif self.getWarning():
            return NSWarning
        else:
            return NSError

    # error funcs
    def error(self, errorString, exception=StandardError):
        """
        Raise an exception with given string and optional type:
        Exception: error
        """
        message = str(errorString)
        if Notifier.showTime.getValue():
            string = (self.getTime() + str(exception) + ": " + self.__name + "(error): " + message)
        else:
            string = (str(exception) + ": " + self.__name + "(error): " + message)
        self.__log(string)
        raise exception(errorString)

    # warning funcs
    def warning(self, warningString):
        """
        Issue the warning message if warn flag is on
        """
        if self.__warning:
            message = str(warningString)
            if Notifier.showTime.getValue():
                string = (self.getTime() + self.__name + '(warning): ' + message)
            else:
                string = (":" + self.__name + '(warning): ' + message)
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert myNotify.warning("blah")

    def setWarning(self, bool):
        """
        Enable/Disable the printing of warning messages
        """
        self.__warning = bool

    def getWarning(self):
        """
        Return whether the printing of warning messages is on or off
        """
        return(self.__warning)

    # debug funcs
    def debug(self, debugString):
        """
        Issue the debug message if debug flag is on
        """
        if self.__debug:
            message = str(debugString)
            if Notifier.showTime.getValue():
                string = (self.getTime() + self.__name + '(debug): ' + message)
            else:
                string = (':' + self.__name + '(debug): ' + message)
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert myNotify.debug("blah")

    def setDebug(self, bool):
        """
        Enable/Disable the printing of debug messages
        """
        self.__debug = bool

    def getDebug(self):
        """
        Return whether the printing of debug messages is on or off
        """
        return self.__debug

    # info funcs
    def info(self, infoString):
        """
        Print the given informational string, if info flag is on
        """
        if self.__info:
            message = str(infoString)
            if Notifier.showTime.getValue():
                string = (self.getTime() + self.__name + ': ' + message)
            else:
                string = (':' + self.__name + ': ' + message)
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert myNotify.info("blah")

    def getInfo(self):
        """
        Return whether the printing of info messages is on or off
        """
        return self.__info

    def setInfo(self, bool):
        """
        Enable/Disable informational message  printing
        """
        self.__info = bool

    # log funcs
    def __log(self, logEntry):
        """
        Determine whether to send informational message to the logger
        """
        if self.__logging:
            self.__logger.log(logEntry)

    def getLogging(self):
        """
        Return 1 if logging enabled, 0 otherwise
        """
        return (self.__logging)

    def setLogging(self, bool):
        """
        Set the logging flag to int (1=on, 0=off)
        """
        self.__logging = bool

    def __print(self, string):
        """
        Prints the string to output followed by a newline.
        """
        if self.streamWriter:
            self.streamWriter.appendData(string + '\n')
        else:
            print >> sys.stderr, string

    def debugStateCall(self, obj=None, fsmMemberName='fsm',
            secondaryFsm='secondaryFSM'):
        """
        If this notify is in debug mode, print the time of the
        call followed by the [fsm state] notifier category and
        the function call (with parameters).
        """
        #f.f_locals['self'].__init__.im_class.__name__
        if self.__debug:
            state = ''
            doId = ''
            if obj is not None:

                fsm=obj.__dict__.get(fsmMemberName)
                if fsm is not None:
                    stateObj = fsm.getCurrentState()
                    if stateObj is not None:
                        #state = "%s=%s"%(fsmMemberName, stateObj.getName())
                        state = stateObj.getName()

                fsm=obj.__dict__.get(secondaryFsm)
                if fsm is not None:
                    stateObj = fsm.getCurrentState()
                    if stateObj is not None:
                        #state = "%s=%s"%(fsmMemberName, stateObj.getName())
                        state = "%s, %s"%(state, stateObj.getName())

                if hasattr(obj, 'doId'):
                    doId = " doId:%s"%(obj.doId,)
            #if type(obj) == types.ClassType:
            #    name = "%s."%(obj.__class__.__name__,)
            string = ":%s:%s [%-7s] id(%s)%s %s"%(
                self.getOnlyTime(),
                self.__name,
                state,
                id(obj),
                doId,
                PythonUtil.traceParentCall())
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert self.notify.debugStateCall(self)

    def debugCall(self, debugString=''):
        """
        If this notify is in debug mode, print the time of the
        call followed by the notifier category and
        the function call (with parameters).
        """
        if self.__debug:
            message = str(debugString)
            string = ":%s:%s \"%s\" %s"%(
                self.getOnlyTime(),
                self.__name,
                message,
                PythonUtil.traceParentCall())
            self.__log(string)
            self.__print(string)
        return 1 # to allow assert self.notify.debugCall("blah")
Esempio n. 35
0
from panda3d.core import loadPrcFile
from panda3d.core import ConfigVariableBool
from spanda3D.engine import Engine
from sky.cube import SkyCube
from spanda3D.light import Light
from spanda3D.joystick import XboxControllerHandler

if __name__ == "__main__":
    loadPrcFile("config.prc")
    mouse = ConfigVariableBool('keyboard_mouse')
    e = Engine(mouse.getValue())
    SkyCube(e)
    Light(e)
    if mouse:
        print("Using keyboard-mouse controller")
    else:
        print("Using X-Box controller")
        XboxControllerHandler(e)
    e.run()