Пример #1
0
 def tick(self):
     #advance time, tick this 6x a second
     if self.lasttime == -1:
         self.lasttime = sysTime()
     delta = sysTime() - self.lasttime
     self.lasttime = sysTime()
     
     self.ticks += 3
     self.second += delta * 24.0 #1 game day = 1 real hour
     if self.second > 59:
         self.second -= 59
         self.minute += 1
         if self.minute > 59:
             self.minute = 0
             self.hour += 1
             if self.hour > 23:
                 self.hour = 0
                 self.day += 1
Пример #2
0
 def _init(self,*args,**kw):
     Persistent._init(self, *args, **kw)
     
     self.shuttingDown = False
     self.liveZoneInstances = []
     self.waitingZoneInstances = []
     self.activePlayers = []
     self.globalPlayers = {}
     self.mutedPlayers = {}
     self.time = Time()
     
     #from db
     self.time.second = 0
     self.time.minute = self.minute
     self.time.hour = self.hour
     self.time.day = self.day
     self.time.ticks = 0
     
     self.lasttime = -1
     
     self.transaction = False
     self.tickTransaction = None
     self.singlePlayer = False
     self.singlePlayerBackupTimer = 120 # Once every minute
     
     self.liveZoneCallback = None
     
     self.usedZonePorts = []
     
     self.running = False
     self.dbFile = None
     self.backupTick = 30 #once every 30 minutes
     
     self.paused = False
     self.pauseTime = sysTime()
     
     self.daemonPerspective = None
     self.daemonMind = None
     self.AHPerspective = None
     self.MailServerPerspective = None
     
     self.clusterNum = -1
     self.worldPort = -1
     
     self.staticZoneNames = []
     
     self.priority = 1
     
     self.deathMarkers = {}
     self.characterInfos = {}
     
     self.allowConnections = True
     
     self.cpuSpawn = 0
     self.cpuDespawn = 0
     self.spawnZoneIndex = 0
     self.isShuttingDown = False
Пример #3
0
    def tick(self):
        #advance time, tick this 6x a second
        if self.lasttime == -1:
            self.lasttime = sysTime()
        delta = sysTime() - self.lasttime
        self.lasttime = sysTime()

        self.ticks += 3
        self.second += delta * 24.0  #1 game day = 1 real hour
        if self.second > 59:
            self.second -= 59
            self.minute += 1
            if self.minute > 59:
                self.minute = 0
                self.hour += 1
                if self.hour > 23:
                    self.hour = 0
                    self.day += 1
Пример #4
0
    def _init(self, *args, **kw):
        Persistent._init(self, *args, **kw)

        self.shuttingDown = False
        self.liveZoneInstances = []
        self.waitingZoneInstances = []
        self.activePlayers = []
        self.globalPlayers = {}
        self.mutedPlayers = {}
        self.time = Time()

        #from db
        self.time.second = 0
        self.time.minute = self.minute
        self.time.hour = self.hour
        self.time.day = self.day
        self.time.ticks = 0

        self.lasttime = -1

        self.transaction = False
        self.tickTransaction = None
        self.singlePlayer = False
        self.singlePlayerBackupTimer = 120  # Once every minute

        self.liveZoneCallback = None

        self.usedZonePorts = []

        self.running = False
        self.dbFile = None
        self.backupTick = 30  #once every 30 minutes

        self.paused = False
        self.pauseTime = sysTime()

        self.daemonPerspective = None
        self.daemonMind = None
        self.AHPerspective = None
        self.MailServerPerspective = None

        self.clusterNum = -1
        self.worldPort = -1

        self.staticZoneNames = []

        self.priority = 1

        self.deathMarkers = {}
        self.characterInfos = {}

        self.allowConnections = True

        self.cpuSpawn = 0
        self.cpuDespawn = 0
        self.spawnZoneIndex = 0
        self.isShuttingDown = False
Пример #5
0
 def perspective_call(self,*args):
     if THESERVER.throttleUsage and self.throttle:
         if self.cpuTime > 0:
             dc = MasterPerspective.deferredCalls[self]
             d = defer.Deferred()
             dc.append((d,args))
             #print "Throttling",args
             return d
         
     tm = sysTime()
     function = args[0]
     interface = self._interface
     try:
         avatar=self.avatars[interface]
     except KeyError:
         try: 
             interface = interface + "Avatar"
             avatar=self.avatars[interface]
         except:
             return failure.Failure(NoAvatarError())
         
     function = "perspective_"+function
     if not hasattr(avatar,function):
         return failure.Failure(NoFunctionError())
         
         
     nargs=args[1:]
     #on any function call we set the player's info to dirty
     if hasattr(avatar,"player"):
         if avatar.player:
             avatar.player.cinfoDirty = True
     try:
         result = getattr(avatar,function)(*nargs)
     except:
         #use errback
         traceback.print_exc()
         return failure.Failure(PerspectiveCallError())
     
     t = sysTime() - tm
     if t > .1:
         print "Warning: %s %s took %f seconds"%(self.username,args,t)
     self.cpuTime+=t
         
     return result
Пример #6
0
    def perspective_call(self, *args):
        if THESERVER.throttleUsage and self.throttle:
            if self.cpuTime > 0:
                dc = MasterPerspective.deferredCalls[self]
                d = defer.Deferred()
                dc.append((d, args))
                #print "Throttling",args
                return d

        tm = sysTime()
        function = args[0]
        interface = self._interface
        try:
            avatar = self.avatars[interface]
        except KeyError:
            try:
                interface = interface + "Avatar"
                avatar = self.avatars[interface]
            except:
                return failure.Failure(NoAvatarError())

        function = "perspective_" + function
        if not hasattr(avatar, function):
            return failure.Failure(NoFunctionError())

        nargs = args[1:]
        #on any function call we set the player's info to dirty
        if hasattr(avatar, "player"):
            if avatar.player:
                avatar.player.cinfoDirty = True
        try:
            result = getattr(avatar, function)(*nargs)
        except:
            #use errback
            traceback.print_exc()
            return failure.Failure(PerspectiveCallError())

        t = sysTime() - tm
        if t > .1:
            print "Warning: %s %s took %f seconds" % (self.username, args, t)
        self.cpuTime += t

        return result
Пример #7
0
    def endInteraction(self, closeWindow=True):
        if not self.interacting:
            return

        if hasattr(self.interacting, "interactTimes"):
            self.interacting.interactTimes[self] = sysTime()

        self.interacting.interacting = None
        self.interacting = None

        if hasattr(self, "zone"):
            if self.zone:
                for c in self.party.members:
                    self.zone.setTarget(c.mob, None)

        if closeWindow:
            self.mind.callRemote("closeNPCWnd")
Пример #8
0
 def endInteraction(self,closeWindow=True):
     if not self.interacting:
         return
     
     if hasattr(self.interacting,"interactTimes"):
         self.interacting.interactTimes[self] = sysTime()
     
     self.interacting.interacting = None
     self.interacting = None
     
     if hasattr(self,"zone"):
         if self.zone:
             for c in self.party.members:
                 self.zone.setTarget(c.mob,None)
     
     if closeWindow:
         self.mind.callRemote("closeNPCWnd")
Пример #9
0
 def removeMob(self, despawnTime=0):
     if not len(self.activeMobs):
         return
     
     lastActiveMob = self.activeMobs[0]
     
     if not despawnTime:
         if lastActiveMob.spawn.respawnTimer:
             despawnTime = lastActiveMob.spawn.respawnTimer
     
     self.activeMobs = []
     self.activeInfo = None
     self.despawnTime = despawnTime
     self.lastTick = sysTime()
     
     # Notify spawngroup controller, but only if zone isn't shutting down.
     if self.spawnGroupController and not self.zone.stopped:
         self.blocked = self.spawnGroupController.spawnRemoved(self,lastActiveMob)
Пример #10
0
    def removeMob(self, despawnTime=0):
        if not len(self.activeMobs):
            return

        lastActiveMob = self.activeMobs[0]

        if not despawnTime:
            if lastActiveMob.spawn.respawnTimer:
                despawnTime = lastActiveMob.spawn.respawnTimer

        self.activeMobs = []
        self.activeInfo = None
        self.despawnTime = despawnTime
        self.lastTick = sysTime()

        # Notify spawngroup controller, but only if zone isn't shutting down.
        if self.spawnGroupController and not self.zone.stopped:
            self.blocked = self.spawnGroupController.spawnRemoved(
                self, lastActiveMob)
