def __init__(self, filename): vfs = VirtualFileSystem.getGlobalPtr() self.material = BSPMaterial.getFromFile(filename) self.filename = filename if self.material.hasKeyvalue("$basetexture"): baseTexturePath = Filename( self.material.getKeyvalue("$basetexture")) if vfs.resolveFilename(baseTexturePath, getModelPath().getValue()): imageData = bytes(VirtualFileSystem.getGlobalPtr().readFile( baseTexturePath, True)) byteArray = QtCore.QByteArray.fromRawData(imageData) image = QtGui.QImage.fromData(byteArray) self.pixmap = QtGui.QPixmap.fromImage(image) self.icon = QtGui.QIcon(self.pixmap) self.size = LVector2i(image.width(), image.height()) else: self.texture = None self.size = LVector2i(64, 64) self.icon = None self.pixmap = None else: self.texture = None self.size = LVector2i(64, 64) self.icon = None self.pixmap = None
def __init__(self, scale, position, function, default=0): VirtualFileSystem.getGlobalPtr().mount(Filename("mf/checkbox.mf"), ".", VirtualFileSystem.MFReadOnly) self.egg = loader.loadModel("checkbox/checkbox.egg") box_image = (self.egg.find("**/check-empty"), self.egg.find("**/check-checked"), None) self.button = DirectCheckButton(boxImage=box_image, boxRelief=None, relief=None, command=function, scale=scale, pos=position)
def destroy(self): VirtualFileSystem.getGlobalPtr().unmount("mf/alert.mf") VirtualFileSystem.getGlobalPtr().unmount("mf/ok_small.mf") self.bg_frame.destroy() self.frame.destroy() self.button.destroy() self.text.cleanup() self.text.destroy() del self.frame del self.button del self.text del self
def __init__(self, style): """ Timer class with fun pictures @param style: 0 = SUN, 1 = MOON, 2 = GUN @type style: int """ self.style = style VirtualFileSystem.getGlobalPtr().mount(Filename("mf/timer.mf"), ".", VirtualFileSystem.MFReadOnly) self.egg = loader.loadModel("timer.egg") self.img = None self.interval = None self.types[style](self)
def __init__(self): self.config = getConfigShowbase() vfs = VirtualFileSystem.getGlobalPtr() self.eventMgr = eventMgr self.messenger = messenger self.bboard = bulletinBoard self.taskMgr = taskMgr self.AISleep = self.config.GetFloat('ai-sleep', 0.04) Task.TaskManager.taskTimerVerbose = self.config.GetBool( 'task-timer-verbose', 0) Task.TaskManager.extendedExceptions = self.config.GetBool( 'extended-exceptions', 0) self.sfxManagerList = None self.musicManager = None self.jobMgr = jobMgr self.hidden = NodePath('hidden') self.graphicsEngine = GraphicsEngine.getGlobalPtr() globalClock = ClockObject.getGlobalClock() self.trueClock = TrueClock.getGlobalPtr() globalClock.setRealTime(self.trueClock.getShortTime()) globalClock.setAverageFrameRateInterval(30.0) globalClock.tick() taskMgr.globalClock = globalClock __builtins__['ostream'] = Notify.out() __builtins__['globalClock'] = globalClock __builtins__['vfs'] = vfs __builtins__['hidden'] = self.hidden self.restart()
def mount(self): """ Inits the VFS Mounts """ self.debug("Setting up virtual filesystem.") vfs = VirtualFileSystem.getGlobalPtr() # Mount shaders vfs.mountLoop( join(self.basePath, 'Shader'), 'Shader', 0) # Mount data and models vfs.mountLoop(join(self.basePath, 'Data'), 'Data', 0) vfs.mountLoop(join(self.basePath, 'Models'), 'Models', 0) vfs.mountLoop(join(self.basePath, 'Config'), 'Config', 0) vfs.mountLoop(join(self.basePath, 'Demoscene.ignore'), 'Demoscene.ignore', 0) # Just mount everything # vfs.mountLoop(self.basePath, '.', 0) if not isdir(self.writePath): self.debug("Creating temp path, as it does not exist yet") try: makedirs(self.writePath) except Exception, msg: self.error("Failed to create temp path:",msg) import sys sys.exit(0)
def reloadTextures(textureName=''): """ Artfart command to reload all of the textures. TODO: A panel that says "Reloading textures... Please wait!" ...though it's not important since it's a staff command and only staff will see it. Stolen from ToontownStart.py Remount all phase files. This maybe might work? Idk. Lets see if Panda craps itself. Place raw files in /resources/non-mf/phase_*/ and they will be mounted without needing to multify! """ # Lock ... vfs = VirtualFileSystem.getGlobalPtr() for file in glob.glob('resources/non-mf/phase_*/'): # Slightly hacky. We remove the trailing slash so we have a tail, # and select the tail value from the returned tuple. Finally we # prepend a slash for the mount point. mount_point = '/' + str(os.path.split(file[:-1])[1]) vfs.mount(Filename(file), Filename(mount_point), 0) # ... and load. if textureName: pool = TexturePool.findAllTextures('*' + textureName + '*') else: pool = TexturePool.findAllTextures() for texture in pool: texture.reload() if textureName: return "Reloaded all textures matching '%s'" % textureName return "Reloaded all of the textures!"
def __init__(self, app=None, dt=None): self.app = app or ShowBase() self.app.accept('escape', sys.exit) self.root_node = self.app.render self._dt = 0.1 if dt is None else dt # setup visualization camera vfov = 45 hfov = vfov * float(self.app.win.getSize()[0]) / float( self.app.win.getSize()[1]) self.app.camLens.setFov(hfov, vfov) self.app.camLens.set_near_far(0.01, 10000.0) # 1cm to 10km # The VirtualFileSystem, which has already initialized, doesn't see the mount # directives in the config(s) yet. We have to force it to load those manually: vfs = VirtualFileSystem.getGlobalPtr() mounts = ConfigVariableList('vfs-mount') for mount_desc in mounts: mount_desc = mount_desc.split(' ') physical_filename, mount_point = mount_desc[:2] physical_filename = os.path.expandvars(physical_filename) mount_point = os.path.expandvars(mount_point) if len(mount_desc) > 2: options = mount_desc[2] else: options = '' vfs.mount(Filename(physical_filename), Filename(mount_point), *parse_options(options))
def reloadTextures(textureName=""): """ Artfart command to reload all of the textures. TODO: A panel that says "Reloading textures... Please wait!" ...though it's not important since it's a staff command and only staff will see it. Stolen from ToontownStart.py Remount all phase files. This maybe might work? Idk. Lets see if Panda craps itself. Place raw files in /resources/non-mf/phase_*/ and they will be mounted without needing to multify! """ # Lock ... vfs = VirtualFileSystem.getGlobalPtr() for file in glob.glob("resources/non-mf/phase_*/"): # Slightly hacky. We remove the trailing slash so we have a tail, # and select the tail value from the returned tuple. Finally we # prepend a slash for the mount point. mount_point = "/" + str(os.path.split(file[:-1])[1]) vfs.mount(Filename(file), Filename(mount_point), 0) # ... and load. if textureName: pool = TexturePool.findAllTextures("*" + textureName + "*") else: pool = TexturePool.findAllTextures() for texture in pool: texture.reload() if textureName: return "Reloaded all textures matching '%s'" % textureName return "Reloaded all of the textures!"
def __init__(self, filename): vfs = VirtualFileSystem.getGlobalPtr() #self.material = BSPMaterial.getFromFile(filename) self.material = TexturePool.loadTexture(filename) self.filename = filename if self.material: #.hasKeyvalue("$basetexture"): # baseTexturePath = self.material.getKeyvalue("$basetexture") if True: #vfs.exists(baseTexturePath): #imageData = bytes(VirtualFileSystem.getGlobalPtr().readFile(baseTexturePath, True)) pimage = PNMImage() self.material.store(pimage, 0, 0) ss = StringStream() pimage.write(ss, "tmp.png") imageData = bytes(ss) byteArray = QtCore.QByteArray.fromRawData(imageData) image = QtGui.QImage.fromData(byteArray) self.pixmap = QtGui.QPixmap.fromImage(image) self.icon = QtGui.QIcon(self.pixmap) self.size = LVector2i(pimage.getXSize(), pimage.getYSize()) print(pimage, self.size) else: self.size = LVector2i(64, 64) self.icon = None self.pixmap = None else: self.size = LVector2i(64, 64) self.icon = None self.pixmap = None
def __init__(self): self.loadDefaultConfig() self.loadLocalConfig() if ConfigVariableBool("want-pstats", False): PStatClient.connect() # Set up some global objects self.globalClock = ClockObject.getGlobalClock() # We will manually manage the clock self.globalClock.setMode(ClockObject.MSlave) builtins.globalClock = self.globalClock self.vfs = VirtualFileSystem.getGlobalPtr() # For tasks that run every application frame self.taskMgr = TaskManagerGlobal.taskMgr builtins.taskMgr = self.taskMgr # For tasks that run every simulation tick self.simTaskMgr = Task.TaskManager() self.simTaskMgr.mgr = AsyncTaskManager("sim") builtins.simTaskmgr = self.simTaskMgr self.eventMgr = EventManagerGlobal.eventMgr builtins.eventMgr = self.eventMgr self.messenger = MessengerGlobal.messenger builtins.messenger = self.messenger self.loader = Loader(self) builtins.loader = self.loader builtins.base = self # What is the current frame number? self.frameCount = 0 # Time at beginning of current frame self.frameTime = self.globalClock.getRealTime() # How long did the last frame take. self.deltaTime = 0 # # Variables pertaining to simulation ticks. # self.prevRemainder = 0 self.remainder = 0 # What is the current overall simulation tick? self.tickCount = 0 # How many ticks are we going to run this frame? self.totalTicksThisFrame = 0 # How many ticks have we run so far this frame? self.currentTicksThisFrame = 0 # What tick are we currently on this frame? self.currentFrameTick = 0 # How many simulations ticks are we running per-second? self.ticksPerSec = 60 self.intervalPerTick = 1.0 / self.ticksPerSec
def load_assets(self): filename = "assets.mf" correct_md5 = '9f733c91cc681a1d1c8108d238a0a50b' read_md5 = y_md5_check.md5_sum(filename) assert read_md5 == correct_md5 vfs = VirtualFileSystem.getGlobalPtr() if vfs.mount(filename, ".", VirtualFileSystem.MFReadOnly): print('mounted')
def qtResolvePath(filename): """ Resolves a filename path using the Panda model-path and returns an OS-specific absolute path. Used to load Qt icons from stuff on model-path. """ filename = Filename.fromOsSpecific(filename) vfs = VirtualFileSystem.getGlobalPtr() vfs.resolveFilename(filename, getModelPath().getValue()) return filename.toOsSpecific()
def dummyAppRunner(tokens=[], argv=None): """ This function creates a dummy global AppRunner object, which is useful for testing running in a packaged environment without actually bothering to package up the application. Call this at the start of your application to enable it. It places the current working directory under /mf, as if it were mounted from a packed multifile. It doesn't convert egg files to bam files, of course; and there are other minor differences from running in an actual packaged environment. But it can be a useful first-look sanity check. """ if AppRunnerGlobal.appRunner: print("Already have AppRunner, not creating a new one.") return AppRunnerGlobal.appRunner appRunner = AppRunner() appRunner.dummy = True AppRunnerGlobal.appRunner = appRunner platform = PandaSystem.getPlatform() version = PandaSystem.getPackageVersionString() hostUrl = PandaSystem.getPackageHostUrl() if platform.startswith('win'): rootDir = Filename(Filename.getUserAppdataDirectory(), 'Panda3D') elif platform.startswith('osx'): rootDir = Filename(Filename.getHomeDirectory(), 'Library/Caches/Panda3D') else: rootDir = Filename(Filename.getHomeDirectory(), '.panda3d') appRunner.rootDir = rootDir appRunner.logDirectory = Filename(rootDir, 'log') # Of course we will have the panda3d application loaded. appRunner.addPackageInfo('panda3d', platform, version, hostUrl) appRunner.tokens = tokens appRunner.tokenDict = dict(tokens) if argv is None: argv = sys.argv appRunner.argv = argv appRunner.altHost = appRunner.tokenDict.get('alt_host', None) appRunner.p3dInfo = None appRunner.p3dPackage = None # Mount the current directory under the multifileRoot, as if it # were coming from a multifile. cwd = ExecutionEnvironment.getCwd() vfs = VirtualFileSystem.getGlobalPtr() vfs.mount(cwd, appRunner.multifileRoot, vfs.MFReadOnly) appRunner.initPackedAppEnvironment() return appRunner
def loadWhiteListData(): global WhiteListData if WhiteListData is None: vfs = VirtualFileSystem.getGlobalPtr() whitelistFile = vfs.readFile('phase_3/etc/ciwhitelist.dat', False) WhiteListData = set() for word in whitelistFile.split(): WhiteListData.add(word) del whitelistFile
def load(self): DistributedEntityAI.load(self) from panda3d.core import VirtualFileSystem vfs = VirtualFileSystem.getGlobalPtr() self.scriptSrc = vfs.readFile(self.scriptFilename, True) self.target = self.bspLoader.getPyEntityByTargetName( self.getEntityValue("scriptTarget"))
def dummyAppRunner(tokens = [], argv = None): """ This function creates a dummy global AppRunner object, which is useful for testing running in a packaged environment without actually bothering to package up the application. Call this at the start of your application to enable it. It places the current working directory under /mf, as if it were mounted from a packed multifile. It doesn't convert egg files to bam files, of course; and there are other minor differences from running in an actual packaged environment. But it can be a useful first-look sanity check. """ if AppRunnerGlobal.appRunner: print("Already have AppRunner, not creating a new one.") return AppRunnerGlobal.appRunner appRunner = AppRunner() appRunner.dummy = True AppRunnerGlobal.appRunner = appRunner platform = PandaSystem.getPlatform() version = PandaSystem.getPackageVersionString() hostUrl = PandaSystem.getPackageHostUrl() if platform.startswith('win'): rootDir = Filename(Filename.getUserAppdataDirectory(), 'Panda3D') elif platform.startswith('osx'): rootDir = Filename(Filename.getHomeDirectory(), 'Library/Caches/Panda3D') else: rootDir = Filename(Filename.getHomeDirectory(), '.panda3d') appRunner.rootDir = rootDir appRunner.logDirectory = Filename(rootDir, 'log') # Of course we will have the panda3d application loaded. appRunner.addPackageInfo('panda3d', platform, version, hostUrl) appRunner.tokens = tokens appRunner.tokenDict = dict(tokens) if argv is None: argv = sys.argv appRunner.argv = argv appRunner.altHost = appRunner.tokenDict.get('alt_host', None) appRunner.p3dInfo = None appRunner.p3dPackage = None # Mount the current directory under the multifileRoot, as if it # were coming from a multifile. cwd = ExecutionEnvironment.getCwd() vfs = VirtualFileSystem.getGlobalPtr() vfs.mount(cwd, appRunner.multifileRoot, vfs.MFReadOnly) appRunner.initPackedAppEnvironment() return appRunner
def __init__(self): self.packPath = 'resources/contentpacks/' if not os.path.exists(self.packPath): os.makedirs(self.packPath) self.sortFile = os.path.join(self.packPath, 'pack-load-order.yaml') if not os.path.exists(self.sortFile): open(self.sortFile, 'a').close() self.mountPoint = '/' self.vfSys = VirtualFileSystem.getGlobalPtr() self.sort = []
def __init__(self, reason): Notifier.__init__(self, "alert") VirtualFileSystem.getGlobalPtr().mount(Filename("mf/alert.mf"), ".", VirtualFileSystem.MFReadOnly) ok = loader.loadModel("alert.egg") if reason not in LOCAL_EN: reason = GENERAL self.reason = reason self.bg_frame = DirectFrame(frameColor=(0, 0, 0, 0), frameSize=(-1, 1, -1, 1), suppressMouse=1, state=DGG.NORMAL, sortOrder=1000) self.frame = DirectFrame(frameSize=(1, 1, 1, 1), image=ok.find('**/alert'), image_scale=(1, 0, 0.6), state=DGG.NORMAL, parent=self.bg_frame) self.text = OnscreenText(text=LOCAL_EN[reason], fg=(1, 1, 1, 1), pos=(0, 0.15, 0), align=TextNode.ACenter, wordwrap=13, parent=self.frame) self.button = DirectButton(geom=(ok.find('**/ok-ready'), ok.find('**/ok-click'), ok.find('**/ok-hover'), ok.find('**/ok-click')), relief=None, geom_scale=(0.3, 0, 0.15), geom_pos=(0, 0, -0.175), pressEffect=0, command=self.destroy, parent=self.frame) self.notify.debug( f"[__init__] Created Alert with reason {self.reason}") loader.unloadModel(ok)
def loadText(self): # Load database vfs = VirtualFileSystem.getGlobalPtr() #print "Virtual fs" ,vfs.lsAll('/mf') path = vfs.findFile('TXT_UI_Common.yaml', '.') if not path: path = vfs.findFile('TXT_UI_Common.yaml', '/mf') stream = vfs.readFile(path.getFilename(), True) textDictionary = yaml.load(stream) for key in textDictionary: self.database[key] = textDictionary[key]
def __init__(self, filepath): self.filepath = filepath self.vfs = VirtualFileSystem.getGlobalPtr() if __debug__: self.mountPoint = "../resources" else: self.mountPoint = "/" self.sortOrder = []
def precacheMusicDir(musicDir, extension = "ogg"): global Cache vfs = VirtualFileSystem.getGlobalPtr() songList = vfs.scanDirectory(musicDir) if not songList: print("No music in {0}".format(musicDir)) return for vFile in songList.getFiles(): fn = vFile.getFilename() if fn.getExtension() == extension: Cache[fn.getBasenameWoExtension()] = fn.getFullpath()
def __init__(self): self.config = DConfig self.graphicsEngine = GraphicsEngine() globalClock = ClockObject.getGlobalClock() self.trueClock = TrueClock.getGlobalPtr() globalClock.setRealTime(self.trueClock.getShortTime()) globalClock.setAverageFrameRateInterval(30.0) globalClock.tick() __builtins__['globalClock'] = globalClock taskMgr.globalClock = globalClock self.vfs = VirtualFileSystem.getGlobalPtr() __builtins__['vfs'] = self.vfs
def exit_game(self): """ Use this to close the game. Closes connection and tells server we're leaving """ VirtualFileSystem.getGlobalPtr().unmount("mf/pawns.mf") VirtualFileSystem.getGlobalPtr().unmount("mf/timer.mf") for level in self.levels: self.levels[level].destroy() if self.console is not None: self.console.destroy() if self.messager.my_connection is None or self.messager.pid is None: sys.exit() # tell server self.write(dg_goodbye(self.messager.pid)) self.messager.cManager.closeConnection(self.messager.my_connection) sys.exit()
def __init__(self, filepath='contentpacks/', sortFilename='sort.yaml'): self.filepath = filepath self.sortFilename = os.path.join(self.filepath, sortFilename) if __debug__: self.mountPoint = '../resources' else: self.mountPoint = '/' self.vfs = VirtualFileSystem.getGlobalPtr() self.sort = [] self.ambience = {}
def ReadResponse(self, dataOut, bytesToRead, bytesReadOut, callback): if self.contents is None: self.contents = VirtualFileSystem.getGlobalPtr().readFile(self.filePath, False) if self.offset < len(self.contents): dataOut[0] = self.contents[self.offset:self.offset + bytesToRead] bytesReadOut[0] = bytesToRead self.offset += bytesToRead return True # We are done self.clientHandler._ReleaseStrongReference(self) return False
def reloadTextures(textureName=''): vfs = VirtualFileSystem.getGlobalPtr() for file in glob.glob('resources/non-mf/phase_*/'): mount_point = '/' + str(os.path.split(file[:-1])[1]) vfs.mount(Filename(file), Filename(mount_point), 0) if textureName: pool = TexturePool.findAllTextures('*' + textureName + '*') else: pool = TexturePool.findAllTextures() for texture in pool: texture.reload() if textureName: return "Reloaded all textures matching '%s'" % textureName return 'Reloaded all of the textures!'
def GetResponseHeaders(self, response, responseLengthOut, redirectUrlOut): """ :type response: cefpython.PyResponse """ response.SetMimeType(getMimeType(self.url)) file = VirtualFileSystem.getGlobalPtr().getFile(self.filePath) if file is None: response.SetStatus(404) response.SetStatusText("File not found") return responseLengthOut[0] = file.getFileSize()
def __init__(self, menu): base.transitions.fadeScreen(1.0) vfs = VirtualFileSystem.getGlobalPtr() creditsTextStr = str(vfs.readFile("scripts/credits.txt", True)) self.creditsText = OnscreenText(text=creditsTextStr, fg=(1, 1, 1, 1), align=TextNode.ACenter, mayChange=False, scale=0.06) self.creditsText.reparentTo(aspect2d, DGG.FADE_SORT_INDEX + 1) self.creditsText.setZ(-1) self.ival = Sequence( LerpPosInterval(self.creditsText, 20.0, (0, 0, 2.6), (0, 0, -1.0)), Func(self.done)) self.ival.start() self.acceptOnce('space', self.done) self.menu = menu
def findAllModelFilesInVFS(phase_array): models = [] vfs = VirtualFileSystem.getGlobalPtr() for phase in phase_array: fileList = vfs.scanDirectory(Filename(phase)) for fileName in fileList: if fileName.get_filename().get_fullpath().endswith('.bam') or fileName.get_filename().get_fullpath().endswith('.egg') or fileName.get_filename().get_fullpath().endswith('.pz'): if fileName.get_filename().get_fullpath() not in models: models.append(fileName.get_filename().get_fullpath()) else: fileList2 = vfs.scanDirectory(Filename(fileName.get_filename().get_fullpath())) for fileName2 in fileList2: if fileName2.get_filename().get_fullpath().endswith('.bam') or fileName2.get_filename().get_fullpath().endswith('.egg') or fileName2.get_filename().get_fullpath().endswith('.pz'): if fileName2.get_filename().get_fullpath() not in models: models.append(fileName2.get_filename().get_fullpath()) return models
def readFavIcon(self): vfs = VirtualFileSystem.getGlobalPtr() filename = Filename('favicon.ico') searchPath = DSearchPath() searchPath.appendDirectory(Filename('.')) searchPath.appendDirectory(Filename('etc')) searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('$DIRECT/src/http'))) searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('direct/src/http'))) searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('direct/http'))) searchPath.appendDirectory(Filename('game/resources/http')) searchPath.appendDirectory(Filename('resources/http')) found = vfs.resolveFilename(filename,searchPath) if not found: raise Exception("Couldn't find direct/http/favicon.ico") return vfs.readFile(filename, 1)
def initPackedAppEnvironment(self): """ This function sets up the Python environment suitably for running a packed app. It should only run once in any given session (and it includes logic to ensure this). """ if self.packedAppEnvironmentInitialized: return self.packedAppEnvironmentInitialized = True vfs = VirtualFileSystem.getGlobalPtr() # Now set up Python to import this stuff. VFSImporter.register() sys.path.append(self.multifileRoot) # Make sure that $MAIN_DIR is set to the p3d root before we # start executing the code in this file. ExecutionEnvironment.setEnvironmentVariable( "MAIN_DIR", Filename(self.multifileRoot).toOsSpecific()) # Put our root directory on the model-path, too. getModelPath().appendDirectory(self.multifileRoot) if not self.trueFileIO: # Replace the builtin open and file symbols so user code will get # our versions by default, which can open and read files out of # the multifile. builtins.open = file.open if sys.version_info < (3, 0): builtins.file = file.open builtins.execfile = file.execfile os.listdir = file.listdir os.walk = file.walk os.path.join = file.join os.path.isfile = file.isfile os.path.isdir = file.isdir os.path.exists = file.exists os.path.lexists = file.lexists os.path.getmtime = file.getmtime os.path.getsize = file.getsize sys.modules['glob'] = glob self.checkDiskUsage()
def setCurrentSurface(self, surface): if self.currentSurface == surface: return self.currentSurface = surface if surface == "default" and self.defaultOverride is not None: surface = self.defaultOverride if not surface in self.footstepSounds: self.footstepSounds[surface] = [] vfs = VirtualFileSystem.getGlobalPtr() for vFile in vfs.scanDirectory("phase_14/audio/sfx/footsteps/"): fullPath = vFile.getFilename().getFullpath() if surface == vFile.getFilename().getBasenameWoExtension( )[:len(surface)]: sound = base.loadSfx(fullPath) self.footstepSounds[surface].append(sound)
def initPackedAppEnvironment(self): """ This function sets up the Python environment suitably for running a packed app. It should only run once in any given session (and it includes logic to ensure this). """ if self.packedAppEnvironmentInitialized: return self.packedAppEnvironmentInitialized = True vfs = VirtualFileSystem.getGlobalPtr() # Now set up Python to import this stuff. VFSImporter.register() sys.path.append(self.multifileRoot) # Make sure that $MAIN_DIR is set to the p3d root before we # start executing the code in this file. ExecutionEnvironment.setEnvironmentVariable("MAIN_DIR", Filename(self.multifileRoot).toOsSpecific()) # Put our root directory on the model-path, too. getModelPath().appendDirectory(self.multifileRoot) if not self.trueFileIO: # Replace the builtin open and file symbols so user code will get # our versions by default, which can open and read files out of # the multifile. builtins.open = file.open if sys.version_info < (3, 0): builtins.file = file.open builtins.execfile = file.execfile os.listdir = file.listdir os.walk = file.walk os.path.join = file.join os.path.isfile = file.isfile os.path.isdir = file.isdir os.path.exists = file.exists os.path.lexists = file.lexists os.path.getmtime = file.getmtime os.path.getsize = file.getsize sys.modules["glob"] = glob self.checkDiskUsage()
def fromFile(self, packageDir, filename, pathname=None, st=None): """ Reads the file information from the indicated file. If st is supplied, it is the result of os.stat on the filename. """ vfs = VirtualFileSystem.getGlobalPtr() filename = Filename(filename) if pathname is None: pathname = Filename(packageDir, filename) self.filename = filename.cStr() self.basename = filename.getBasename() if st is None: st = os.stat(pathname.toOsSpecific()) self.size = st.st_size self.timestamp = st.st_mtime self.readHash(pathname)
def fromFile(self, packageDir, filename, pathname = None, st = None): """ Reads the file information from the indicated file. If st is supplied, it is the result of os.stat on the filename. """ vfs = VirtualFileSystem.getGlobalPtr() filename = Filename(filename) if pathname is None: pathname = Filename(packageDir, filename) self.filename = str(filename) self.basename = filename.getBasename() if st is None: st = os.stat(pathname.toOsSpecific()) self.size = st.st_size self.timestamp = int(st.st_mtime) self.readHash(pathname)
def __init__(self, filePath, fileName): self.__filePath = filePath self.__fileName = fileName vfs = VirtualFileSystem.getGlobalPtr() filename = Filename(fileName) searchPath = DSearchPath() if __debug__: searchPath.appendDirectory(Filename.expandFrom('resources/%s' % filePath)) else: searchPath.appendDirectory(Filename.expandFrom(filePath)) found = vfs.resolveFilename(filename, searchPath) if not found: raise TileFileIOException('Unable to locate tiled file \"%s\"; File not found on %s' % (fileName, searchPath)) self.__fileData = json.loads(vfs.readFile(filename, 1)) self.__verifyData() self.__layers = self.__fileData['layers']
def mount(self): """ Inits the VFS Mounts """ self.debug("Setting up virtual filesystem.") vfs = VirtualFileSystem.getGlobalPtr() # Mount data and models vfs.mountLoop(join(self.basePath, 'Data'), 'Data', 0) vfs.mountLoop(join(self.basePath, 'Models'), 'Models', 0) vfs.mountLoop(join(self.basePath, 'Config'), 'Config', 0) # Ensure the pipeline write path exists, and if not, create it if not isdir(self.writePath): self.debug("Creating temp path, as it does not exist yet") try: os.makedirs(self.writePath, 0777) except Exception, msg: self.error("Failed to create temp path:",msg) import sys sys.exit(0)
def mount(self): """ Inits the VFS Mounts """ self.debug("Setting up virtual filesystem.") vfs = VirtualFileSystem.getGlobalPtr() # Mount shaders vfs.mountLoop( join(self.basePath, 'Shader'), 'Shader', 0) # Mount data vfs.mountLoop(join(self.basePath, 'Data'), 'Data', 0) # TODO: Mount core if not isdir(self.writePath): self.debug("Creating temp path, as it does not exist yet") try: makedirs(self.writePath) except Exception, msg: self.error("Failed to create temp path:",msg) import sys sys.exit(0)
__builtins__['jobMgr'] = simbase.jobMgr __builtins__['eventMgr'] = simbase.eventMgr __builtins__['messenger'] = simbase.messenger __builtins__['bboard'] = simbase.bboard __builtins__['config'] = simbase.config __builtins__['directNotify'] = directNotify from direct.showbase import Loader simbase.loader = Loader.Loader(simbase) __builtins__['loader'] = simbase.loader directNotify.setDconfigLevels() def inspect(anObject): from direct.tkpanels import Inspector Inspector.inspect(anObject) __builtins__['inspect'] = inspect if not __debug__ and __dev__: notify = directNotify.newCategory('ShowBaseGlobal') notify.error("You must set 'want-dev' to false in non-debug mode.") taskMgr.finalInit() # The VirtualFileSystem, which has already initialized, doesn't see the mount # directives in the config(s) yet. We have to force it to load those manually: from panda3d.core import VirtualFileSystem, ConfigVariableList, Filename vfs = VirtualFileSystem.getGlobalPtr() mounts = ConfigVariableList('vfs-mount') for mount in mounts: mountfile, mountpoint = (mount.split(' ', 2) + [None, None, None])[:2] vfs.mount(Filename(mountfile), Filename(mountpoint), 0)
def setP3DFilename(self, p3dFilename, tokens, argv, instanceId, interactiveConsole, p3dOffset = 0, p3dUrl = None): """ Called by the browser to specify the p3d file that contains the application itself, along with the web tokens and/or command-line arguments. Once this method has been called, the application is effectively started. """ # One day we will have support for multiple instances within a # Python session. Against that day, we save the instance ID # for this instance. self.instanceId = instanceId self.tokens = tokens self.argv = argv # We build up a token dictionary with care, so that if a given # token appears twice in the token list, we record only the # first value, not the second or later. This is consistent # with the internal behavior of the core API. self.tokenDict = {} for token, keyword in tokens: self.tokenDict.setdefault(token, keyword) # Also store the arguments on sys, for applications that # aren't instance-ready. sys.argv = argv # That means we now know the altHost in effect. self.altHost = self.tokenDict.get('alt_host', None) # Tell the browser that Python is up and running, and ready to # respond to queries. self.notifyRequest('onpythonload') # Now go load the applet. fname = Filename.fromOsSpecific(p3dFilename) vfs = VirtualFileSystem.getGlobalPtr() if not vfs.exists(fname): raise ArgumentError, "No such file: %s" % (p3dFilename) fname.makeAbsolute() fname.setBinary() mf = Multifile() if p3dOffset == 0: if not mf.openRead(fname): raise ArgumentError, "Not a Panda3D application: %s" % (p3dFilename) else: if not mf.openRead(fname, p3dOffset): raise ArgumentError, "Not a Panda3D application: %s at offset: %s" % (p3dFilename, p3dOffset) # Now load the p3dInfo file. self.p3dInfo = None self.p3dPackage = None self.p3dConfig = None self.allowPythonDev = False i = mf.findSubfile('p3d_info.xml') if i >= 0 and hasattr(core, 'readXmlStream'): stream = mf.openReadSubfile(i) self.p3dInfo = core.readXmlStream(stream) mf.closeReadSubfile(stream) if self.p3dInfo: self.p3dPackage = self.p3dInfo.FirstChildElement('package') if self.p3dPackage: self.p3dConfig = self.p3dPackage.FirstChildElement('config') xhost = self.p3dPackage.FirstChildElement('host') while xhost: self.__readHostXml(xhost) xhost = xhost.NextSiblingElement('host') if self.p3dConfig: allowPythonDev = self.p3dConfig.Attribute('allow_python_dev') if allowPythonDev: self.allowPythonDev = int(allowPythonDev) guiApp = self.p3dConfig.Attribute('gui_app') if guiApp: self.guiApp = int(guiApp) trueFileIO = self.p3dConfig.Attribute('true_file_io') if trueFileIO: self.trueFileIO = int(trueFileIO) # The interactiveConsole flag can only be set true if the # application has allow_python_dev set. if not self.allowPythonDev and interactiveConsole: raise StandardError, "Impossible, interactive_console set without allow_python_dev." self.interactiveConsole = interactiveConsole if self.allowPythonDev: # Set the fps text to remind the user that # allow_python_dev is enabled. ConfigVariableString('frame-rate-meter-text-pattern').setValue('allow_python_dev %0.1f fps') if self.guiApp: init_app_for_gui() self.initPackedAppEnvironment() # Mount the Multifile under self.multifileRoot. vfs.mount(mf, self.multifileRoot, vfs.MFReadOnly) self.p3dMultifile = mf VFSImporter.reloadSharedPackages() self.loadMultifilePrcFiles(mf, self.multifileRoot) self.gotP3DFilename = True self.p3dFilename = fname if p3dUrl: # The url from which the p3d file was downloaded is # provided if available. It is only for documentation # purposes; the actual p3d file has already been # downloaded to p3dFilename. self.p3dUrl = core.URLSpec(p3dUrl) # Send this call to the main thread; don't call it directly. messenger.send('AppRunner_startIfReady', taskChain = 'default')
def installPackage(self, appRunner): """ Mounts the package and sets up system paths so it becomes available for use. Returns true on success, false on failure. """ assert self.hasPackage if self.installed: # Already installed. return True assert self not in appRunner.installedPackages mfPathname = Filename(self.getPackageDir(), self.uncompressedArchive.filename) mf = Multifile() if not mf.openRead(mfPathname): self.notify.warning("Couldn't open %s" % (mfPathname)) return False # We mount it under its actual location on disk. root = self.getPackageDir() vfs = VirtualFileSystem.getGlobalPtr() vfs.mount(mf, root, vfs.MFReadOnly) # Add this to the Python search path, if it's not already # there. We have to take a bit of care to check if it's # already there, since there can be some ambiguity in # os-specific path strings. osRoot = self.getPackageDir().toOsSpecific() foundOnPath = False for p in sys.path: if osRoot == p: # Already here, exactly. foundOnPath = True break elif osRoot == Filename.fromOsSpecific(p).toOsSpecific(): # Already here, with some futzing. foundOnPath = True break if not foundOnPath: # Not already here; add it. sys.path.append(osRoot) # Put it on the model-path, too. We do this indiscriminantly, # because the Panda3D runtime won't be adding things to the # model-path, so it shouldn't be already there. getModelPath().appendDirectory(self.getPackageDir()) # Set the environment variable to reference the package root. envvar = '%s_ROOT' % (self.packageName.upper()) ExecutionEnvironment.setEnvironmentVariable(envvar, osRoot) # Add the package root to the system paths. if sys.platform.startswith('win'): path = os.environ.get('PATH', '') os.environ['PATH'] = "%s;%s" % (osRoot, path) else: path = os.environ.get('PATH', '') os.environ['PATH'] = "%s:%s" % (osRoot, path) path = os.environ.get('LD_LIBRARY_PATH', '') os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (osRoot, path) if sys.platform == "darwin": path = os.environ.get('DYLD_LIBRARY_PATH', '') os.environ['DYLD_LIBRARY_PATH'] = "%s:%s" % (osRoot, path) # Now that the environment variable is set, read all of the # prc files in the package. appRunner.loadMultifilePrcFiles(mf, self.getPackageDir()) # Also, find any toplevel Python packages, and add these as # shared packages. This will allow different packages # installed in different directories to share Python files as # if they were all in the same directory. for filename in mf.getSubfileNames(): if filename.endswith('/__init__.pyc') or \ filename.endswith('/__init__.pyo') or \ filename.endswith('/__init__.py'): components = filename.split('/')[:-1] moduleName = '.'.join(components) VFSImporter.sharedPackages[moduleName] = True # Fix up any shared directories so we can load packages from # disparate locations. VFSImporter.reloadSharedPackages() self.installed = True appRunner.installedPackages.append(self) self.markUsed() return True
def read(self, levelFilename, isInsideMF=True): """This function reads the given level file and store the data for further use inside the self.levelPhysics and self.levelPhysics.level variables""" # use try except block for reading the xml file # if something happen, we simply return False to # indicate the loading failed try: if isInsideMF: # as we can't parse files which are inside multifiles, # we need to read them with the vfs and then parse the String from panda3d.core import VirtualFileSystem vfs = VirtualFileSystem.getGlobalPtr() lvlFile = vfs.readFile(levelFilename, False) levelTree = ElementTree.XML(lvlFile) else: lvlFile = levelFilename levelTree = ElementTree.parse(lvlFile) # read some basic informations of the level like # author name and creation date author = levelTree.find("author") if author != None: self.leveldata.author = author.text date = levelTree.find("date") if date != None: self.leveldata.date = date.text name = levelTree.find("name") if name != None: self.leveldata.name = name.text model = self.__readModel(levelTree.find("baseModel")) if model != None: self.leveldata.model = model else: # We have a problem with loading the base model return False collision = levelTree.find("collisionModel") if collision != None: colModel = self.__readModel(levelTree.find("collisionModel")) if colModel != None: self.leveldata.colModel = colModel walls = levelTree.find("wallCollision") if walls != None: colWall = self.__readCollisionModel(walls) if colWall != None: self.leveldata.colWall = colWall colGround = self.__readCollisionModel( levelTree.find("groundCollision")) if colGround != None: self.leveldata.colGround = colGround wallRunSensor = SensorWallRun() wallRunSensor.sensorID = "wallrun" if self.leveldata.colWall != None: wallRunSensor.model = self.leveldata.colWall elif self.leveldata.colModel != None: wallRunSensor.model = self.leveldata.colModel elif self.leveldata.colGround != None: wallRunSensor.model = self.leveldata.colGround wallRunSensor.sensorType = "wallRuns" self.leveldata.sensors.append(wallRunSensor) startPos = levelTree.find("startPos") if startPos != None: pos = self.__readPos(startPos) self.leveldata.playerStartPos = pos hpr = self.__readHpr(startPos) self.leveldata.playerStartHpr = hpr if levelTree.find("exit") is not None: colExit = self.__readCollisionModel(levelTree.find("exit")) if colExit != None: sensor = SensorExit() sensor.sensorID = "exit" sensor.model = colExit sensor.sensorType = "exit" self.leveldata.sensors.append(sensor) objects = levelTree.find("objects") if objects != None: self.__readObjects(objects) sensors = levelTree.find("sensors") if sensors != None: self.__readSensors(sensors) lights = levelTree.find("lights") if lights != None: self.__readLights(lights) aiUnits = levelTree.find("aiUnits") if aiUnits != None: self.__readAIUnits(aiUnits) except: logging.error("Error while loading level: %s %s", levelFilename, sys.exc_info()) return False return True
def findDataFilename(name, extract=False, executable=False): """ Resolve a filename along Panda's model-path. :param name: :return: filename or None """ from panda3d.core import Filename, getModelPath from panda3d.core import VirtualFileSystem logging.debug("findDataFilename: "+ name +" on: \n" + str(getModelPath().getValue())) vfs = VirtualFileSystem.getGlobalPtr() fileName = Filename(name) vfile = vfs.findFile(fileName, getModelPath().getValue()) if not vfile: if extract and name.endswith(".exe"): fileName = Filename(name[:-4]) vfile = vfs.findFile(fileName, getModelPath().getValue()) if not vfile: return None fileName = vfile.getFilename() if extract: # see if the file is embedded in some virtual place OR has the wrong perms from panda3d.core import SubfileInfo info = SubfileInfo() needsCopy = not vfile.getSystemInfo(info) or info.getFilename() != fileName if not needsCopy: if executable: # see if on Linux or OSX and not executable try: stat = os.stat(fileName.toOsSpecific()) if (stat.st_mode & 0111) == 0: logging.error("Found %s locally, but not marked executable!", fileName) needsCopy = True except: needsCopy = True if needsCopy: # virtual file needs to be copied out global _tempDir if not _tempDir: import tempfile _tempDir = os.path.realpath(tempfile.mkdtemp()) #print "Temp dir:",_tempDir xpath = _tempDir + '/' + fileName.getBasename() xTarg = Filename.fromOsSpecific(xpath) # on Windows, case-sensitivity must be honored for the following to work xTarg.makeCanonical() print "extracting",fileName,"to",xTarg if not xTarg.exists(): if not vfs.copyFile(fileName, xTarg): raise IOError("extraction failed when copying " + str(fileName) + " to " + str(xTarg)) fileName = xTarg os.chmod(fileName.toOsSpecific(), 0777) return fileName
def __init__(self, browser, texture): self.browser = browser self.texture = texture self.vfs = VirtualFileSystem.getGlobalPtr()