Beispiel #1
0
    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)
Beispiel #3
0
 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
Beispiel #4
0
    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)
Beispiel #5
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 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)
Beispiel #6
0
    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
Beispiel #7
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!"
Beispiel #8
0
def main():
    args = parse_args()

    if args.frames:
        animations_frames = map(int, args.frames.split(','))
    else:
        animations_frames = [len(args.input)]

    kwargs = {}
    if args.fps:
        kwargs['fps'] = args.fps
    if args.scale:
        kwargs['scale'] = args.scale
    if args.type:
        kwargs['type'] = args.type
    if args.empty:
        kwargs['empty'] = args.empty
    if args.prefix:
        kwargs['prefix'] = args.prefix

    if args.prefix:
        vfs = VirtualFileSystem.get_global_ptr()
        vfs.mount(
            Filename.from_os_specific('.').get_fullpath(),
            args.prefix.rstrip('/'), 0)
        mp = get_model_path()
        mp.prepend_directory(args.prefix.rstrip('/'))

    cm = CardMaker(animations_frames, args.input, **kwargs)
    cm.make(args.output)
Beispiel #9
0
    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 load(self, filename):
        """ Loads a profile from a given filename """

        # Make filename unique

        fname = Filename.from_os_specific(filename)
        if not VirtualFileSystem.get_global_ptr().resolve_filename(fname, get_model_path().get_value(), "ies"):
            self.error("Could not resolve", filename)
            return -1
        fname = fname.get_fullpath()

        # Check for cache entries
        if fname in self._entries:
            return self._entries.index(fname)

        # Check for out of bounds
        if len(self._entries) >= self._max_entries:
            # TODO: Could remove unused profiles here or regenerate texture
            self.warn("Cannot load IES Profile, too many loaded! (Maximum: 32)")

        # Try loading the dataset, and see what happes
        try:
            dataset = self._loader.load(fname)
        except IESLoaderException as msg:
            self.warn("Failed to load profile from", filename, ":", msg)
            return -1

        if not dataset:
            return -1

        # Dataset was loaded successfully, now copy it
        dataset.generate_dataset_texture_into(self._storage_tex, len(self._entries))
        self._entries.append(fname)

        return len(self._entries) - 1
 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()
Beispiel #13
0
    def __init__(self):
        self.loadDefaultConfig()
        self.loadLocalConfig()

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

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

        self.vfs = VirtualFileSystem.getGlobalPtr()

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

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

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

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

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

        builtins.base = self

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

        #
        # Variables pertaining to simulation ticks.
        #

        self.prevRemainder = 0
        self.remainder = 0
        # What is the current overall simulation tick?
        self.tickCount = 0
        # How many ticks are we going to run this frame?
        self.totalTicksThisFrame = 0
        # How many ticks have we run so far this frame?
        self.currentTicksThisFrame = 0
        # What tick are we currently on this frame?
        self.currentFrameTick = 0
        # How many simulations ticks are we running per-second?
        self.ticksPerSec = 60
        self.intervalPerTick = 1.0 / self.ticksPerSec
 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')
Beispiel #15
0
    def mount_multifile(self):
        mf = Multifile()
        mf.open_read(Filename.from_os_specific('phase_1.ef'))
        mf.set_encryption_flag(True)
        mf.set_encryption_password(self.PW)

        if not VirtualFileSystem.get_global_ptr().mount(mf, Filename('/'), 0):
            raise Exception('Multifile could not be mounted.')
Beispiel #16
0
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
Beispiel #17
0
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()
Beispiel #18
0
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
Beispiel #19
0
    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"))
Beispiel #20
0
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
Beispiel #21
0
 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 = []
Beispiel #22
0
    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)
Beispiel #23
0
def ramdir():
    """Fixture yielding a fresh ramdisk directory."""
    from panda3d.core import VirtualFileMountRamdisk, Filename

    vfs = VirtualFileSystem.get_global_ptr()
    mount = VirtualFileMountRamdisk()
    dir = Filename.temporary("/virtual", "ram.")
    assert vfs.mount(mount, dir, 0)

    yield dir
    vfs.unmount(mount)
    def __init__(self, filepath):
        self.filepath = filepath

        self.vfs = VirtualFileSystem.getGlobalPtr()

        if __debug__:
            self.mountPoint = "../resources"
        else:
            self.mountPoint = "/"

        self.sortOrder = []