Пример #11
0
def DoCharm(effect, src, dst):
    proto = effect.effectProto
    if not proto.flags&RPG_EFFECT_CHARM:
        return
    
    if dst.player:
        return
    
    if src.pet or src.petSpawning:
        return
    
    if dst.master:
        return
    
    pet = dst
    
    pet.charmBackupRealm = pet.realm
    pet.charmBackupAggro = pet.aggro
    pet.charmBegin = sysTime()
    pet.realm = src.realm
    pet.master = src
    src.pet = pet
    if src.player:
        pet.playerPet = True
        src.character.refreshPetItems()
    
    from mud.world.pet import PetCmdFollowMe
    PetCmdFollowMe(pet)
    
    pet.aggro = defaultdict(int)
    pet.setTarget(None)
    
    pet.charmEffect = effect
    
    petPet = pet.pet
    if petPet:
        if petPet.charmEffect:
            petPet.charmEffect.parent.cancel()
            if pet.pet:
                traceback.print_stack()
                print "AssertionError: pet charm effect resisted breaking!"
            return
        petPet.zone.removeMob(petPet)
Пример #12
0
def BreakCharm(effect):
    proto = effect.effectProto
    if not proto.flags&RPG_EFFECT_CHARM:
        return
    
    src = effect.src
    dst = effect.dst
    
    if not src.pet or src.pet != dst:
        return
    
    pet = src.pet
    zone = pet.zone
    
    pet.realm = pet.charmBackupRealm
    pet.aggro = pet.charmBackupAggro
    pet.petSpeedMod = 0.0
    pet.charmEffect = None
    pet.master = None
    src.pet = None
    pet.playerPet = False
    
    if src.character:
        # Unequip the items given by the Character master.
        map(pet.unequipItem,xrange(RPG_SLOT_WORN_BEGIN,RPG_SLOT_WORN_END))
        
        # Refresh the items given by the Character master.
        src.character.refreshPetItems()
        
        # And reequip own gear.
        map(pet.aiEquipItem,pet.loot.items)
        pet.mobInfo.refresh()
    
    zone.setTarget(pet,None)
    zone.setFollowTarget(pet,None)
    
    # Reset home transform in case the player used a /pet stay command.
    zone.simAvatar.mind.callRemote("resetHomeTransform",pet.simObject.id)
    
    # Make the released pet angry at its former master.
    # The longer the charm duration and the higher the pet level, the more angry.
    pet.addAggro(src,int(ceil(10 * pet.plevel * (sysTime() - pet.charmBegin))))
Пример #13
0
    def removeMob(self, mob, despawnTime=0):
        if mob.master and mob.master.player:
            mob.master.character.petHealthBackup = mob.health
            mob.master.character.petHealthTimer = int(sysTime())

        if mob.corpseRemoval:
            mob.corpseRemoval.cancel()
            mob.corpseRemoval = None

        if mob.spawnpoint:
            mob.spawnpoint.removeMob(despawnTime)

        mob.kingKiller = None

        if not mob.detached:
            self.detachMob(mob)

        if mob.looter:
            mob.looter.looting = None
            try:
                mob.looter.mind.callRemote("setLoot", {})
            except:
                pass

        if mob.loot:
            mob.loot.mob = None
            for item in mob.loot.items:
                item.destroySelf()

        if not mob.player:
            try:
                self.simAvatar.deleteObject(mob.simObject)
            except:
                pass
            try:
                del self.mobLookup[mob.simObject]
            except KeyError:
                pass

        mob.simObject = None
        self.world.cpuDespawn -= 1
Пример #14
0
    def removeMob(self, mob, despawnTime=0):
        if mob.master and mob.master.player:
            mob.master.character.petHealthBackup = mob.health
            mob.master.character.petHealthTimer = int(sysTime())

        if mob.corpseRemoval:
            mob.corpseRemoval.cancel()
            mob.corpseRemoval = None

        if mob.spawnpoint:
            mob.spawnpoint.removeMob(despawnTime)

        mob.kingKiller = None

        if not mob.detached:
            self.detachMob(mob)

        if mob.looter:
            mob.looter.looting = None
            try:
                mob.looter.mind.callRemote("setLoot", {})
            except:
                pass

        if mob.loot:
            mob.loot.mob = None
            for item in mob.loot.items:
                item.destroySelf()

        if not mob.player:
            try:
                self.simAvatar.deleteObject(mob.simObject)
            except:
                pass
            try:
                del self.mobLookup[mob.simObject]
            except KeyError:
                pass

        mob.simObject = None
        self.world.cpuDespawn -= 1
Пример #15
0
    def playerEnterZone(self, player):

        if not player.world:
            print "WARNING: Player Entering Zone not attached to world... probably lost connection to world while zoning in"
            return

        player.zone.simAvatar.setDisplayName(player)

        # announce to other players
        if player.role.name not in ("Guardian", "Immortal"):
            if player.enteringWorld:
                for p in self.players:
                    p.sendGameText(RPG_MSG_GAME_BLUE, r"%s has entered the zone.\n" % player.charName)
                for p in player.world.activePlayers:
                    if p == player:
                        continue
                    if p.enteringWorld:
                        continue
                    if p in self.players:  # already told that we entered zone
                        continue
                    p.sendGameText(RPG_MSG_GAME_BLUE, r"%s has entered the world.\n" % player.charName)
            else:
                pmob = player.curChar.mob
                for p in self.players:
                    if AllowHarmful(pmob, p.curChar.mob):
                        continue
                    p.sendGameText(RPG_MSG_GAME_BLUE, r"%s has entered the zone.\n" % player.charName)

        # If the player was logging in and not zoning, we still need to reset
        #  the flag denoting him/her entering the world.
        player.enteringWorld = False

        # we use queue to keep dynamic zones alive
        try:
            del self.playerQueue[player]
        except KeyError:
            pass

        # Check if encounter setting will be preserved or not
        #  yeah, 5 minutes are long, this is just to make sure ...
        if sysTime() - player.encounterPreserveTimer < 300:
            player.mind.callRemote("checkEncounterSetting", True)
        player.encounterPreserveTimer = 0
        player.encounterSetting = RPG_ENCOUNTER_PVE  # go safe until required otherwise

        self.players.append(player)

        for c in player.party.members:
            # Get a handle to this Character's Mob.
            mob = c.mob
            # Add the Mob to the Mob lookup table. Even if the player
            #  has multiple Characters in the party, there will be only
            #  one lookup table entry.
            self.mobLookup[player.simObject] = mob
            # Set the Mob's simulation object.
            mob.simObject = player.simObject
            # Append this Mob to this Zone's list of active Mobs.
            self.activeMobs.append(mob)

            # If the Character zoned in dead, detach the Mob again.
            if c.dead:
                self.detachMob(mob)

        # If this world doesn't allow more than a single party member,
        #  then set the death marker of the zoned in Player.
        if CoreSettings.MAXPARTY == 1:
            player.world.setDeathMarker(player, player.party.members[0])

        if CoreSettings.PGSERVER:
            player.world.sendCharacterInfo(player)
