def ConnectToDatabase(self): configurator = Configurator(world) cfg = configurator.config conn = MySQLdb.Connection( host=cfg['host'], user=cfg['user'], passwd=cfg['password'], db=cfg['db']) return conn
def __init__(self, process_pk): process = Process.objects.get(pk=process_pk) self.cfg = Configurator() self.max_outstanding = self.cfg.getint('MPROCESSOR', 'max_outstanding') self.batch_size = self.cfg.getint('MPROCESSOR', 'batch_size') # how many items to load self.pipeline = loads(process.pipeline.params) self.dag = DAG(self.pipeline) self.schedule_length = len(self.pipeline) self.process = process self.scripts = self._get_scripts(self.pipeline) self.all_targets_read = False # True when all targets have been read self.gameover = False # True when all targets are done self.outstanding = 0 # number of not yet answered requests self.cur_batch = 0 # index in batch self.cur_task = 0 # index in tasks self.totals = {'update':0, 'passed':0, 'failed':0, 'targets': 0, None: 0} self.results = {}
class Storage: def __init__(self): self.c = Configurator() self._root = os.path.normpath(self.c.get('STORAGE', 'cache_dir')) def exists(self, filename): if filename != None: return os.path.exists(self.abspath(filename)) else: log.debug('inside MProcessor storage, method exists, filename is %s' % filename) return False def abspath(self, path, in_cache=False): """absolute path of path, relative to the cache_dir defined in mprocessor.cfg If the argument path is already an absolute path, returns it unchanged, unless in_cache = True. In this case raise an exception unless path points inside cache_dir """ if os.path.isabs(path): abs = path else: abs = os.path.abspath(os.path.join(self._root, path)) abs = normpath(abs) if in_cache: if not abs.startswith(self._root): raise StorageError('%s is not under %s' % (abs, self._root)) return abs def relpath(self, path, in_cache=False): """ This is the inverse of abspath """ path = os.path.abspath(path) path = normpath(path) rel = os.path.relpath(path, self._root) if in_cache: if rel.startswith('..'): raise StorageError('%s is not under %s' % (path, self._root)) else: return rel
from flask_script import Manager, Shell import os CONFIG_KEY = os.getenv('KRABBY_CONFIG') or 'default' from config import Configurator # noqa Configurator.configure() Configurator.set_logging(name=CONFIG_KEY, console_logging=True) from config import logger # noqa from webapp import dba, models, create_app # noqa app = create_app(CONFIG_KEY) app_ctx = app.app_context() app_ctx.push() manager = Manager(app) # ___________________________________________ def make_shell_context(): context = {} context.update(dict(app=app, dba=dba, models=models)) return context # ___________________________________________ manager.add_command("shell", Shell(make_context=make_shell_context, use_ipython=True)) # ___________________________________________
def __init__(self): self.last_mousex = 0 self.last_mousey = 0 self.zone = None self.zone_reload_name = None self.winprops = WindowProperties() # simple console output self.consoleNode = NodePath(PandaNode("console_root")) self.consoleNode.reparentTo(aspect2d) self.console_num_lines = 24 self.console_cur_line = -1 self.console_lines = [] for i in range(0, self.console_num_lines): self.console_lines.append( OnscreenText( text="", style=1, fg=(1, 1, 1, 1), pos=(-1.3, 0.4 - i * 0.05), align=TextNode.ALeft, scale=0.035, parent=self.consoleNode, ) ) # Configuration self.consoleOut("zonewalk v.%s loading configuration" % VERSION) self.configurator = Configurator(self) cfg = self.configurator.config resaveRes = False if "xres" in cfg: self.xres = int(cfg["xres"]) else: self.xres = 1024 resaveRes = True if "yres" in cfg: self.yres = int(cfg["yres"]) else: self.yres = 768 resaveRes = True if resaveRes: self.saveDefaultRes() self.xres_half = self.xres / 2 self.yres_half = self.yres / 2 self.mouse_accum = MouseAccume(lambda: (self.xres_half, self.yres_half)) self.eyeHeight = 7.0 self.rSpeed = 80 self.flyMode = 1 # application window setup base.win.setClearColor(Vec4(0, 0, 0, 1)) self.winprops.setTitle("zonewalk") self.winprops.setSize(self.xres, self.yres) base.win.requestProperties(self.winprops) base.disableMouse() # network test stuff self.login_client = None if "testnet" in cfg: if cfg["testnet"] == "1": self.doLogin() # Post the instructions self.title = addTitle("zonewalk v." + VERSION) self.inst0 = addInstructions(0.95, "[FLYMODE][1]") self.inst1 = addInstructions(-0.95, "Camera control with WSAD/mouselook. Press K for hotkey list, ESC to exit.") self.inst2 = addInstructions(0.9, "Loc:") self.inst3 = addInstructions(0.85, "Hdg:") self.error_inst = addInstructions(0, "") self.kh = [] self.campos = Point3(155.6, 41.2, 4.93) base.camera.setPos(self.campos) # Accept the application control keys: currently just esc to exit navgen self.accept("escape", self.exitGame) self.accept("window-event", self.resizeGame) # Create some lighting ambient_level = 0.6 ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(ambient_level, ambient_level, ambient_level, 1.0)) render.setLight(render.attachNewNode(ambientLight)) direct_level = 0.8 directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0.0, 0.0, -1.0)) directionalLight.setColor(Vec4(direct_level, direct_level, direct_level, 1)) directionalLight.setSpecularColor(Vec4(direct_level, direct_level, direct_level, 1)) render.setLight(render.attachNewNode(directionalLight)) # create a point light that will follow our view point (the camera for now) # attenuation is set so that this point light has a torch like effect self.plight = PointLight("plight") self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1.0)) self.plight.setAttenuation(Point3(0.0, 0.0, 0.0002)) self.plnp = base.camera.attachNewNode(self.plight) self.plnp.setPos(0, 0, 0) render.setLight(self.plnp) self.cam_light = 1 self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "mouse3": 0, "flymode": 1, } # setup FOG self.fog_colour = (0.8, 0.8, 0.8, 1.0) self.linfog = Fog("A linear-mode Fog node") self.linfog.setColor(self.fog_colour) self.linfog.setLinearRange(700, 980) # onset, opaque distances as params # linfog.setLinearFallback(45,160,320) base.camera.attachNewNode(self.linfog) render.setFog(self.linfog) self.fog = 1 # camera control self.campos = Point3(0, 0, 0) self.camHeading = 0.0 self.camPitch = 0.0 base.camLens.setFov(65.0) base.camLens.setFar(1200) self.cam_speed = 0 # index into self.camp_speeds self.cam_speeds = [40.0, 80.0, 160.0, 320.0, 640.0] # Collision Detection for "WALKMODE" # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. The ray will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0.0, 0.0, 0.0) self.camGroundRay.setDirection(0, 0, -1) # straight down self.camGroundCol = CollisionNode("camRay") self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) # attach the col node to the camCollider dummy node self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Add the spinCameraTask procedure to the task manager. # taskMgr.add(self.spinCameraTask, "SpinCameraTask") taskMgr.add(self.camTask, "camTask") self.toggleControls(1) # need to step the task manager once to make our fake console work taskMgr.step()
class World(DirectObject): def __init__(self): self.last_mousex = 0 self.last_mousey = 0 self.zone = None self.zone_reload_name = None self.winprops = WindowProperties() # simple console output self.consoleNode = NodePath(PandaNode("console_root")) self.consoleNode.reparentTo(aspect2d) self.console_num_lines = 24 self.console_cur_line = -1 self.console_lines = [] for i in range(0, self.console_num_lines): self.console_lines.append( OnscreenText( text="", style=1, fg=(1, 1, 1, 1), pos=(-1.3, 0.4 - i * 0.05), align=TextNode.ALeft, scale=0.035, parent=self.consoleNode, ) ) # Configuration self.consoleOut("zonewalk v.%s loading configuration" % VERSION) self.configurator = Configurator(self) cfg = self.configurator.config resaveRes = False if "xres" in cfg: self.xres = int(cfg["xres"]) else: self.xres = 1024 resaveRes = True if "yres" in cfg: self.yres = int(cfg["yres"]) else: self.yres = 768 resaveRes = True if resaveRes: self.saveDefaultRes() self.xres_half = self.xres / 2 self.yres_half = self.yres / 2 self.mouse_accum = MouseAccume(lambda: (self.xres_half, self.yres_half)) self.eyeHeight = 7.0 self.rSpeed = 80 self.flyMode = 1 # application window setup base.win.setClearColor(Vec4(0, 0, 0, 1)) self.winprops.setTitle("zonewalk") self.winprops.setSize(self.xres, self.yres) base.win.requestProperties(self.winprops) base.disableMouse() # network test stuff self.login_client = None if "testnet" in cfg: if cfg["testnet"] == "1": self.doLogin() # Post the instructions self.title = addTitle("zonewalk v." + VERSION) self.inst0 = addInstructions(0.95, "[FLYMODE][1]") self.inst1 = addInstructions(-0.95, "Camera control with WSAD/mouselook. Press K for hotkey list, ESC to exit.") self.inst2 = addInstructions(0.9, "Loc:") self.inst3 = addInstructions(0.85, "Hdg:") self.error_inst = addInstructions(0, "") self.kh = [] self.campos = Point3(155.6, 41.2, 4.93) base.camera.setPos(self.campos) # Accept the application control keys: currently just esc to exit navgen self.accept("escape", self.exitGame) self.accept("window-event", self.resizeGame) # Create some lighting ambient_level = 0.6 ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(ambient_level, ambient_level, ambient_level, 1.0)) render.setLight(render.attachNewNode(ambientLight)) direct_level = 0.8 directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0.0, 0.0, -1.0)) directionalLight.setColor(Vec4(direct_level, direct_level, direct_level, 1)) directionalLight.setSpecularColor(Vec4(direct_level, direct_level, direct_level, 1)) render.setLight(render.attachNewNode(directionalLight)) # create a point light that will follow our view point (the camera for now) # attenuation is set so that this point light has a torch like effect self.plight = PointLight("plight") self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1.0)) self.plight.setAttenuation(Point3(0.0, 0.0, 0.0002)) self.plnp = base.camera.attachNewNode(self.plight) self.plnp.setPos(0, 0, 0) render.setLight(self.plnp) self.cam_light = 1 self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "mouse3": 0, "flymode": 1, } # setup FOG self.fog_colour = (0.8, 0.8, 0.8, 1.0) self.linfog = Fog("A linear-mode Fog node") self.linfog.setColor(self.fog_colour) self.linfog.setLinearRange(700, 980) # onset, opaque distances as params # linfog.setLinearFallback(45,160,320) base.camera.attachNewNode(self.linfog) render.setFog(self.linfog) self.fog = 1 # camera control self.campos = Point3(0, 0, 0) self.camHeading = 0.0 self.camPitch = 0.0 base.camLens.setFov(65.0) base.camLens.setFar(1200) self.cam_speed = 0 # index into self.camp_speeds self.cam_speeds = [40.0, 80.0, 160.0, 320.0, 640.0] # Collision Detection for "WALKMODE" # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. The ray will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0.0, 0.0, 0.0) self.camGroundRay.setDirection(0, 0, -1) # straight down self.camGroundCol = CollisionNode("camRay") self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) # attach the col node to the camCollider dummy node self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Add the spinCameraTask procedure to the task manager. # taskMgr.add(self.spinCameraTask, "SpinCameraTask") taskMgr.add(self.camTask, "camTask") self.toggleControls(1) # need to step the task manager once to make our fake console work taskMgr.step() # CONSOLE --------------------------------------------------------------------- def consoleScroll(self): for i in range(0, self.console_num_lines - 1): self.console_lines[i].setText(self.console_lines[i + 1].getText()) def consoleOut(self, text): print text # output to stdout/log too if self.console_cur_line == self.console_num_lines - 1: self.consoleScroll() elif self.console_cur_line < self.console_num_lines - 1: self.console_cur_line += 1 self.console_lines[self.console_cur_line].setText(text) taskMgr.step() def consoleOn(self): self.consoleNode.show() def consoleOff(self): self.consoleNode.hide() # User controls ----------------------------------------------------------- def toggleControls(self, on): if on == 1: self.accept("escape", self.exitGame) self.accept("1", self.setSpeed, ["speed", 0]) self.accept("2", self.setSpeed, ["speed", 1]) self.accept("3", self.setSpeed, ["speed", 2]) self.accept("4", self.setSpeed, ["speed", 3]) self.accept("5", self.setSpeed, ["speed", 4]) self.accept("alt-f", self.fogToggle) self.accept("t", self.camLightToggle) self.accept("k", self.displayKeyHelp) self.accept("f", self.toggleFlymode) self.accept("l", self.reloadZone) self.accept("z", self.saveDefaultZone) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("d", self.setKey, ["cam-right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("mouse1", self.setKey, ["forward", 1]) self.accept("mouse3", self.setKey, ["mouse3", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("k-up", self.hideKeyHelp) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("d-up", self.setKey, ["cam-right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("mouse1-up", self.setKey, ["forward", 0]) self.accept("mouse3-up", self.setKey, ["mouse3", 0]) self.accept("s-up", self.setKey, ["backward", 0]) else: messenger.clear() def setSpeed(self, key, value): self.cam_speed = value self.setFlymodeText() def fogToggle(self): if self.fog == 1: render.clearFog() base.camLens.setFar(100000) self.fog = 0 else: render.setFog(self.linfog) base.camLens.setFar(1200) self.fog = 1 def camLightToggle(self): if self.cam_light == 0: render.setLight(self.plnp) self.cam_light = 1 else: render.clearLight(self.plnp) self.cam_light = 0 def displayKeyHelp(self): self.kh = [] msg = "HOTKEYS:" pos = 0.75 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "------------------" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "W: camera fwd, S: camera bck, A: rotate view left, D: rotate view right" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "1-5: set camera movement speed" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "F: toggle Flymode/Walkmode" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "L: load a zone" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "ALT-F: toggle FOG and FAR plane on/off" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = 'T: toggle additional camera "torch" light on/off' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "Z: set currently loaded zone as new startup default" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) msg = "ESC: exit zonewalk" pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=0.04) ) def hideKeyHelp(self): for n in self.kh: n.removeNode() def setFlymodeText(self): zname = "" if self.zone: zname = self.zone.name if self.flyMode == 0: self.inst0.setText("[WALKMODE][%i] %s" % (self.cam_speed + 1, zname)) else: self.inst0.setText("[FLYMODE][%i] %s " % (self.cam_speed + 1, zname)) def toggleFlymode(self): zname = "" if self.zone: zname = self.zone.name if self.flyMode == 0: self.flyMode = 1 else: self.flyMode = 0 self.setFlymodeText() # Define a procedure to move the camera. def spinCameraTask(self, task): angleDegrees = task.time * 6.0 angleRadians = angleDegrees * (pi / 180.0) base.camera.setPos(20 * sin(angleRadians), -20.0 * cos(angleRadians), 3) base.camera.setHpr(angleDegrees, 0, 0) return task.cont def camTask(self, task): # query the mouse mouse_dx = 0 mouse_dy = 0 # if we have a mouse and the right button is depressed if base.mouseWatcherNode.hasMouse(): if self.keyMap["mouse3"] != 0: self.mouse_accum.update() else: self.mouse_accum.reset() mouse_dx = self.mouse_accum.dx mouse_dy = self.mouse_accum.dy self.rXSpeed = fabs(self.mouse_accum.dx) * (self.cam_speed + 1) * max(5 * 1000 / self.xres, 3) self.rYSpeed = fabs(self.mouse_accum.dy) * (self.cam_speed + 1) * max(3 * 1000 / self.yres, 1) if self.keyMap["cam-left"] != 0 or mouse_dx < 0: if self.rSpeed < 160: self.rSpeed += 80 * globalClock.getDt() if mouse_dx != 0: self.camHeading += self.rXSpeed * globalClock.getDt() else: self.camHeading += self.rSpeed * globalClock.getDt() if self.camHeading > 360.0: self.camHeading = self.camHeading - 360.0 elif self.keyMap["cam-right"] != 0 or mouse_dx > 0: if self.rSpeed < 160: self.rSpeed += 80 * globalClock.getDt() if mouse_dx != 0: self.camHeading -= self.rXSpeed * globalClock.getDt() else: self.camHeading -= self.rSpeed * globalClock.getDt() if self.camHeading < 0.0: self.camHeading = self.camHeading + 360.0 else: self.rSpeed = 80 if mouse_dy > 0: self.camPitch += self.rYSpeed * globalClock.getDt() elif mouse_dy < 0: self.camPitch -= self.rYSpeed * globalClock.getDt() # set camera heading and pitch base.camera.setHpr(self.camHeading, self.camPitch, 0) # viewer position (camera) movement control v = render.getRelativeVector(base.camera, Vec3.forward()) if not self.flyMode: v.setZ(0.0) move_speed = self.cam_speeds[self.cam_speed] if self.keyMap["forward"] == 1: self.campos += v * move_speed * globalClock.getDt() if self.keyMap["backward"] == 1: self.campos -= v * move_speed * globalClock.getDt() # actually move the camera lastPos = base.camera.getPos() base.camera.setPos(self.campos) # self.plnp.setPos(self.campos) # move the point light with the viewer position # WALKMODE: simple collision detection # we simply check a ray from slightly below the "eye point" straight down # for geometry collisions and if there are any we detect the point of collision # and adjust the camera's Z accordingly if self.flyMode == 0: # move the camera to where it would be if it made the move # the colliderNode moves with it # base.camera.setPos(self.campos) # check for collissons self.cTrav.traverse(render) entries = [] for i in range(self.camGroundHandler.getNumEntries()): entry = self.camGroundHandler.getEntry(i) entries.append(entry) # print 'collision' entries.sort(lambda x, y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if len(entries) > 0: # and (entries[0].getIntoNode().getName() == "terrain"): # print len(entries) self.campos.setZ(entries[0].getSurfacePoint(render).getZ() + self.eyeHeight) else: self.campos = lastPos base.camera.setPos(self.campos) # if (base.camera.getZ() < self.player.getZ() + 2.0): # base.camera.setZ(self.player.getZ() + 2.0) # update loc and hpr display pos = base.camera.getPos() hpr = base.camera.getHpr() self.inst2.setText("Loc: %.2f, %.2f, %.2f" % (pos.getX(), pos.getY(), pos.getZ())) self.inst3.setText("Hdg: %.2f, %.2f, %.2f" % (hpr.getX(), hpr.getY(), hpr.getZ())) return task.cont def exitGame(self): sys.exit(0) def resizeGame(self, win): props = base.win.getProperties() self.xres = props.getXSize() self.yres = props.getYSize() self.xres_half = self.xres / 2 self.yres_half = self.yres / 2 self.saveDefaultRes() # Records the state of the arrow keys # this is used for camera control def setKey(self, key, value): self.keyMap[key] = value # ------------------------------------------------------------------------- # this is the mythical MAIN LOOP :) def update(self): if self.zone_reload_name != None: self.doReload(self.zone_reload_name) self.zone_reload_name = None if self.zone != None: self.zone.update() taskMgr.step() if self.login_client != None: self.login_client.update() # ZONE loading ------------------------------------------------------------ # general zone loader driver # removes existing zone (if any) and load the new one def loadZone(self, name, path): if path[len(path) - 1] != "/": path += "/" if self.zone: self.zone.rootNode.removeNode() self.zone = Zone(self, name, path) error = self.zone.load() if error == 0: self.consoleOff() self.setFlymodeText() base.setBackgroundColor(self.fog_colour) def saveDefaultRes(self): cfg = self.configurator.config cfg["xres"] = str(self.xres) cfg["yres"] = str(self.yres) self.configurator.saveConfig() # initial world load after bootup def load(self): cfg = self.configurator.config if self.login_client != None: return zone_name = cfg["default_zone"] basepath = cfg["basepath"] self.loadZone(zone_name, basepath) # config save user interfacce def saveDefaultZone(self): if self.zone: cfg = self.configurator.config cfg["default_zone"] = self.zone.name self.configurator.saveConfig() # zone reload user interface # this gets called from our update loop when it detects that zone_reload_name has been set # we do this in this convoluted fashion in order to keep the main loop taskMgr updates ticking # because otherwise our status console output at various stages during the zone load would not # be displayed. Yes, this is hacky. def doReload(self, name): cfg = self.configurator.config basepath = cfg["basepath"] self.loadZone(name, basepath) # form dialog callback # this gets called from the form when the user has entered a something # (hopefully a correct zone short name) def reloadZoneDialogCB(self, name): self.frmDialog.end() self.zone_reload_name = name self.toggleControls(1) # this is called when the user presses "l" # it disables normal controls and fires up our query form dialog def reloadZone(self): base.setBackgroundColor((0, 0, 0)) self.toggleControls(0) self.consoleOn() self.frmDialog = FileDialog( "Please enter the shortname of the zone you wish to load:", "Examples: qrg, blackburrow, freportn, crushbone etc.", self.reloadZoneDialogCB, ) self.frmDialog.activate() # relies on the main update loop to run ############################### # EXPERIMENTAL def doLogin(self): self.login_client = UDPClientStream("127.0.0.1", 5998)
def __init__(self): self.last_mousex = 0 self.last_mousey = 0 self.zone = None self.zone_reload_name = None self.winprops = WindowProperties( ) # simple console output self.consoleNode = NodePath(PandaNode("console_root")) self.consoleNode.reparentTo(aspect2d) self.console_num_lines = 24 self.console_cur_line = -1 self.console_lines = [] for i in range(0, self.console_num_lines): self.console_lines.append(OnscreenText(text='', style=1, fg=(1,1,1,1), pos=(-1.3, .4-i*.05), align=TextNode.ALeft, scale = .035, parent = self.consoleNode)) # Configuration self.consoleOut('World Forge v.%s loading configuration' % VERSION) self.configurator = Configurator(self) cfg = self.configurator.config resaveRes = False if 'xres' in cfg: self.xres = int(cfg['xres']) else: self.xres = 1024 resaveRes = True if 'yres' in cfg: self.yres = int(cfg['yres']) else: self.yres = 768 resaveRes = True if resaveRes: self.saveDefaultRes() self.xres_half = self.xres / 2 self.yres_half = self.yres / 2 self.mouse_accum = MouseAccume( lambda: (self.xres_half,self.yres_half)) self.eyeHeight = 7.0 self.rSpeed = 80 self.flyMode = 1 # application window setup base.win.setClearColor(Vec4(0,0,0,1)) self.winprops.setTitle( 'World Forge') self.winprops.setSize(self.xres, self.yres) base.win.requestProperties( self.winprops ) base.disableMouse() # Post the instructions self.title = addTitle('World Forge v.' + VERSION) self.inst0 = addInstructions(0.95, "[FLYMODE][1]") self.inst1 = addInstructions(-0.95, "Camera control with WSAD/mouselook. Press K for hotkey list, ESC to exit.") self.inst2 = addInstructions(0.9, "Loc:") self.inst3 = addInstructions(0.85, "Hdg:") self.error_inst = addInstructions(0, '') self.kh = [] self.campos = Point3(155.6, 41.2, 4.93) base.camera.setPos(self.campos) # Accept the application control keys: currently just esc to exit navgen self.accept("escape", self.exitGame) self.accept("window-event", self.resizeGame) # Create some lighting ambient_level = .6 ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(ambient_level, ambient_level, ambient_level, 1.0)) render.setLight(render.attachNewNode(ambientLight)) direct_level = 0.8 directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0.0, 0.0, -1.0)) directionalLight.setColor(Vec4(direct_level, direct_level, direct_level, 1)) directionalLight.setSpecularColor(Vec4(direct_level, direct_level, direct_level, 1)) render.setLight(render.attachNewNode(directionalLight)) # create a point light that will follow our view point (the camera for now) # attenuation is set so that this point light has a torch like effect self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1.0)) self.plight.setAttenuation(Point3(0.0, 0.0, 0.0002)) self.plnp = base.camera.attachNewNode(self.plight) self.plnp.setPos(0, 0, 0) render.setLight(self.plnp) self.cam_light = 1 self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, \ "cam-right":0, "mouse3":0, "flymode":1 } # setup FOG self.fog_colour = (0.8,0.8,0.8,1.0) self.linfog = Fog("A linear-mode Fog node") self.linfog.setColor(self.fog_colour) self.linfog.setLinearRange(700, 980) # onset, opaque distances as params # linfog.setLinearFallback(45,160,320) base.camera.attachNewNode(self.linfog) render.setFog(self.linfog) self.fog = 1 # camera control self.campos = Point3(0, 0, 0) self.camHeading = 0.0 self.camPitch = 0.0 base.camLens.setFov(65.0) base.camLens.setFar(1200) self.cam_speed = 0 # index into self.camp_speeds self.cam_speeds = [40.0, 80.0, 160.0, 320.0, 640.0] # Collision Detection for "WALKMODE" # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. The ray will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0.0, 0.0, 0.0) self.camGroundRay.setDirection(0,0,-1) # straight down self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) # attach the col node to the camCollider dummy node self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Add the spinCameraTask procedure to the task manager. # taskMgr.add(self.spinCameraTask, "SpinCameraTask") globals.hasClickedSpawn = False; globals.hasClickedGrid = False; taskMgr.add(self.camTask, "camTask") self.toggleControls(1) # need to step the task manager once to make our fake console work taskMgr.step()
def GetCamera(self): return base.camera ################################### # End ################################### # ------------------------------------------------------------------------------ # main # ------------------------------------------------------------------------------ print 'starting World Forge v' + VERSION world = World() world.load() configurator = Configurator(world) cfg = configurator.config globals.config = cfg globals.zoneid = globals.getzoneidbyname(globals.config['default_zone']) # Creates a ModelPicker object in charge of setting spawn models as Pickable. globals.picker = ModelPicker() globals.grid_list = list() globals.gridlinks_list = list() # Loads the various GUI components app = wx.App() globals.spawndialog = SpawnsFrame(wx.Frame(None, -1, ' ')) globals.spawndialog.Show() globals.griddialog = GridsFrame(wx.Frame(None, -1, ' ')) globals.griddialog.Show() #
class Batch: def __init__(self, process_pk): process = Process.objects.get(pk=process_pk) self.cfg = Configurator() self.max_outstanding = self.cfg.getint('MPROCESSOR', 'max_outstanding') self.batch_size = self.cfg.getint('MPROCESSOR', 'batch_size') # how many items to load self.pipeline = loads(process.pipeline.params) self.dag = DAG(self.pipeline) self.schedule_length = len(self.pipeline) self.process = process self.scripts = self._get_scripts(self.pipeline) self.all_targets_read = False # True when all targets have been read self.gameover = False # True when all targets are done self.outstanding = 0 # number of not yet answered requests self.cur_batch = 0 # index in batch self.cur_task = 0 # index in tasks self.totals = {'update':0, 'passed':0, 'failed':0, 'targets': 0, None: 0} self.results = {} def run(self): "Start the iteration initializing state so that the iteration starts correctly" log.debug('### Running batch for process %s' % (str(self.process.pk),)) self.process.targets = ProcessTarget.objects.filter(process=self.process).count() self.tasks = [] self._iterate() def stop(self, seconds_offset=0): log.info('stopping process %s' % self.process.pk) with transaction.commit_on_success(): when = datetime.datetime.now() + datetime.timedelta(seconds=seconds_offset) self.process.end_date = when self.process.save() self.gameover = True def _update_item_stats(self, item, action, result, success, failure, cancelled): #log.debug('_update_item_stats: item=%s action=%s success=%s, failure=%s, cancelled=%s' % (item.target_id, action, success, failure, cancelled)) #d item.actions_passed += success item.actions_failed += failure item.actions_cancelled += cancelled item.actions_todo -= (success + failure + cancelled) if item.pk not in self.results: self.results[item.pk] = {} self.results[item.pk][action] = (success, result) if item.actions_todo <= 0 or failure > 0: item.result = dumps(self.results[item.pk]) if item.actions_todo <= 0: #log.debug('_update_item_stats: finalizing item %s' % item.target_id) #d del self.results[item.pk] def _get_scripts(self, pipeline): """Load scripts from plugin directory. Returns the dictionary {'script_name': (callable, params)} Throws an exception if not all scripts can be loaded. """ plugins_module = self.cfg.get("MPROCESSOR", "plugins") scripts = {} for script_key, script_dict in pipeline.items(): script_name = script_dict['script_name'] full_name = plugins_module + '.' + script_name + '.run' p = full_name.split('.') log.info('<$> loading script: %s' % '.'.join(p[:-1])) m = __import__('.'.join(p[:-1]), fromlist = p[:-1]) f = getattr(m, p[-1], None) if not f or not callable(f): raise BatchError('Plugin %s has no callable run method' % script_name) else: scripts[script_key] = (f, script_dict.get('params', {})) return scripts def _new_batch(self): "Loads from db the next batch of items and associate a schedule to each item" if self.all_targets_read: return [] targetset = ProcessTarget.objects.filter(process=self.process.pk)[self.cur_batch:self.cur_batch + self.batch_size] if targetset: self.cur_batch += self.batch_size ret = [{'item':x, 'schedule':Schedule(self.dag, x.target_id)} for x in targetset] # item, index of current action, schedule else: self.all_targets_read = True ret = [] return ret def _get_action(self): """returns the first action found or None. Delete tasks with no actions left""" #log.debug("_get_action on num_tasks=%s" % len(self.tasks)) #d to_delete = [] action = '' for n in xrange(len(self.tasks)): idx = (self.cur_task + n) % len(self.tasks) task = self.tasks[idx] action = task['schedule'].action_to_run() if action is None: to_delete.append(task) elif action: break #log.debug('to_delete %s' % to_delete) #d for t in to_delete: #log.debug('deleting done target %s' % t['item'].target_id) #d self.tasks.remove(t) # update cur_task so that we do not always start querying the same task for new actions if action: idx = self.tasks.index(task) self.cur_task = (idx + 1) % len(self.tasks) else: self.cur_task = 0 # if action is None or empy there is no action ready to run # if there are new targets available try to read some and find some new action if action: return action, task else: if not self.all_targets_read and self.outstanding < self.max_outstanding: new_tasks = self._new_batch() if new_tasks: self.cur_task = len(self.tasks) self.tasks.extend(new_tasks) if self.all_targets_read and not self.tasks: log.debug("_get_action: gameover") self.stop() return None, None def _iterate(self): """ Run the actions listed in schedule on the items returned by _new_batch """ #log.debug('_iterate: oustanding=%s' % self.outstanding) #d while True: if self.gameover: log.debug('_iterate: gameover') return action, task = self._get_action() if action: log.debug('processing action: "%s"' % (action, )) item, schedule = task['item'], task['schedule'] method, params = self.scripts[action] try: item_params = loads(item.params) # tmp bug fixing starts here for k in params.keys(): if params[k] == '' and (k in item_params[action]): params[k] = item_params[action][k] # tmp bug fixing ends here params.update(item_params.get('*', {})) x = re.compile('^[a-z_]+' ) # cut out digits from action name params.update(item_params.get(x.match(action).group(), {})) self.outstanding += 1 #params = {u'source_variant_name': u'original'} res = method(self.process.workspace, item.target_id, **params) self._handle_ok(res, item, schedule, action, params) except Exception, e: log.error('ERROR in %s: %s %s' % (str(method), type(e), str(e))) self._handle_err(str(e), item, schedule, action, params) # If _get_action did not find anything and there are no more targets, no action # will be available until an action completes and allows more actions to go ready. if not (self.outstanding < self.max_outstanding and (action or not self.all_targets_read)): break
from twisted.internet import reactor from json import dumps from dam.workspace.models import DAMWorkspace as Workspace from config import Configurator from dam.mprocessor.models import Process, ProcessTarget,Pipeline, TriggerEvent from dam.mprocessor.pipeline import DAG from dam.mprocessor.processor import Batch c=Configurator() c.set('MPROCESSOR', 'plugins', 'dam.mprocessor.plogins') pipeline = { 'script1':{ 'script_name': 'a1', 'params':{ 'source_variant_name': 'original', 'output_variant_name': 'output', 'output_preset': 'script1', 'uno': 'uno', 'due': 'due', }, 'in': [], 'out':['1'] }, 'script2':{ 'script_name': 'a1', 'params':{ 'source_variant_name': 'original', 'output_variant_name': 'output',
class World(DirectObject): def __init__(self): self.last_mousex = 0 self.last_mousey = 0 self.zone = None self.zone_reload_name = None self.winprops = WindowProperties() # simple console output self.consoleNode = NodePath(PandaNode("console_root")) self.consoleNode.reparentTo(aspect2d) self.console_num_lines = 24 self.console_cur_line = -1 self.console_lines = [] for i in range(0, self.console_num_lines): self.console_lines.append( OnscreenText(text='', style=1, fg=(1, 1, 1, 1), pos=(-1.3, .4 - i * .05), align=TextNode.ALeft, scale=.035, parent=self.consoleNode)) # Configuration self.consoleOut('zonewalk v.%s loading configuration' % VERSION) self.configurator = Configurator(self) cfg = self.configurator.config resaveRes = False if 'xres' in cfg: self.xres = int(cfg['xres']) else: self.xres = 1024 resaveRes = True if 'yres' in cfg: self.yres = int(cfg['yres']) else: self.yres = 768 resaveRes = True if resaveRes: self.saveDefaultRes() self.xres_half = self.xres / 2 self.yres_half = self.yres / 2 self.mouse_accum = MouseAccume(lambda: (self.xres_half, self.yres_half)) self.eyeHeight = 7.0 self.rSpeed = 80 self.flyMode = 1 # application window setup base.win.setClearColor(Vec4(0, 0, 0, 1)) self.winprops.setTitle('zonewalk') self.winprops.setSize(self.xres, self.yres) base.win.requestProperties(self.winprops) base.disableMouse() # network test stuff self.login_client = None if 'testnet' in cfg: if cfg['testnet'] == '1': self.doLogin() # Post the instructions self.title = addTitle('zonewalk v.' + VERSION) self.inst0 = addInstructions(0.95, "[FLYMODE][1]") self.inst1 = addInstructions( -0.95, "Camera control with WSAD/mouselook. Press K for hotkey list, ESC to exit." ) self.inst2 = addInstructions(0.9, "Loc:") self.inst3 = addInstructions(0.85, "Hdg:") self.error_inst = addInstructions(0, '') self.kh = [] self.campos = Point3(155.6, 41.2, 4.93) base.camera.setPos(self.campos) # Accept the application control keys: currently just esc to exit navgen self.accept("escape", self.exitGame) self.accept("window-event", self.resizeGame) # Create some lighting ambient_level = .6 ambientLight = AmbientLight("ambientLight") ambientLight.setColor( Vec4(ambient_level, ambient_level, ambient_level, 1.0)) render.setLight(render.attachNewNode(ambientLight)) direct_level = 0.8 directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0.0, 0.0, -1.0)) directionalLight.setColor( Vec4(direct_level, direct_level, direct_level, 1)) directionalLight.setSpecularColor( Vec4(direct_level, direct_level, direct_level, 1)) render.setLight(render.attachNewNode(directionalLight)) # create a point light that will follow our view point (the camera for now) # attenuation is set so that this point light has a torch like effect self.plight = PointLight('plight') self.plight.setColor(VBase4(0.8, 0.8, 0.8, 1.0)) self.plight.setAttenuation(Point3(0.0, 0.0, 0.0002)) self.plnp = base.camera.attachNewNode(self.plight) self.plnp.setPos(0, 0, 0) render.setLight(self.plnp) self.cam_light = 1 self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, \ "cam-right":0, "mouse3":0, "flymode":1 } # setup FOG self.fog_colour = (0.8, 0.8, 0.8, 1.0) self.linfog = Fog("A linear-mode Fog node") self.linfog.setColor(self.fog_colour) self.linfog.setLinearRange(700, 980) # onset, opaque distances as params # linfog.setLinearFallback(45,160,320) base.camera.attachNewNode(self.linfog) render.setFog(self.linfog) self.fog = 1 # camera control self.campos = Point3(0, 0, 0) self.camHeading = 0.0 self.camPitch = 0.0 base.camLens.setFov(65.0) base.camLens.setFar(1200) self.cam_speed = 0 # index into self.camp_speeds self.cam_speeds = [40.0, 80.0, 160.0, 320.0, 640.0] # Collision Detection for "WALKMODE" # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. The ray will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0.0, 0.0, 0.0) self.camGroundRay.setDirection(0, 0, -1) # straight down self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) # attach the col node to the camCollider dummy node self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Add the spinCameraTask procedure to the task manager. # taskMgr.add(self.spinCameraTask, "SpinCameraTask") taskMgr.add(self.camTask, "camTask") self.toggleControls(1) # need to step the task manager once to make our fake console work taskMgr.step() # CONSOLE --------------------------------------------------------------------- def consoleScroll(self): for i in range(0, self.console_num_lines - 1): self.console_lines[i].setText(self.console_lines[i + 1].getText()) def consoleOut(self, text): print text # output to stdout/log too if self.console_cur_line == self.console_num_lines - 1: self.consoleScroll() elif self.console_cur_line < self.console_num_lines - 1: self.console_cur_line += 1 self.console_lines[self.console_cur_line].setText(text) taskMgr.step() def consoleOn(self): self.consoleNode.show() def consoleOff(self): self.consoleNode.hide() # User controls ----------------------------------------------------------- def toggleControls(self, on): if on == 1: self.accept("escape", self.exitGame) self.accept("1", self.setSpeed, ["speed", 0]) self.accept("2", self.setSpeed, ["speed", 1]) self.accept("3", self.setSpeed, ["speed", 2]) self.accept("4", self.setSpeed, ["speed", 3]) self.accept("5", self.setSpeed, ["speed", 4]) self.accept("alt-f", self.fogToggle) self.accept("t", self.camLightToggle) self.accept("k", self.displayKeyHelp) self.accept("f", self.toggleFlymode) self.accept("l", self.reloadZone) self.accept("z", self.saveDefaultZone) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("d", self.setKey, ["cam-right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("mouse1", self.setKey, ["forward", 1]) self.accept("mouse3", self.setKey, ["mouse3", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("k-up", self.hideKeyHelp) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("d-up", self.setKey, ["cam-right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("mouse1-up", self.setKey, ["forward", 0]) self.accept("mouse3-up", self.setKey, ["mouse3", 0]) self.accept("s-up", self.setKey, ["backward", 0]) else: messenger.clear() def setSpeed(self, key, value): self.cam_speed = value self.setFlymodeText() def fogToggle(self): if self.fog == 1: render.clearFog() base.camLens.setFar(100000) self.fog = 0 else: render.setFog(self.linfog) base.camLens.setFar(1200) self.fog = 1 def camLightToggle(self): if self.cam_light == 0: render.setLight(self.plnp) self.cam_light = 1 else: render.clearLight(self.plnp) self.cam_light = 0 def displayKeyHelp(self): self.kh = [] msg = 'HOTKEYS:' pos = 0.75 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = '------------------' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = 'W: camera fwd, S: camera bck, A: rotate view left, D: rotate view right' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = '1-5: set camera movement speed' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = 'F: toggle Flymode/Walkmode' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = 'L: load a zone' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = 'ALT-F: toggle FOG and FAR plane on/off' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = 'T: toggle additional camera "torch" light on/off' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = 'Z: set currently loaded zone as new startup default' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) msg = 'ESC: exit zonewalk' pos -= 0.05 self.kh.append( OnscreenText(text=msg, style=1, fg=(1, 1, 1, 1), pos=(-0.5, pos), align=TextNode.ALeft, scale=.04)) def hideKeyHelp(self): for n in self.kh: n.removeNode() def setFlymodeText(self): zname = '' if self.zone: zname = self.zone.name if self.flyMode == 0: self.inst0.setText("[WALKMODE][%i] %s" % (self.cam_speed + 1, zname)) else: self.inst0.setText("[FLYMODE][%i] %s " % (self.cam_speed + 1, zname)) def toggleFlymode(self): zname = '' if self.zone: zname = self.zone.name if self.flyMode == 0: self.flyMode = 1 else: self.flyMode = 0 self.setFlymodeText() # Define a procedure to move the camera. def spinCameraTask(self, task): angleDegrees = task.time * 6.0 angleRadians = angleDegrees * (pi / 180.0) base.camera.setPos(20 * sin(angleRadians), -20.0 * cos(angleRadians), 3) base.camera.setHpr(angleDegrees, 0, 0) return task.cont def camTask(self, task): # query the mouse mouse_dx = 0 mouse_dy = 0 # if we have a mouse and the right button is depressed if base.mouseWatcherNode.hasMouse(): if self.keyMap["mouse3"] != 0: self.mouse_accum.update() else: self.mouse_accum.reset() mouse_dx = self.mouse_accum.dx mouse_dy = self.mouse_accum.dy self.rXSpeed = fabs(self.mouse_accum.dx) * (self.cam_speed + 1) * max( 5 * 1000 / self.xres, 3) self.rYSpeed = fabs(self.mouse_accum.dy) * (self.cam_speed + 1) * max( 3 * 1000 / self.yres, 1) if (self.keyMap["cam-left"] != 0 or mouse_dx < 0): if self.rSpeed < 160: self.rSpeed += 80 * globalClock.getDt() if mouse_dx != 0: self.camHeading += self.rXSpeed * globalClock.getDt() else: self.camHeading += self.rSpeed * globalClock.getDt() if self.camHeading > 360.0: self.camHeading = self.camHeading - 360.0 elif (self.keyMap["cam-right"] != 0 or mouse_dx > 0): if self.rSpeed < 160: self.rSpeed += 80 * globalClock.getDt() if mouse_dx != 0: self.camHeading -= self.rXSpeed * globalClock.getDt() else: self.camHeading -= self.rSpeed * globalClock.getDt() if self.camHeading < 0.0: self.camHeading = self.camHeading + 360.0 else: self.rSpeed = 80 if mouse_dy > 0: self.camPitch += self.rYSpeed * globalClock.getDt() elif mouse_dy < 0: self.camPitch -= self.rYSpeed * globalClock.getDt() # set camera heading and pitch base.camera.setHpr(self.camHeading, self.camPitch, 0) # viewer position (camera) movement control v = render.getRelativeVector(base.camera, Vec3.forward()) if not self.flyMode: v.setZ(0.0) move_speed = self.cam_speeds[self.cam_speed] if self.keyMap["forward"] == 1: self.campos += v * move_speed * globalClock.getDt() if self.keyMap["backward"] == 1: self.campos -= v * move_speed * globalClock.getDt() # actually move the camera lastPos = base.camera.getPos() base.camera.setPos(self.campos) # self.plnp.setPos(self.campos) # move the point light with the viewer position # WALKMODE: simple collision detection # we simply check a ray from slightly below the "eye point" straight down # for geometry collisions and if there are any we detect the point of collision # and adjust the camera's Z accordingly if self.flyMode == 0: # move the camera to where it would be if it made the move # the colliderNode moves with it # base.camera.setPos(self.campos) # check for collissons self.cTrav.traverse(render) entries = [] for i in range(self.camGroundHandler.getNumEntries()): entry = self.camGroundHandler.getEntry(i) entries.append(entry) # print 'collision' entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0 ): # and (entries[0].getIntoNode().getName() == "terrain"): # print len(entries) self.campos.setZ(entries[0].getSurfacePoint(render).getZ() + self.eyeHeight) else: self.campos = lastPos base.camera.setPos(self.campos) #if (base.camera.getZ() < self.player.getZ() + 2.0): # base.camera.setZ(self.player.getZ() + 2.0) # update loc and hpr display pos = base.camera.getPos() hpr = base.camera.getHpr() self.inst2.setText('Loc: %.2f, %.2f, %.2f' % (pos.getX(), pos.getY(), pos.getZ())) self.inst3.setText('Hdg: %.2f, %.2f, %.2f' % (hpr.getX(), hpr.getY(), hpr.getZ())) return task.cont def exitGame(self): sys.exit(0) def resizeGame(self, win): props = base.win.getProperties() self.xres = props.getXSize() self.yres = props.getYSize() self.xres_half = self.xres / 2 self.yres_half = self.yres / 2 self.saveDefaultRes() #Records the state of the arrow keys # this is used for camera control def setKey(self, key, value): self.keyMap[key] = value # ------------------------------------------------------------------------- # this is the mythical MAIN LOOP :) def update(self): if self.zone_reload_name != None: self.doReload(self.zone_reload_name) self.zone_reload_name = None if self.zone != None: self.zone.update() taskMgr.step() if self.login_client != None: self.login_client.update() # ZONE loading ------------------------------------------------------------ # general zone loader driver # removes existing zone (if any) and load the new one def loadZone(self, name, path): if path[len(path) - 1] != '/': path += '/' if self.zone: self.zone.rootNode.removeNode() self.zone = Zone(self, name, path) error = self.zone.load() if error == 0: self.consoleOff() self.setFlymodeText() base.setBackgroundColor(self.fog_colour) def saveDefaultRes(self): cfg = self.configurator.config cfg['xres'] = str(self.xres) cfg['yres'] = str(self.yres) self.configurator.saveConfig() # initial world load after bootup def load(self): cfg = self.configurator.config if self.login_client != None: return zone_name = cfg['default_zone'] basepath = cfg['basepath'] self.loadZone(zone_name, basepath) # config save user interfacce def saveDefaultZone(self): if self.zone: cfg = self.configurator.config cfg['default_zone'] = self.zone.name self.configurator.saveConfig() # zone reload user interface # this gets called from our update loop when it detects that zone_reload_name has been set # we do this in this convoluted fashion in order to keep the main loop taskMgr updates ticking # because otherwise our status console output at various stages during the zone load would not # be displayed. Yes, this is hacky. def doReload(self, name): cfg = self.configurator.config basepath = cfg['basepath'] self.loadZone(name, basepath) # form dialog callback # this gets called from the form when the user has entered a something # (hopefully a correct zone short name) def reloadZoneDialogCB(self, name): self.frmDialog.end() self.zone_reload_name = name self.toggleControls(1) # this is called when the user presses "l" # it disables normal controls and fires up our query form dialog def reloadZone(self): base.setBackgroundColor((0, 0, 0)) self.toggleControls(0) self.consoleOn() self.frmDialog = FileDialog( "Please enter the shortname of the zone you wish to load:", "Examples: qrg, blackburrow, freportn, crushbone etc.", self.reloadZoneDialogCB) self.frmDialog.activate() # relies on the main update loop to run ############################### # EXPERIMENTAL def doLogin(self): self.login_client = UDPClientStream('127.0.0.1', 5998)
def __init__(self): self.c = Configurator() self._root = os.path.normpath(self.c.get('STORAGE', 'cache_dir'))