Beispiel #25
0
 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 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()
Beispiel #27
0
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()
Beispiel #28
0
 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
Beispiel #29
0
    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 __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 = {}
Beispiel #31
0
    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
Beispiel #32
0
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!'
Beispiel #33
0
    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()
Beispiel #34
0
    def load_3d_texture(cls, fname, tile_size_x, tile_size_y=None, num_tiles=None):
        """ Loads a texture from the given filename and dimensions. If only
        one dimensions is specified, the other dimensions are assumed to be
        equal. This internally loads the texture into ram, splits it into smaller
        sub-images, and then calls the load_3d_texture from the Panda loader """

        # Generate a unique name to prevent caching
        tempfile_name = "$$SliceLoaderTemp-" + str(time.time()) + "/"

        # For quaddratic textures
        tile_size_y = tile_size_x if tile_size_y is None else tile_size_y
        num_tiles = tile_size_x if num_tiles is None else num_tiles

        # Load sliced image from disk
        source = PNMImage(fname)
        width = source.get_x_size()

        # Find slice properties
        num_cols = width // tile_size_x
        temp = PNMImage(
            tile_size_x, tile_size_y, source.get_num_channels(), source.get_maxval())

        # Construct a ramdisk to write the files to
        vfs = VirtualFileSystem.get_global_ptr()
        ramdisk = VirtualFileMountRamdisk()
        vfs.mount(ramdisk, tempfile_name, 0)

        # Extract all slices and write them to the virtual disk
        for z_slice in range(num_tiles):
            slice_x = (z_slice % num_cols) * tile_size_x
            slice_y = (z_slice // num_cols) * tile_size_y
            temp.copy_sub_image(source, 0, 0, slice_x, slice_y, tile_size_x, tile_size_y)
            temp.write(tempfile_name + str(z_slice) + ".png")

        # Load the de-sliced texture from the ramdisk
        texture_handle = Globals.loader.load3DTexture(tempfile_name + "/#.png")

        # This should never trigger, but can't hurt to have
        assert texture_handle.get_x_size() == tile_size_x
        assert texture_handle.get_y_size() == tile_size_y
        assert texture_handle.get_z_size() == num_tiles

        # Finally unmount the ramdisk
        vfs.unmount(ramdisk)

        return texture_handle
Beispiel #35
0
 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 mount(self):
        """ Inits the VFS Mounts. This creates the following virtual directory
        structure, from which all files can be located:

        /$$rp/  (Mounted from the render pipeline base directory)
           + config/
           + data/
           + rpcore/
           + shader/
           + ...

        /$$rptemp/ (Either ramdisk or user specified)
            + day_time_config
            + shader_auto_config
            + ...

         """
        self.debug("Setting up virtual filesystem")
        self._mounted = True

        def convert_path(pth):
            return Filename.from_os_specific(pth).get_fullpath()

        vfs = VirtualFileSystem.get_global_ptr()

        # Mount the pipeline temp path:
        # If no write path is specified, use a virtual ramdisk
        if self._write_path is None:
            self.debug("Mounting ramdisk as /$$rptemp")
            vfs.mount(VirtualFileMountRamdisk(), "/$$rptemp", 0)
        else:
            # In case an actual write path is specified:
            # Ensure the pipeline write path exists, and if not, create it
            if not isdir(self._write_path):
                self.debug(
                    "Creating temporary path, since it does not exist yet")
                try:
                    os.makedirs(self._write_path)
                except IOError as msg:
                    self.fatal("Failed to create temporary path:", msg)
            self.debug("Mounting", self._write_path, "as /$$rptemp")
            vfs.mount(convert_path(self._write_path), '/$$rptemp', 0)

        get_model_path().prepend_directory("/$$rp")
        get_model_path().prepend_directory("/$$rp/shader")
        get_model_path().prepend_directory("/$$rptemp")
Beispiel #37
0
    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)
Beispiel #38
0
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
Beispiel #39
0
    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)
Beispiel #40
0
    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()