Пример #16
0
 def update(self, finfo=None, fromServer=False):
     from playerSettings import PLAYERSETTINGS
     
     try:
         FRIENDS = PLAYERSETTINGS.friends
         if finfo == None:
             finfo = self.remoteFriendsInfo
         else:
             self.remoteFriendsInfo = finfo
         
         playsound = False
         
         if fromServer:
             if sysTime() - self.lastSoundTime >= 15:
                 if TGEGetGlobal("$pref::game::friendsAudioAlerts") == "1":
                     playsound = True
         
         pos = self.scrollCtrl.childRelPos.split(" ")
         
         tc = self.textList
         tc.setVisible(False)
         tc.clear()
         
         online = set()
         offline = dict((friend.upper(),friend) for friend in FRIENDS)
         
         # Add online friends to list.
         for index,friend in enumerate(finfo.iterkeys()):
             friendUpper = friend.upper()
             matchGuild,wname,zname = finfo[friend]
             online.add(friend)
             try:
                 del offline[friendUpper]
             except KeyError:
                 pass
             if matchGuild:
                 # To be collected and forwarded to guild gui once this exists.
                 guildTag = " (Guild Member)"
             else:
                 guildTag = ""
             self.textList.addRow(index,"%s%s\t%s\t%s"%(friend,guildTag,wname,zname))
         
         # Add offline friends to list.
         for index,friend in enumerate(offline.itervalues()):
             self.textList.addRow(index,"%s\tAway\t"%(friend))
         
         if fromServer:
             for name in online.difference(self.active):
                 receiveGameText(RPG_MSG_GAME_LEVELGAINED, \
                     "Your friend %s has joined the game!\\n"%name)
                 if playsound:
                     TGEEval('alxPlay(alxCreateSource(AudioMessage, "%s/data/sound/sfx/Heartbeat_Loop1.ogg"));'%GAMEROOT)
                     self.lastSoundTime = sysTime()
             
             for name in self.active.difference(online):
                 receiveGameText(RPG_MSG_GAME_BLUE, \
                     "Your friend %s has left the game!\\n"%name)
                 if playsound:
                     TGEEval('alxPlay(alxCreateSource(AudioMessage, "%s/data/sound/sfx/BoneTowerPercussionRattle7.ogg"));'%GAMEROOT)
                     self.lastSoundTime = sysTime()
         
         self.active = online
         
         tc.setActive(True)
         tc.setVisible(True)
         
         self.scrollCtrl.scrollRectVisible(pos[0],pos[1],1,444)
     
     except:
         traceback.print_exc()
Пример #17
0
def ShutdownWorld(minutes = 10):
    global FORCEKILL_TIME,REBOOT, ANNOUNCE_MINUTE
    REBOOT = False
    FORCEKILL_TIME = sysTime()+minutes*60
    ANNOUNCE_MINUTE = minutes
    AnnounceShutdownReboot()
Пример #18
0
def ShutdownWorld(minutes=10):
    global FORCEKILL_TIME, REBOOT, ANNOUNCE_MINUTE
    REBOOT = False
    FORCEKILL_TIME = sysTime() + minutes * 60
    ANNOUNCE_MINUTE = minutes
    AnnounceShutdownReboot()
Пример #19
0
if not WORLDNAME or not PUBLICNAME or PASSWORD is None:
    print "Usage: WorldDaemon -worldname=MYWORLD -publicname=MYPUBLICNAME -password=MYPASSWORD"
    raise "Incorrect Usage"


class BadConnectionError(Exception):
    def __str__(self):
        return "Bad Connection"


#military time!
REBOOT = True
REBOOT_HOUR = 3
REBOOT_MINUTE = 0
REBOOT_TIME = sysTime()
ANNOUNCE_MINUTE = -1

FORCEKILL_TIME = None

KILLED = False

SPAWNED = False

try:
    exec("from serverconfig.%s import *" % WORLDNAME)
except:
    print "Error reading server configuration, %s" % WORLDNAME
    sys.exit(-1)

Пример #20
0
def RebootWorld(minutes = 10):
    global FORCEKILL_TIME,REBOOT, ANNOUNCE_MINUTE
    FORCEKILL_TIME = sysTime()+minutes*60
    REBOOT = True
    ANNOUNCE_MINUTE = minutes
    AnnounceShutdownReboot()
Пример #21
0
    def update(self, finfo=None, fromServer=False):
        from playerSettings import PLAYERSETTINGS

        try:
            FRIENDS = PLAYERSETTINGS.friends
            if finfo == None:
                finfo = self.remoteFriendsInfo
            else:
                self.remoteFriendsInfo = finfo

            playsound = False

            if fromServer:
                if sysTime() - self.lastSoundTime >= 15:
                    if TGEGetGlobal("$pref::game::friendsAudioAlerts") == "1":
                        playsound = True

            pos = self.scrollCtrl.childRelPos.split(" ")

            tc = self.textList
            tc.setVisible(False)
            tc.clear()

            online = set()
            offline = dict((friend.upper(), friend) for friend in FRIENDS)

            # Add online friends to list.
            for index, friend in enumerate(finfo.iterkeys()):
                friendUpper = friend.upper()
                matchGuild, wname, zname = finfo[friend]
                online.add(friend)
                try:
                    del offline[friendUpper]
                except KeyError:
                    pass
                if matchGuild:
                    # To be collected and forwarded to guild gui once this exists.
                    guildTag = " (Guild Member)"
                else:
                    guildTag = ""
                self.textList.addRow(
                    index, "%s%s\t%s\t%s" % (friend, guildTag, wname, zname))

            # Add offline friends to list.
            for index, friend in enumerate(offline.itervalues()):
                self.textList.addRow(index, "%s\tAway\t" % (friend))

            if fromServer:
                for name in online.difference(self.active):
                    receiveGameText(RPG_MSG_GAME_LEVELGAINED, \
                        "Your friend %s has joined the game!\\n"%name)
                    if playsound:
                        TGEEval(
                            'alxPlay(alxCreateSource(AudioMessage, "%s/data/sound/sfx/Heartbeat_Loop1.ogg"));'
                            % GAMEROOT)
                        self.lastSoundTime = sysTime()

                for name in self.active.difference(online):
                    receiveGameText(RPG_MSG_GAME_BLUE, \
                        "Your friend %s has left the game!\\n"%name)
                    if playsound:
                        TGEEval(
                            'alxPlay(alxCreateSource(AudioMessage, "%s/data/sound/sfx/BoneTowerPercussionRattle7.ogg"));'
                            % GAMEROOT)
                        self.lastSoundTime = sysTime()

            self.active = online

            tc.setActive(True)
            tc.setVisible(True)

            self.scrollCtrl.scrollRectVisible(pos[0], pos[1], 1, 444)

        except:
            traceback.print_exc()
Пример #22
0
def DoResurrection(effect,src,dst):
    proto = effect.effectProto
    if not proto.flags&RPG_EFFECT_RESURRECTION:
        return False
    
    healthRecover = manaRecover = staminaRecover = 0
    for st in proto.stats:
        statname = st.statname
        if statname == 'health':
            if value > 0:
                healthRecover += st.value * (effect.mod + effect.healMod)
        elif statname == 'mana':
            manaRecover += st.value * effect.mod
        elif statname == 'stamina':
            staminaRecover += st.value * effect.mod
    
    if CoreSettings.MAXPARTY != 1:
        player = dst.player
        if not player:
            return False
        
        for c in player.party.members:
            if c.dead:
                c.resurrect(proto.resurrectionXP)
                mob = c.mob
                if healthRecover:
                    mob.health += healthRecover
                    if mob.health > mob.maxHealth:
                        mob.health = mob.maxHealth
                    c.health = int(mob.health)
                if manaRecover:
                    mob.mana += manaRecover
                    if mob.mana > mob.maxMana:
                        mob.mana = mob.maxMana
                    c.mana = int(mob.mana)
                if staminaRecover:
                    mob.stamina += staminaRecover
                    if mob.stamina > mob.maxStamina:
                        mob.stamina = mob.maxStamina
                    c.stamina = int(mob.stamina)
        return True
    else:
        if src.player:
            # Player resurrection of grave. Gather up the corpses in the zone.
            cnames = []
            srcZoneName = src.player.zone.zone.name
            srcPos = src.simObject.position
            for pname,dm in src.player.world.deathMarkers.iteritems():
                try:
                    charName,realm,zoneName,dstPos,rot = dm
                    if zoneName == srcZoneName:
                        x = srcPos[0] - dstPos[0]
                        y = srcPos[1] - dstPos[1]
                        z = srcPos[2] - dstPos[2]
                        r = x*x + y*y + z*z
                        # Test radius squared, no need to take root on vector.
                        if r < 50:
                            cnames.append(charName)
                except:
                    traceback.print_exc()
            
            # If the list of possible resurrection targets is empty,
            #  notify caster and return.
            if not len(cnames):
                src.player.sendGameText(RPG_MSG_GAME_DENIED,r'There are no graves near enough to resurrect.\n')
                return False
            
            # Send a list of names of possible resurrection targets to the caster.
            src.player.mind.callRemote("setResurrectNames",cnames)
            src.player.resurrection = (sysTime(),proto.resurrectionXP,healthRecover,manaRecover,staminaRecover,cnames)
            return True
        
        else:
            #hm, this is a mob resurrection, we could wipe the grave location and return some XP
            #for now, do nothing
            return False
Пример #23
0
    def tick():

        global TICK_COUNTER

        if not AVATAR:
            return  #not official

        #error?
        if not AVATAR.mind:
            return

        if AVATAR.world.shuttingDown:
            return

        try:

            now = sysTime()

            #ship off any player buffers from the last time

            try:
                from mud.worldserver.charutil import PLAYER_BUFFERS
                for pname, pbuffer, cbuffer, cvalues in PLAYER_BUFFERS[:]:
                    pbuf = encodestring(dumps(pbuffer, 2))
                    cbuf = None
                    if cbuffer:
                        cbuf = encodestring(dumps(cbuffer, 2))

                    print "Sending Player/Character buffers: %s (%ik/%ik)" % (
                        pname, len(pbuf) / 1024, len(cbuf) / 1024)
                    AVATAR.mind.callRemote("savePlayerBuffer", pname, pbuf,
                                           cbuf,
                                           cvalues)  #xxx add callback/errback
                    EXTRACT_TIMES[pname] = now
                    #should be removing these upon success
                    PLAYER_BUFFERS.remove((pname, pbuffer, cbuffer, cvalues))
            except:
                traceback.print_exc()

            TICK_COUNTER -= 3
            if TICK_COUNTER > 0:
                return

            TICK_COUNTER = 6 * 15  #once every minute

            pnames = []
            extractTarget = None
            best = 0
            for p in AVATAR.world.activePlayers:
                if not p.zone or p.enteringWorld:
                    continue

                pname = p.publicName
                pnames.append(pname)

                extractionTimer = EXTRACT_TIMES.setdefault(pname, now)
                t = now - extractionTimer

                if t < (60 * 10):
                    continue

                if t > best:
                    best = t
                    extractTarget = pname

            remove = []
            for k in EXTRACT_TIMES.iterkeys():
                if k not in pnames:
                    remove.append(k)
            map(EXTRACT_TIMES.__delitem__, remove)

            if extractTarget:
                p = Player.byPublicName(
                    extractTarget)  #already in active chars
                if p and p.party:
                    p.backupItems()
                    ExtractPlayer(p.publicName, p.id, p.party.members[0].id)
        except:
            traceback.print_exc()

        #send off all players

        try:
            pnames = []
            #it's still possible that the player is installed but isn't active
            #so 2 people sharing an account could still cause problems
            for p in AVATAR.world.activePlayers:
                cname = ""
                if p.curChar:
                    cname = p.curChar.name

                zname = ""
                if p.zone:
                    zname = p.zone.zone.niceName

                pnames.append((p.publicName, cname, p.guildName, zname))

            d = AVATAR.mind.callRemote("recordActivePlayers",
                                       AVATAR.world.multiName, pnames)
            d.addCallback(AVATAR.gotGlobalPlayers)

        except:
            traceback.print_exc()
Пример #24
0
 def wrapper(*a, **k):
     start = sysTime()
     retval = fct(*a, **k)
     elapsed = sysTime() - start
     return (retval, elapsed)
Пример #25
0
 def prepForZoneOut(self):
     self.encounterPreserveTimer = int(sysTime())
     self.backupItems()
Пример #26
0
 def tick(self):
     if not self.running:
         return
     
     reactor.callLater(.5,self.tick) #2x sec
     
     if False:#CoreSettings.PGSERVER:
         if len(self.liveZoneInstances)==len(self.staticZoneNames) and self.allowConnections:
             if not len(self.activePlayers) and self.priority:
                 self.priority = 0
                 win32process.SetPriorityClass(win32process.GetCurrentProcess(),win32process.IDLE_PRIORITY_CLASS)
                 
             if len(self.activePlayers) and not self.priority:
                 self.priority = 1
                 win32process.SetPriorityClass(win32process.GetCurrentProcess(),win32process.NORMAL_PRIORITY_CLASS)
                 
             #if not self.priority:
             #    win32api.Sleep(2000)
         elif not self.priority:
             self.priority = 1
             win32process.SetPriorityClass(win32process.GetCurrentProcess(),win32process.NORMAL_PRIORITY_CLASS)
             
     
     if False:#RPG_BUILD_DEMO:
         t = sysTime() - self.pauseTime
         if 13*60 >= t >= 12*60:
             self.paused = True
         elif t>13*60:
             self.paused = False
             self.pauseTime = sysTime()
         else:
             self.paused=False
     
     
     
     self.time.tick()
     
     #store in db
     if self.time.hour != self.hour:
         self.minute = self.time.minute
         self.hour = self.time.hour
         self.day = self.time.day
         
     CharacterServerAvatar.tick()
         
     #if self.lasttime == -1:
     #    self.lasttime = sysTime()-2
     #delta = sysTime()-self.lasttime
     
     #if delta > .5:
         #self.lasttime = sysTime()
         
     
     if CoreSettings.PGSERVER:
         if self.isShuttingDown:
             self.cpuSpawn = 0
             self.cpuDespawn = 0
         else:
             self.cpuSpawn = 4
             self.cpuDespawn = 8
     else:
         self.cpuSpawn = 1000000
         self.cpuDespawn = 1000000
     
     # Select the zone which will be allowed to spawn mobs.
     spawnZone = None
     if len(self.liveZoneInstances) > 0:
         if self.spawnZoneIndex > len(self.liveZoneInstances) - 1:
             self.spawnZoneIndex = 0
         spawnZone = self.liveZoneInstances[self.spawnZoneIndex]
         self.spawnZoneIndex += 1
     
     # Tick all live zone instances.
     for z in self.liveZoneInstances:
         z.tick(spawnZone)
     
     #weed out dynamic zones that haven't any players for x amount of time
     #we need to weed out failed zones (stuck in waiting, etc)
     
     if not self.singlePlayer:
         timedOut = []
         for z in self.liveZoneInstances:
             if not z.dynamic:
                 continue
             if not len(z.players) and not len(z.playerQueue):
                 if z.timeOut == -1:
                     z.timeOut = sysTime()
                 elif (sysTime() - z.timeOut)/60 > 20: # 20 minutes
                     timedOut.append(z)
                 
             else:
                 z.timeOut = -1
         
         for z in timedOut:
             self.closeZone(z)
     
     # Backup single player data every minute.
     else:
         self.singlePlayerBackupTimer -= 1
         if self.singlePlayerBackupTimer < 0:
             # Reset timer to one minute.
             self.singlePlayerBackupTimer = 120
             
             for player in self.activePlayers:
                 # If there's no party, player hasn't logged in yet and
                 #  there's no need to back up.
                 if player.party:
                     player.backupPlayer()
             
             # Force a write to database.
             conn = Persistent._connection.getConnection()
             cursor = conn.cursor()
             cursor.execute("END;")
             cursor.execute("BEGIN;")
             cursor.close()
Пример #27
0
    def reset(self):
        self.friends = set()
        self.friendsInfo = {}
        self.mailList = {}
        self.lastMailID = 0
        self.curChar = None
        self.zone = None
        self.avatar = None
        self.mind = None
        self.simObject = None
        self.cursorItem = None
        self.interacting = None
        self.dialog = None
        self.curDialogLine = None
        self.transfering = False
        self.cinfoDirty = True
        self.alliance = None

        self.textMessages = []
        self.textTicker = 0

        self.extract = True

        self.allianceTimeStamp = None

        #time, effect, cnames tuple
        self.resurrection = None
        #time, effect tuple
        self.resurrectionRequest = None

        self.realm = None
        self.telelink = None

        self.lastInnAddTime = sysTime()
        self.cserverInfos = None

        self.triggeredZoneOptions = []
        self.triggeredZoneLink = None
        self.invite = None
        self.name = self.fantasyName
        self.loggingOut = False
        self.trade = None
        self.world = None
        self.inn = None
        if self.party:
            for m in self.party.members:
                if m.mob:
                    m.mob.character = None
                    m.mob.player = None
                m.mob = None
        self.party = None
        self.rootInfo = None

        self.msgCombatNotCloseEnough = 0
        self.msgCombatCantSee = 0
        self.msgCombatNotFacing = 0

        self.trackingTimer = 0

        self.lastTell = None
        self.looting = None

        self.spellEffectCastTime = sysTime()
        self.spellEffectBeginTime = sysTime()

        self.bankList = None

        self.encounterSetting = RPG_ENCOUNTER_PVE

        # This gets set to True if the player party walks. Default is run.
        # Mobs have this handled specially and all player mobs in the same
        #  party are displayed by a single avatar. So it wouldn't make
        #  sense to put this somewhere else.
        self.walk = False