Beispiel #41
0
    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 load(self, filename):
        """ Loads a profile from a given filename and returns the internal
        used index which can be assigned to a light."""

        # Make sure the user can load profiles directly from the ies profile folder
        data_path = join("/$$rp/data/ies_profiles/", filename)
        if isfile(data_path):
            filename = data_path

        # Make filename unique
        fname = Filename.from_os_specific(filename)
        if not VirtualFileSystem.get_global_ptr().resolve_filename(
                fname, get_model_path().get_value(), "ies"):
            self.error("Could not resolve", filename)
            return -1
        fname = fname.get_fullpath()

        # Check for cache entries
        if fname in self._entries:
            return self._entries.index(fname)

        # Check for out of bounds
        if len(self._entries) >= self._max_entries:
            # TODO: Could remove unused profiles here or regenerate texture
            self.warn("Cannot load IES Profile, too many loaded! (Maximum: 32)")

        # Try loading the dataset, and see what happes
        try:
            dataset = self._load_and_parse_file(fname)
        except InvalidIESProfileException as msg:
            self.warn("Failed to load profile from", filename, ":", msg)
            return -1

        if not dataset:
            return -1

        # Dataset was loaded successfully, now copy it
        dataset.generate_dataset_texture_into(self._storage_tex, len(self._entries))
        self._entries.append(fname)

        return len(self._entries) - 1
    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)