Пример #28
0
 def tick(self):
     if not self.spawngroup:
         return
     
     t = sysTime()
     delta = ceil((t - self.lastTick)*6.0)
     self.lastTick = t
     
     if self.despawnTime > 0:
         self.despawnTime -= delta
     
     if self.delay > 0:
         self.delay -= delta
     
     if self.despawnTime > 0:
         return
     
     if self.delay > 0:
         return
     
     if self.lastCheckTicker > 0:
         self.lastCheckTicker -= delta
         return
     
     # Here because should continue ticking down.
     if self.blocked:
         return
     
     #30 seconds
     self.lastCheckTicker = 180
     
     zone = self.zone
     if len(self.activeMobs):
         #there is currently a mob populating this spawnpoint
         
         #handle lifetime (disabled)
         if 0:
             if self.lifetime > 0:
                 self.lifetime -= delta
                 if self.lifetime == 0:
                     #poof
                     self.removeMob()
         
         #handle despawn times
         if self.activeInfo:
             sinfo = self.activeInfo
             # If we parse the list in reversed order,
             #  no need to copy to prevent problems
             #  while removing items during loop.
             for aMob in reversed(self.activeMobs):
                 if not aMob.target and not aMob.corpseRemoval:
                     if sinfo.startTime != -1 and sinfo.endTime != -1:
                         #if spawn crosses day boundry
                         if sinfo.endTime < sinfo.startTime:
                             if sinfo.startTime > zone.time.hour >= sinfo.endTime:
                                 zone.removeMob(aMob)
                         elif not (sinfo.endTime > zone.time.hour >= sinfo.startTime):
                             zone.removeMob(aMob)
 #code added by BellyFish
                     #does the NPC have a start and end day?
                     if sinfo.startDayRL != "" and sinfo.endDayRL != "":
                         #if so convert the startDayRL string to a 'date' object
                         startDayRL = date(*strptime(sinfo.startDayRL + "-" + strftime('%Y'), "%m-%d-%Y")[0:3])
                         #convert the endDayRL string to a 'date' object
                         endDayRL = date(*strptime(sinfo.endDayRL + "-" + strftime('%Y'), "%m-%d-%Y")[0:3])
                         #Figure out what todays date is
                         todayRL = date.today()
                         if endDayRL < startDayRL:
                         #spawn crosses the year boundry
                             if endDayRL < todayRL < startDayRL:
                                 zone.removeMob(aMob)
                         elif not (startDayRL <= todayRL <= endDayRL):
                             #spawn doesn't cross year boundry
                             zone.removeMob(aMob)
 #end added code
         
         if not len(self.activeMobs):
             #we poofed so no delay
             self.delay = 0
     
     if len(self.activeMobs):
         return
     
     sinfo = self.getSpawnInfo()
     if sinfo:
         self.lifetime = sinfo.lifetime
         self.activeMobs = [zone.spawnMob(sinfo.spawn,self.transform,self.wanderGroup)]
         self.activeMobs[0].spawnpoint = self
         self.activeInfo = sinfo
         
         if self.spawnGroupController:
             self.spawnGroupController.spawnAdded(self)
Пример #29
0
 def __init__(self):
     self.remoteFriendsInfo = {}
     self.active = []
     self.lastSoundTime = sysTime() - 15
Пример #30
0
    def tick(self):
        if not self.spawngroup:
            return

        t = sysTime()
        delta = ceil((t - self.lastTick) * 6.0)
        self.lastTick = t

        if self.despawnTime > 0:
            self.despawnTime -= delta

        if self.delay > 0:
            self.delay -= delta

        if self.despawnTime > 0:
            return

        if self.delay > 0:
            return

        if self.lastCheckTicker > 0:
            self.lastCheckTicker -= delta
            return

        # Here because should continue ticking down.
        if self.blocked:
            return

        #30 seconds
        self.lastCheckTicker = 180

        zone = self.zone
        if len(self.activeMobs):
            #there is currently a mob populating this spawnpoint

            #handle lifetime (disabled)
            if 0:
                if self.lifetime > 0:
                    self.lifetime -= delta
                    if self.lifetime == 0:
                        #poof
                        self.removeMob()

            #handle despawn times
            if self.activeInfo:
                sinfo = self.activeInfo
                # If we parse the list in reversed order,
                #  no need to copy to prevent problems
                #  while removing items during loop.
                for aMob in reversed(self.activeMobs):
                    if not aMob.target and not aMob.corpseRemoval:
                        if sinfo.startTime != -1 and sinfo.endTime != -1:
                            #if spawn crosses day boundry
                            if sinfo.endTime < sinfo.startTime:
                                if sinfo.startTime > zone.time.hour >= sinfo.endTime:
                                    zone.removeMob(aMob)
                            elif not (sinfo.endTime > zone.time.hour >=
                                      sinfo.startTime):
                                zone.removeMob(aMob)
    #code added by BellyFish
    #does the NPC have a start and end day?
                        if sinfo.startDayRL != "" and sinfo.endDayRL != "":
                            #if so convert the startDayRL string to a 'date' object
                            startDayRL = date(*strptime(
                                sinfo.startDayRL + "-" +
                                strftime('%Y'), "%m-%d-%Y")[0:3])
                            #convert the endDayRL string to a 'date' object
                            endDayRL = date(*strptime(
                                sinfo.endDayRL + "-" +
                                strftime('%Y'), "%m-%d-%Y")[0:3])
                            #Figure out what todays date is
                            todayRL = date.today()
                            if endDayRL < startDayRL:
                                #spawn crosses the year boundry
                                if endDayRL < todayRL < startDayRL:
                                    zone.removeMob(aMob)
                            elif not (startDayRL <= todayRL <= endDayRL):
                                #spawn doesn't cross year boundry
                                zone.removeMob(aMob)

    #end added code

            if not len(self.activeMobs):
                #we poofed so no delay
                self.delay = 0

        if len(self.activeMobs):
            return

        sinfo = self.getSpawnInfo()
        if sinfo:
            self.lifetime = sinfo.lifetime
            self.activeMobs = [
                zone.spawnMob(sinfo.spawn, self.transform, self.wanderGroup)
            ]
            self.activeMobs[0].spawnpoint = self
            self.activeInfo = sinfo

            if self.spawnGroupController:
                self.spawnGroupController.spawnAdded(self)
Пример #31
0
    def reset(self):
        self.friends = set()
        self.friendsInfo = {}
        self.mailList = {}
        self.lastMailID = 0        
        self.curChar = None
        self.zone = None
        self.avatar = None
        self.mind = None
        self.simObject = None
        self.cursorItem = None
        self.interacting = None
        self.dialog = None
        self.curDialogLine = None
        self.transfering = False
        self.cinfoDirty = True
        self.alliance = None
        
        self.textMessages = []
        self.textTicker = 0
        
        self.extract = True
        
        self.allianceTimeStamp = None
        
        #time, effect, cnames tuple
        self.resurrection = None
        #time, effect tuple
        self.resurrectionRequest = None

        
        self.realm = None
        self.telelink = None
        
        self.lastInnAddTime = sysTime()
        self.cserverInfos = None
        
        self.triggeredZoneOptions = []
        self.triggeredZoneLink = None
        self.invite = None
        self.name = self.fantasyName
        self.loggingOut = False
        self.trade = None
        self.world = None
        self.inn = None
        if self.party:
            for m in self.party.members:
                if m.mob:
                    m.mob.character = None
                    m.mob.player = None
                m.mob = None
        self.party = None
        self.rootInfo = None
        
        self.msgCombatNotCloseEnough = 0
        self.msgCombatCantSee = 0
        self.msgCombatNotFacing = 0
        
        self.trackingTimer = 0
        
        self.lastTell = None
        self.looting = None
        
        self.spellEffectCastTime = sysTime()
        self.spellEffectBeginTime = sysTime()
        
        self.bankList = None
        
        self.encounterSetting = RPG_ENCOUNTER_PVE
        
        # This gets set to True if the player party walks. Default is run.
        # Mobs have this handled specially and all player mobs in the same
        #  party are displayed by a single avatar. So it wouldn't make
        #  sense to put this somewhere else.
        self.walk = False
Пример #32
0
def Tick():
    global REBOOT_TIME, ANNOUNCE_MINUTE,FORCEKILL_TIME,ANNOUNCECALLBACK,KILLED,REBOOT,SPAWNED,ZONECLUSTERS
    
    reactor.callLater(15,Tick)
    
    if KILLED:
        if not len(ZoneClusterAvatar.avatars):
            if not REBOOT:
                reactor.stop()
            else:
                print "Rebooting"
                KILLED = False
                SpawnWorld()
        return
    
    #are we live?
    if SPAWNED:
        if not ANNOUNCECALLBACK and len(ZONECLUSTERS)==len(CLUSTERNAMES):
            for z in ZONECLUSTERS:
                if not z.live:
                    break
            else:
                SPAWNED = False
                AnnounceWorld()
    
    if FORCEKILL_TIME != None:
        if ANNOUNCECALLBACK:
            ANNOUNCECALLBACK.cancel()
            ANNOUNCECALLBACK = None
            
        
        minutes = int(ceil((FORCEKILL_TIME - sysTime())/60.0))
        if minutes<=0:
            FORCEKILL_TIME = None
            ANNOUNCE_MINUTE = -1
            REBOOT_TIME = sysTime()
            
            KILLED = True
            CServerAvatar.worldCSAvatars = {}
            for z in ZONECLUSTERS:
                z.killWorld()
            ZONECLUSTERS = []

            
        else:
            if minutes < 11 and ANNOUNCE_MINUTE!=minutes:
                if REBOOT:
                    print "Reboot in %i minutes"%minutes
                else:
                    print "Shutdown in %i minutes"%minutes
                    
                ANNOUNCE_MINUTE = minutes
                
                AnnounceShutdownReboot()
                
            
        
    
    elif sysTime()-REBOOT_TIME > 60*60*2: #if we haven't rebooted within the last 2 hours

        #automated reboot
        lt =  localtime()
        hour,minute =  lt[3],lt[4]
        
        nm = hour*60+minute
        rm = REBOOT_HOUR*60+REBOOT_MINUTE
        
        minutes = 0
        
        if rm > nm:
            minutes = rm-nm
        elif rm < nm:
            minutes = 24*60 - (nm-rm)
        
        if minutes < 0:
            minutes = 0
                        
        if minutes and minutes < 11 and ANNOUNCE_MINUTE != minutes:
            print "Reboot in %i minutes"%minutes
            ANNOUNCE_MINUTE = minutes
            if ANNOUNCECALLBACK:
                ANNOUNCECALLBACK.cancel()
                ANNOUNCECALLBACK = None
            AnnounceShutdownReboot()
            
        
        if hour == REBOOT_HOUR and minute >= REBOOT_MINUTE:
            ANNOUNCE_MINUTE = -1
            REBOOT_TIME = sysTime()
            KILLED = True
            REBOOT = True
            CServerAvatar.worldCSAvatars = {}

            for z in ZONECLUSTERS:                
                z.killWorld()
            ZONECLUSTERS = []
Пример #33
0
 def prepForZoneOut(self):
     self.encounterPreserveTimer = int(sysTime())
     self.backupItems()
Пример #34
0
 def setDelay(self,delay):
     self.delay = delay
     self.lastTick = sysTime()
Пример #35
0
def Tick():
    global REBOOT_TIME, ANNOUNCE_MINUTE, FORCEKILL_TIME, ANNOUNCECALLBACK, KILLED, REBOOT, SPAWNED, ZONECLUSTERS

    reactor.callLater(15, Tick)

    if KILLED:
        if not len(ZoneClusterAvatar.avatars):
            if not REBOOT:
                reactor.stop()
            else:
                print "Rebooting"
                KILLED = False
                SpawnWorld()
        return

    #are we live?
    if SPAWNED:
        if not ANNOUNCECALLBACK and len(ZONECLUSTERS) == len(CLUSTERNAMES):
            for z in ZONECLUSTERS:
                if not z.live:
                    break
            else:
                SPAWNED = False
                AnnounceWorld()

    if FORCEKILL_TIME != None:
        if ANNOUNCECALLBACK:
            ANNOUNCECALLBACK.cancel()
            ANNOUNCECALLBACK = None

        minutes = int(ceil((FORCEKILL_TIME - sysTime()) / 60.0))
        if minutes <= 0:
            FORCEKILL_TIME = None
            ANNOUNCE_MINUTE = -1
            REBOOT_TIME = sysTime()

            KILLED = True
            CServerAvatar.worldCSAvatars = {}
            for z in ZONECLUSTERS:
                z.killWorld()
            ZONECLUSTERS = []

        else:
            if minutes < 11 and ANNOUNCE_MINUTE != minutes:
                if REBOOT:
                    print "Reboot in %i minutes" % minutes
                else:
                    print "Shutdown in %i minutes" % minutes

                ANNOUNCE_MINUTE = minutes

                AnnounceShutdownReboot()

    elif sysTime(
    ) - REBOOT_TIME > 60 * 60 * 2:  #if we haven't rebooted within the last 2 hours

        #automated reboot
        lt = localtime()
        hour, minute = lt[3], lt[4]

        nm = hour * 60 + minute
        rm = REBOOT_HOUR * 60 + REBOOT_MINUTE

        minutes = 0

        if rm > nm:
            minutes = rm - nm
        elif rm < nm:
            minutes = 24 * 60 - (nm - rm)

        if minutes < 0:
            minutes = 0

        if minutes and minutes < 11 and ANNOUNCE_MINUTE != minutes:
            print "Reboot in %i minutes" % minutes
            ANNOUNCE_MINUTE = minutes
            if ANNOUNCECALLBACK:
                ANNOUNCECALLBACK.cancel()
                ANNOUNCECALLBACK = None
            AnnounceShutdownReboot()

        if hour == REBOOT_HOUR and minute >= REBOOT_MINUTE:
            ANNOUNCE_MINUTE = -1
            REBOOT_TIME = sysTime()
            KILLED = True
            REBOOT = True
            CServerAvatar.worldCSAvatars = {}

            for z in ZONECLUSTERS:
                z.killWorld()
            ZONECLUSTERS = []
Пример #36
0
    def __init__(self,zone,transform,group,wandergroup):
        self.activeMobs = []
        self.activeInfo = None
        self.lifetime = 0
        self.delay = 0
        self.despawnTime = 0
        self.transform = transform
        self.zone = zone
        self.wanderGroup = wandergroup
        self.lastTick = sysTime()
        self.lastCheckTicker = 0
        
        self.blocked = False
        self.spawnGroupController = None
        
        populator = False
        
        if group.startswith("POPULATOR_"):
            populator = True
            p,num = group.split("_")
            num = int(num)
            if zone.populatorGroups.has_key(num):
                group = zone.populatorGroups[num]
            else:
                groups = []
                fgroups = []
                gengroups = []
                for sg in zone.zone.spawnGroups:
                    if sg.targetName or sg.popFreq < 0:
                        continue
                    unique = False
                    for sinfo in sg.spawninfos:
                        if sinfo.spawn.flags&RPG_SPAWN_UNIQUE:
                            unique = True
                            break
                    if unique:
                        print "Warning: pop group contains a unique spawn",sg.groupName
                        continue

                    if "CMT_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif "PRT_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif "MGE_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif "RGE_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif sg.popFreq > 1:
                        fgroups.append(sg)
                    else:
                        groups.append(sg)
                
                if len(gengroups):
                    g = None
                    if len(gengroups) == 1:
                        g = gengroups[0]
                    else:
                        g = gengroups[randint(0,len(gengroups)-1)]
                    if g.popFreq > 1:
                        fgroups.append(g)
                    else:
                        groups.append(g)
                
                for g in fgroups:
                    if not randint(0,g.popFreq):
                        groups.append(g)

                if not len(groups):
                    groups.extend(fgroups)                
                
                if not len(groups):                    
                    print "WARNING!!!!! No spawn for populator %i"%num
                elif len(groups) == 1:
                    group = groups[0].groupName.upper()
                else:
                    group = groups[randint(0,len(groups) - 1)].groupName.upper()
                zone.populatorGroups[num] = group
        
        self.groupName = group
        
        self.spawngroup = None
        for sg in zone.zone.spawnGroups:
            if sg.groupName.upper() == group.upper():
                if sg.controllerInfo:
                    self.spawnGroupController = sg.controllerInfo.spawnGroupController
                    self.spawngroup = self.spawnGroupController.registerSpawnpoint(self,sg.controllerInfo)
                    self.groupName = self.spawngroup.groupName
                else:
                    self.spawngroup = sg
                break
        else:
            if not populator:
                print "WARNING!!!!! Cannot find %s SpawnGroup"%group