Beispiel #44
0
    def load_sliced_3d_texture(cls, fname, tile_size_x, tile_size_y=None, num_tiles=None):
        """ Loads a texture from the given filename and dimensions. If only
        one dimensions is specified, the other dimensions are assumed to be
        equal. This internally loads the texture into ram, splits it into smaller
        sub-images, and then calls the load_3d_texture from the Panda loader """

        tempfile_name = "/$$slice_loader_temp-" + str(time.time()) + "/"
        tile_size_y = tile_size_x if tile_size_y is None else tile_size_y
        num_tiles = tile_size_x if num_tiles is None else num_tiles

        # Load sliced image from disk
        source = PNMImage(fname)
        width = source.get_x_size()

        # Find slice properties
        num_cols = width // tile_size_x
        temp_img = PNMImage(
            tile_size_x, tile_size_y, source.get_num_channels(), source.get_maxval())

        # Construct a ramdisk to write the files to
        vfs = VirtualFileSystem.get_global_ptr()
        ramdisk = VirtualFileMountRamdisk()
        vfs.mount(ramdisk, tempfile_name, 0)

        # Extract all slices and write them to the virtual disk
        for z_slice in range(num_tiles):
            slice_x = (z_slice % num_cols) * tile_size_x
            slice_y = (z_slice // num_cols) * tile_size_y
            temp_img.copy_sub_image(source, 0, 0, slice_x, slice_y, tile_size_x, tile_size_y)
            temp_img.write(tempfile_name + str(z_slice) + ".png")

        # Load the de-sliced texture from the ramdisk
        texture_handle = cls.load_3d_texture(tempfile_name + "/#.png")
        vfs.unmount(ramdisk)

        return texture_handle
Beispiel #45
0
def createVFS():
    '''Generates vfs. First loads program VFS, then user directory overrides'''
    global vfs
    vfs = VirtualFileSystem()
    vfs.mount(Filename('.'), Filename('.'), 0)
    vfs.mount(Filename(getHome()), Filename('.'), 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)
Beispiel #47
0
    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
Beispiel #48
0
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
Beispiel #49
0
 def __init__(self, browser, texture):
     self.browser = browser
     self.texture = texture
     self.vfs = VirtualFileSystem.getGlobalPtr()
Beispiel #50
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')
Beispiel #51
0
    def mount(self):
        """ Inits the VFS Mounts. This creates the following virtual directory
        structure, from which all files can be located:

        /$$rp/  (Mounted from the render pipeline base directory)
           + rpcore/
           + shader/
           + ...

        /$rpconfig/ (Mounted from config/, may be set by user)
           + pipeline.yaml
           + ...

        /$$rptemp/ (Either ramdisk or user specified)
            + day_time_config
            + shader_auto_config
            + ...

        /$$rpshader/ (Link to /$$rp/rpcore/shader)

         """
        self.debug("Setting up virtual filesystem")
        self._mounted = True

        def convert_path(pth):
            return Filename.from_os_specific(pth).get_fullpath()
        vfs = VirtualFileSystem.get_global_ptr()

        # Mount config dir as $$rpconf
        if self._config_dir is None:
            config_dir = convert_path(join(self._base_path, "config/"))
            self.debug("Mounting auto-detected config dir:", config_dir)
            vfs.mount(config_dir, "/$$rpconfig", 0)
        else:
            self.debug("Mounting custom config dir:", self._config_dir)
            vfs.mount(convert_path(self._config_dir), "/$$rpconfig", 0)

        # Mount directory structure
        vfs.mount(convert_path(self._base_path), "/$$rp", 0)
        vfs.mount(convert_path(join(self._base_path, "rpcore/shader")), "/$$rp/shader", 0)
        vfs.mount(convert_path(join(self._base_path, "effects")), "effects", 0)

        # Mount the pipeline temp path:
        # If no write path is specified, use a virtual ramdisk
        if self._write_path is None:
            self.debug("Mounting ramdisk as /$$rptemp")
            vfs.mount(VirtualFileMountRamdisk(), "/$$rptemp", 0)
        else:
            # In case an actual write path is specified:
            # Ensure the pipeline write path exists, and if not, create it
            if not isdir(self._write_path):
                self.debug("Creating temporary path, since it does not exist yet")
                try:
                    os.makedirs(self._write_path)
                except IOError as msg:
                    self.fatal("Failed to create temporary path:", msg)
            self.debug("Mounting", self._write_path, "as /$$rptemp")
            vfs.mount(convert_path(self._write_path), '/$$rptemp', 0)

        get_model_path().prepend_directory("/$$rp")
        get_model_path().prepend_directory("/$$rp/shader")
        get_model_path().prepend_directory("/$$rptemp")
    def mount(self):
        """ Inits the VFS Mounts """

        self.debug("Setting up virtual filesystem.")
        self._mounted = True
        vfs = VirtualFileSystem.get_global_ptr()

        # Mount data and models
        dirs_to_mount = ["Data", "Effects", "Plugins", "Shader"]
        for directory in dirs_to_mount:
            vfs.mount_loop(join(self._base_path, directory), directory, 0)

        if isdir(join(self._base_path, "Models")):
            vfs.mount_loop(join(self._base_path, 'Models'), 'Models', 0)

        # Mount config dir
        if self._config_dir is None:
            config_dir = join(self._base_path, "Config/")
            vfs.mount_loop(config_dir, "$$Config/", 0)
            self.debug("Auto-Detected config dir:", config_dir)
        else:
            vfs.mount_loop(self._config_dir, "$$Config/", 0)
            self.debug("Config dir:", self._config_dir)


        # Convert the base path to something the os can work with
        sys_base_path = Filename(self._base_path).to_os_specific()

        # Add plugin folder to the include path
        sys.path.insert(0, join(sys_base_path, 'Plugins'))

        # Add current folder to the include path
        sys.path.insert(0, sys_base_path)

        # Mount the pipeline temp path:
        # If no write path is specified, use a virtual ramdisk
        if self._write_path is None:
            self.debug("Mounting ramdisk as $$PipelineTemp/")
            vfs.mount(VirtualFileMountRamdisk(), "$$PipelineTemp/", 0)
        else:
            # In case an actual write path is specified:
            # Ensure the pipeline write path exists, and if not, create it
            if not isdir(self._write_path):
                self.debug("Creating temp path, it does not exist yet")
                try:
                    os.makedirs(self._write_path)
                except IOError as msg:
                    self.fatal("Failed to create temp path:", msg)
            self.debug("Mounting", self._write_path, "as $$PipelineTemp/")
            vfs.mount_loop(self._write_path, '$$PipelineTemp/', 0)

        # #pragma include "something" searches in current directory first,
        # and then on the model-path. Append the Shader directory to the
        # modelpath to ensure the shader includes can be found.
        self._model_paths.append(join(self._base_path, "Shader"))

        # Add the pipeline root directory to the model path as well
        self._model_paths.append(self._base_path)
        self._model_paths.append(".")

        # Append the write path to the model directory to make pragma include
        # find the ShaderAutoConfig.include
        self._model_paths.append("$$PipelineTemp")

        # Add the plugins dir to the model path so plugins can include their
        # own resources more easily
        self._model_paths.append(join(self._base_path, "Plugins"))

        # Write the model paths to the global model path
        for pth in self._model_paths:
            get_model_path().append_directory(pth)
Beispiel #53
0
    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