Пример #37
0
def RebootWorld(minutes=10):
    global FORCEKILL_TIME, REBOOT, ANNOUNCE_MINUTE
    FORCEKILL_TIME = sysTime() + minutes * 60
    REBOOT = True
    ANNOUNCE_MINUTE = minutes
    AnnounceShutdownReboot()
    def tick():    
            
        global TICK_COUNTER
        
        if not AVATAR:
            return #not official
        
        #error?
        if not AVATAR.mind:
            return 
        
        if AVATAR.world.shuttingDown:
            return
        
        try:

            now = sysTime()
            
            #ship off any player buffers from the last time
            
            try:
                from mud.worldserver.charutil import PLAYER_BUFFERS
                for pname,pbuffer,cbuffer,cvalues in PLAYER_BUFFERS[:]:
                    pbuf = encodestring(dumps(pbuffer, 2))
                    cbuf = None
                    if cbuffer:
                        cbuf = encodestring(dumps(cbuffer, 2))

                    print "Sending Player/Character buffers: %s (%ik/%ik)"%(pname,len(pbuf)/1024,len(cbuf)/1024)
                    AVATAR.mind.callRemote("savePlayerBuffer",pname,pbuf,cbuf,cvalues) #xxx add callback/errback
                    EXTRACT_TIMES[pname]=now
                    #should be removing these upon success
                    PLAYER_BUFFERS.remove((pname,pbuffer,cbuffer,cvalues))
            except:
                traceback.print_exc()
            
            
            TICK_COUNTER -= 3
            if TICK_COUNTER > 0:
                return
            
            TICK_COUNTER = 6 * 15 #once every minute
            
            pnames = []
            extractTarget = None
            best = 0
            for p in AVATAR.world.activePlayers:
                if not p.zone or p.enteringWorld:
                    continue
                
                pname = p.publicName
                pnames.append(pname)
                
                extractionTimer = EXTRACT_TIMES.setdefault(pname,now)
                t = now - extractionTimer
                
                if t < (60 * 10):
                    continue
                
                if t > best:
                    best = t
                    extractTarget = pname
            
            remove = []
            for k in EXTRACT_TIMES.iterkeys():
                if k not in pnames:
                    remove.append(k)
            map(EXTRACT_TIMES.__delitem__,remove)
            
            if extractTarget:
                p = Player.byPublicName(extractTarget) #already in active chars
                if p and p.party:
                    p.backupItems()
                    ExtractPlayer(p.publicName,p.id,p.party.members[0].id)
        except:
            traceback.print_exc()
        
        #send off all players
        
        try:
            pnames = []
            #it's still possible that the player is installed but isn't active
            #so 2 people sharing an account could still cause problems
            for p in AVATAR.world.activePlayers:
                cname = ""
                if p.curChar:
                    cname = p.curChar.name
                
                zname = ""
                if p.zone:
                    zname = p.zone.zone.niceName
                
                pnames.append((p.publicName,cname,p.guildName,zname))
            
            d = AVATAR.mind.callRemote("recordActivePlayers",AVATAR.world.multiName,pnames)
            d.addCallback(AVATAR.gotGlobalPlayers)
        
        except:
            traceback.print_exc()
Пример #39
0
 def remote_addToParty(self, cname):
     # Get a handle to the player.
     player = self.player
     
     # Do not allow a player to change party members while in a trade.
     if player.trade:
         player.sendGameText(RPG_MSG_GAME_DENIED,"You must finish a trade before using the Inn.\\n")
         return
     
     from mud.world.cserveravatar import AVATAR
     
     if AVATAR:
         if player.cserverInfos:
             for ci in player.cserverInfos:
                 if ci.rename == 2 and ci.name.lower() == cname.lower():
                     player.sendGameText(RPG_MSG_GAME_DENIED,"You must rename this character before bringing them into the game.  You can rename the character by logging in with them from the main world login screen.\\n")
                     return
         
         #should be on client
         if cname == player.party.members[0].name:
             return
         
         t = sysTime() - player.lastInnAddTime
         if t < 30:
             player.sendGameText(RPG_MSG_GAME_DENIED,"You can change characters in %i seconds.\\n"%(31-t))
             return
         
         player.lastInnAddTime = sysTime()
         
         d = AVATAR.mind.callRemote("getCharacterBuffer", \
                 player.publicName,cname)
         d.addCallback(self.gotCharacterBuffer,cname)
         return d
     
     else:
         try:
             c = Character.byName(cname)
         except:
             return
         
         if c.player != player:
             print "WARNING: Player at inn attempting to add a character that isn't theres!"
             return
         
         if len(player.party.members) == 6:
             return
         
         if len(player.party.members) >= CoreSettings.MAXPARTY:
             player.sendGameText(RPG_MSG_GAME_DENIED,"This world allows at most %i characters in your party.\\n"%(CoreSettings.MAXPARTY))
             return
         
         if c in player.party.members:
             return
         
         #add the character!!!!
         player.party.addCharacter(c)
         
         # Monsters don't like to party...
         if player.realm == RPG_REALM_MONSTER:
             for member in player.party.members:
                 if member != c:
                     player.party.removeCharacter(member)
             player.sendGameText(RPG_MSG_GAME_EVENT, \
                                      "Rawr! Monsters don't like to party.\\n")
         
         player.alliance.allianceInfo.refresh()
         
         self.sendLists()
         return
Пример #40
0
 def __init__(self):
     self.remoteFriendsInfo = {}
     self.active = []
     self.lastSoundTime = sysTime() - 15
Пример #41
0
    def __init__(self, zone, transform, group, wandergroup):
        self.activeMobs = []
        self.activeInfo = None
        self.lifetime = 0
        self.delay = 0
        self.despawnTime = 0
        self.transform = transform
        self.zone = zone
        self.wanderGroup = wandergroup
        self.lastTick = sysTime()
        self.lastCheckTicker = 0

        self.blocked = False
        self.spawnGroupController = None

        populator = False

        if group.startswith("POPULATOR_"):
            populator = True
            p, num = group.split("_")
            num = int(num)
            if zone.populatorGroups.has_key(num):
                group = zone.populatorGroups[num]
            else:
                groups = []
                fgroups = []
                gengroups = []
                for sg in zone.zone.spawnGroups:
                    if sg.targetName or sg.popFreq < 0:
                        continue
                    unique = False
                    for sinfo in sg.spawninfos:
                        if sinfo.spawn.flags & RPG_SPAWN_UNIQUE:
                            unique = True
                            break
                    if unique:
                        print "Warning: pop group contains a unique spawn", sg.groupName
                        continue

                    if "CMT_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif "PRT_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif "MGE_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif "RGE_RANK" in sg.groupName:
                        gengroups.append(sg)
                    elif sg.popFreq > 1:
                        fgroups.append(sg)
                    else:
                        groups.append(sg)

                if len(gengroups):
                    g = None
                    if len(gengroups) == 1:
                        g = gengroups[0]
                    else:
                        g = gengroups[randint(0, len(gengroups) - 1)]
                    if g.popFreq > 1:
                        fgroups.append(g)
                    else:
                        groups.append(g)

                for g in fgroups:
                    if not randint(0, g.popFreq):
                        groups.append(g)

                if not len(groups):
                    groups.extend(fgroups)

                if not len(groups):
                    print "WARNING!!!!! No spawn for populator %i" % num
                elif len(groups) == 1:
                    group = groups[0].groupName.upper()
                else:
                    group = groups[randint(0,
                                           len(groups) - 1)].groupName.upper()
                zone.populatorGroups[num] = group

        self.groupName = group

        self.spawngroup = None
        for sg in zone.zone.spawnGroups:
            if sg.groupName.upper() == group.upper():
                if sg.controllerInfo:
                    self.spawnGroupController = sg.controllerInfo.spawnGroupController
                    self.spawngroup = self.spawnGroupController.registerSpawnpoint(
                        self, sg.controllerInfo)
                    self.groupName = self.spawngroup.groupName
                else:
                    self.spawngroup = sg
                break
        else:
            if not populator:
                print "WARNING!!!!! Cannot find %s SpawnGroup" % group
Пример #42
0
    def playerEnterZone(self, player):

        if not player.world:
            print "WARNING: Player Entering Zone not attached to world... probably lost connection to world while zoning in"
            return

        player.zone.simAvatar.setDisplayName(player)

        # announce to other players
        if player.role.name not in ("Guardian", "Immortal"):
            if player.enteringWorld:
                for p in self.players:
                    p.sendGameText(RPG_MSG_GAME_BLUE, \
                        r'%s has entered the zone.\n'%player.charName)
                for p in player.world.activePlayers:
                    if p == player:
                        continue
                    if p.enteringWorld:
                        continue
                    if p in self.players:  #already told that we entered zone
                        continue
                    p.sendGameText(RPG_MSG_GAME_BLUE, \
                        r'%s has entered the world.\n'%player.charName)
            else:
                pmob = player.curChar.mob
                for p in self.players:
                    if AllowHarmful(pmob, p.curChar.mob):
                        continue
                    p.sendGameText(RPG_MSG_GAME_BLUE, \
                        r'%s has entered the zone.\n'%player.charName)

        # If the player was logging in and not zoning, we still need to reset
        #  the flag denoting him/her entering the world.
        player.enteringWorld = False

        #we use queue to keep dynamic zones alive
        try:
            del self.playerQueue[player]
        except KeyError:
            pass

        # Check if encounter setting will be preserved or not
        #  yeah, 5 minutes are long, this is just to make sure ...
        if sysTime() - player.encounterPreserveTimer < 300:
            player.mind.callRemote("checkEncounterSetting", True)
        player.encounterPreserveTimer = 0
        player.encounterSetting = RPG_ENCOUNTER_PVE  # go safe until required otherwise

        self.players.append(player)

        for c in player.party.members:
            # Get a handle to this Character's Mob.
            mob = c.mob
            # Add the Mob to the Mob lookup table. Even if the player
            #  has multiple Characters in the party, there will be only
            #  one lookup table entry.
            self.mobLookup[player.simObject] = mob
            # Set the Mob's simulation object.
            mob.simObject = player.simObject
            # Append this Mob to this Zone's list of active Mobs.
            self.activeMobs.append(mob)

            # If the Character zoned in dead, detach the Mob again.
            if c.dead:
                self.detachMob(mob)

        # If this world doesn't allow more than a single party member,
        #  then set the death marker of the zoned in Player.
        if CoreSettings.MAXPARTY == 1:
            player.world.setDeathMarker(player, player.party.members[0])

        if CoreSettings.PGSERVER:
            player.world.sendCharacterInfo(player)
Пример #43
0
 def setDelay(self, delay):
     self.delay = delay
     self.lastTick = sysTime()
Пример #44
0
    def tick(self):
        if not self.running:
            return

        reactor.callLater(.5, self.tick)  #2x sec

        if False:  #CoreSettings.PGSERVER:
            if len(self.liveZoneInstances) == len(
                    self.staticZoneNames) and self.allowConnections:
                if not len(self.activePlayers) and self.priority:
                    self.priority = 0
                    win32process.SetPriorityClass(
                        win32process.GetCurrentProcess(),
                        win32process.IDLE_PRIORITY_CLASS)

                if len(self.activePlayers) and not self.priority:
                    self.priority = 1
                    win32process.SetPriorityClass(
                        win32process.GetCurrentProcess(),
                        win32process.NORMAL_PRIORITY_CLASS)

                #if not self.priority:
                #    win32api.Sleep(2000)
            elif not self.priority:
                self.priority = 1
                win32process.SetPriorityClass(
                    win32process.GetCurrentProcess(),
                    win32process.NORMAL_PRIORITY_CLASS)

        if False:  #RPG_BUILD_DEMO:
            t = sysTime() - self.pauseTime
            if 13 * 60 >= t >= 12 * 60:
                self.paused = True
            elif t > 13 * 60:
                self.paused = False
                self.pauseTime = sysTime()
            else:
                self.paused = False

        self.time.tick()

        #store in db
        if self.time.hour != self.hour:
            self.minute = self.time.minute
            self.hour = self.time.hour
            self.day = self.time.day

        CharacterServerAvatar.tick()

        #if self.lasttime == -1:
        #    self.lasttime = sysTime()-2
        #delta = sysTime()-self.lasttime

        #if delta > .5:
        #self.lasttime = sysTime()

        if CoreSettings.PGSERVER:
            if self.isShuttingDown:
                self.cpuSpawn = 0
                self.cpuDespawn = 0
            else:
                self.cpuSpawn = 4
                self.cpuDespawn = 8
        else:
            self.cpuSpawn = 1000000
            self.cpuDespawn = 1000000

        # Select the zone which will be allowed to spawn mobs.
        spawnZone = None
        if len(self.liveZoneInstances) > 0:
            if self.spawnZoneIndex > len(self.liveZoneInstances) - 1:
                self.spawnZoneIndex = 0
            spawnZone = self.liveZoneInstances[self.spawnZoneIndex]
            self.spawnZoneIndex += 1

        # Tick all live zone instances.
        for z in self.liveZoneInstances:
            z.tick(spawnZone)

        #weed out dynamic zones that haven't any players for x amount of time
        #we need to weed out failed zones (stuck in waiting, etc)

        if not self.singlePlayer:
            timedOut = []
            for z in self.liveZoneInstances:
                if not z.dynamic:
                    continue
                if not len(z.players) and not len(z.playerQueue):
                    if z.timeOut == -1:
                        z.timeOut = sysTime()
                    elif (sysTime() - z.timeOut) / 60 > 20:  # 20 minutes
                        timedOut.append(z)

                else:
                    z.timeOut = -1

            for z in timedOut:
                self.closeZone(z)

        # Backup single player data every minute.
        else:
            self.singlePlayerBackupTimer -= 1
            if self.singlePlayerBackupTimer < 0:
                # Reset timer to one minute.
                self.singlePlayerBackupTimer = 120

                for player in self.activePlayers:
                    # If there's no party, player hasn't logged in yet and
                    #  there's no need to back up.
                    if player.party:
                        player.backupPlayer()

                # Force a write to database.
                conn = Persistent._connection.getConnection()
                cursor = conn.cursor()
                cursor.execute("END;")
                cursor.execute("BEGIN;")
                cursor.close()
Пример #45
0
 def wrapper(*a, **k):
     start=sysTime()
     retval=fct(*a, **k)
     elapsed=sysTime()-start
     return (retval, elapsed)
Пример #46
0
    print "Usage: WorldDaemon -worldname=MYWORLD -publicname=MYPUBLICNAME -password=MYPASSWORD"
    raise "Incorrect Usage"



class BadConnectionError(Exception):
    def __str__(self):
        return "Bad Connection"



#military time!
REBOOT = True
REBOOT_HOUR = 3
REBOOT_MINUTE = 0
REBOOT_TIME = sysTime()
ANNOUNCE_MINUTE = -1

FORCEKILL_TIME = None

KILLED = False

SPAWNED = False

def AnnounceShutdownReboot():
    for z in ZONECLUSTERS:
        try:
            if REBOOT:
                z.mind.callRemote("announceReboot",ANNOUNCE_MINUTE)
            else:
                z.mind.callRemote("announceShutdown",ANNOUNCE_MINUTE)