def setInstanceInfo(self, rootDir, logDirectory, superMirrorUrl, verifyContents, main): """ Called by the browser to set some global information about the instance. """ # rootDir is the root Panda3D install directory on the local # machine. self.rootDir = Filename.fromOsSpecific(rootDir) # logDirectory is the directory name where all log files end # up. if logDirectory: self.logDirectory = Filename.fromOsSpecific(logDirectory) else: self.logDirectory = Filename(rootDir, 'log') # The "super mirror" URL, generally used only by panda3d.exe. self.superMirrorUrl = superMirrorUrl # How anxious should we be about contacting the server for # the latest code? self.verifyContents = verifyContents # The initial "main" object, if specified. if main is not None: self.main = main # Now that we have rootDir, we can read the config file. self.readConfigXml()
def setInstanceInfo(self, rootDir, logDirectory, superMirrorUrl, verifyContents, main): """ Called by the browser to set some global information about the instance. """ # rootDir is the root Panda3D install directory on the local # machine. self.rootDir = Filename.fromOsSpecific(rootDir) # logDirectory is the directory name where all log files end # up. if logDirectory: self.logDirectory = Filename.fromOsSpecific(logDirectory) else: self.logDirectory = Filename(rootDir, 'log') # The "super mirror" URL, generally used only by panda3d.exe. self.superMirrorUrl = superMirrorUrl # How anxious should we be about contacting the server for # the latest code? self.verifyContents = verifyContents # The initial "main" object, if specified. if main is not None: self.main = main # Now that we have rootDir, we can read the config file. self.readConfigXml()
def onCreateObject(self, e): """Invoked when the user hits one of the buttons in the "Create" menu.""" modelParent = modelController.getSelectedObject() if modelParent == None: modelParent = render objectInstance = None if e.Id == ID_NODEPATH: objectInstance = NodePathWrapper.onCreateInstance(modelParent) elif e.Id == ID_MODEL: filter = "Panda3D Egg Format (*.egg)|*.[eE][gG][gG];*.egg" filter += "|Panda3D Binary Format (*.bam)|*.[bB][aA][mM];*.bam" filter += "|MultiGen (*.flt)|*.[fF][lL][tT];*.flt" filter += "|Lightwave (*.lwo)|*.[lL][wW][oO];*.lwo" filter += "|AutoCAD (*.dxf)|*.[dD][xX][fF];*.dxf" filter += "|VRML (*.wrl)|*.[wW][rR][lL];*.wrl" filter += "|DirectX (*.x)|*.[xX];*.x" filter += "|COLLADA (*.dae)|*.[dD][aA][eE];*.dae" dlg = wx.FileDialog(self, "Select model", "", "", filter, wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: objectInstance = NodePathWrapper.onCreateInstance( modelParent, Filename.fromOsSpecific(dlg.GetPath()).getFullpath()) finally: dlg.Destroy() elif e.Id == ID_TERRAIN: filter = "Portable Network Graphics (*.png)|*.[pP][nN][gG];*.png" dlg = wx.FileDialog(self, "Select heightfield", "", "", filter, wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: objectInstance = GeoMipTerrainNodeWrapper.onCreateInstance( modelParent, Filename.fromOsSpecific(dlg.GetPath()).getFullpath()) finally: dlg.Destroy() elif e.Id == ID_AMBIENT: objectInstance = AmbientLightNodeWrapper.onCreateInstance( modelParent) elif e.Id == ID_DIRECTIONAL: objectInstance = DirectionalLightNodeWrapper.onCreateInstance( modelParent) elif e.Id == ID_POINT: objectInstance = PointLightNodeWrapper.onCreateInstance( modelParent) elif e.Id == ID_SPOT: objectInstance = SpotLightNodeWrapper.onCreateInstance(modelParent) if objectInstance != None: objectInstance.reparentTo(modelParent) objectInstance.enableEditmode() modelController.selectObject(objectInstance) messenger.send(EVENT_SCENEGRAPH_REFRESH)
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'))) found = vfs.resolveFilename(filename,searchPath) if not found: raise "Couldn't find direct/http/favicon.ico" return vfs.readFile(filename, 1)
def buildPandaPTZCamera(self, config): buffer = self.makeFBO("camera buffer") panda_camera = base.makeCamera(buffer) panda_camera.reparentTo(render) path = Filename.fromOsSpecific(os.path.dirname(__file__)) camera_model = loader.loadModel("%s/../camera/camera.egg" % path) camera_model.setScale(0.3) camera_model.reparentTo(render) panda_ptz_camera = PandaPTZCamera(buffer, panda_camera, camera_model) panda_ptz_camera.setColor(config.color) panda_ptz_camera.setId(config.id) panda_ptz_camera.setPos(config.position) panda_ptz_camera.setFovLimits(*config.fov_limits) panda_ptz_camera.setPanLimits(*config.pan_limits) panda_ptz_camera.setTiltLimits(*config.tilt_limits) panda_ptz_camera.setDefaultDirection(config.default_direction) panda_ptz_camera.setUp(config.up_vector) panda_ptz_camera.setNear(config.near_plane) panda_ptz_camera.setFar(config.far_plane) panda_ptz_camera.setFov(config.fov) panda_ptz_camera.setDefaultFov(config.default_fov) panda_ptz_camera.setPan(config.pan) panda_ptz_camera.setTilt(config.tilt) return panda_ptz_camera
def findNewsDir(self): """Returns the directory string for news content. Returns None if it cant find the directory """ if self.NewsOverHttp: # If we're running news-over-http, we dump the news into a # staging directory. return self.NewsStageDir searchPath = DSearchPath() if AppRunnerGlobal.appRunner: # In the web-publish runtime, it will always be here: searchPath.appendDirectory( Filename.expandFrom('$TT_3_5_ROOT/phase_3.5/models/news')) else: # In the launcher or dev environment, look here: basePath = os.path.expandvars('$TTMODELS') or './ttmodels' searchPath.appendDirectory( Filename.fromOsSpecific(basePath + '/built/' + self.NewsBaseDir)) searchPath.appendDirectory(Filename(self.NewsBaseDir)) pfile = Filename(self.NewsIndexFilename) found = vfs.resolveFilename(pfile, searchPath) if not found: self.notify.warning('findNewsDir - no path: %s' % self.NewsIndexFilename) self.setErrorMessage(TTLocalizer.NewsPageErrorDownloadingFile % self.NewsIndexFilename) return None self.notify.debug("found index file %s" % pfile) realDir = pfile.getDirname() return realDir
def onChooseFolder(self, evt): dialog = wx.DirDialog(None, "Choose a project directory", os.getcwd()) if dialog.ShowModal() == wx.ID_OK: self.dir = Filename.fromOsSpecific(dialog.GetPath()) self.dirText.SetLabel(self.dir.toOsSpecific()) if self.dir and self.projName: self.okButton.Enable(True)
def onChooseFolder(self, evt): dialog = wx.DirDialog(None, "Choose a project directory", os.getcwd()) if dialog.ShowModal() == wx.ID_OK: self.dir = Filename.fromOsSpecific(dialog.GetPath()) self.dirText.SetLabel(self.dir.toOsSpecific()) if self.dir and self.projName: self.okButton.Enable(True)
def decode_real_path (real_path): abs_real_path = os.path.abspath(real_path) enc_full_path = Filename.fromOsSpecific(abs_real_path).getFullpath() enc = locale.getpreferredencoding() full_path = enc_full_path.decode(enc) return full_path
def onOpen(self, evt=None): filter = "Panda3D Egg Scene Format (*.egs)|*.[eE][gG][sS];*.egs" #filter += "|Panda3D Compressed Egg Format (*.egg.pz)|*.[eE][gG][gG].[pP][zZ];*.egg.pz" #filter += "|Panda3D Binary Format (*.bam)|*.[bB][aA][mM];*.bam" #filter += "|Panda3D Compressed Binary Format (*.bam)|*.[bB][aA][mM].[pP][zZ];*.bam.pz" ''' # disabled by hypnos, making the loading work filter += "|MultiGen (*.flt)|*.[fF][lL][tT]" filter += "|Lightwave (*.lwo)|*.[lL][wW][oO]" filter += "|AutoCAD (*.dxf)|*.[dD][xX][fF]" filter += "|VRML (*.wrl)|*.[wW][rR][lL]" filter += "|DirectX (*.x)|*.[xX]" filter += "|COLLADA (*.dae)|*.[dD][aA][eE]" ''' dlg = wx.FileDialog(self, "Load file", "", "", filter, wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: #self.filename = Filename.fromOsSpecific(dlg.GetPath()) p3dFilename = Filename.fromOsSpecific(dlg.GetPath()) self.filename = str(dlg.GetPath()) self.SetTitle(p3dFilename.getBasename() + " - Panda Editor") self.modified = False self.editorInstance.loadEggModelsFile(self.filename) # Reset the camera if base.trackball != None: base.trackball.node().setPos(0, 30, 0) base.trackball.node().setHpr(0, 15, 0) self.onCenterTrackball() if p3dFilename.getExtension().lower() != "bam": self.filename = Filename() self.modified = True self.sceneGraphTree.reload() finally: dlg.Destroy()
def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--dir', dest='directory', required=True, help='the directory where the config files are located') parser.add_argument('-p', '--port', dest='port', type=int, default=9099, help='the port the server should run on') parser.add_argument('-a', '--automatic', dest='mode', action='store_const', const=AUTOMATIC, default=MANUAL, help='set the mode of the simulation controller to automatic') parser.add_argument('-s', '--sync', dest='sync', action='store_true', default=False, help='a Sync session is used to control the time') parser.add_argument('-m', '--models', dest='models', help='the directory where the models are located') parser.add_argument('--debug', dest='debug', action='store_const', const=logging.DEBUG, default=logging.INFO, help='show debug messages') args = parser.parse_args() logging.basicConfig(format='%(levelname)s: %(message)s', level=args.debug) # Create the virtual world by loading all of the models that make up the # scene as well as all of the pedestrians. virtual_world = VirtualWorld(os.path.join(args.directory, 'scene.xml'), os.path.join(args.directory, 'pedestrians.xml'), Filename.fromOsSpecific(args.directory), args.mode) model = virtual_world.getModel() # Create the camera manager which keeps track of what cameras are linked to # what Vision Processing clients. Also acts as a message sender used to send # messages between cameras camera_manager = CameraManager() # Load all of the camera modules. # Each camera module is linked with a panda camera that has the ability to # render to a texture that can be processed using opencv. camera_file = os.path.join(args.directory, 'cameras.xml') if not os.path.exists(camera_file): logging.error("The path '%s' does not exist" % camera_file) sys.exit() parser = CameraFileParser() configs = parser.parse(camera_file) camera_builder = CameraBuilder() for config in configs: cam_module = camera_builder.buildCamera(config) if not cam_module: continue model.addCameraModule(cam_module) cam_type = cam_module.getType() camera_manager.addCamera(cam_module) camera = virtual_world.addCamera(config) cam_module.setPandaCamera(camera) cam_module.setCameraManager(camera_manager) # Create the server object that listens for incoming messages and connection # requests from other modules. if args.mode != AUTOMATIC: server = SocketServer(args.port, virtual_world, camera_manager, args.sync) # Start the main event loop that runs the world. virtual_world.run()
def parseSysArgs(): """ Handles sys.argv, if there are any local arguments, and returns a new argv suitable for passing into the application. """ # We prefix a "+" sign, following the GNU convention, to tell # getopt not to parse options following the first non-option # parameter. opts, args = getopt.getopt(sys.argv[1:], '+h') for option, value in opts: if option == '-h': print __doc__ sys.exit(1) if not args or not args[0]: raise ArgumentError, "No Panda app specified. Use:\nrunp3d.py app.p3d" arg0 = args[0] p3dFilename = Filename.fromOsSpecific(arg0) if p3dFilename.exists(): p3dFilename.makeAbsolute() arg0 = p3dFilename.toOsSpecific() return [arg0] + args[1:]
def onOpen(self, evt = None): filter = "Panda3D Egg Scene Format (*.egs)|*.[eE][gG][sS];*.egs" #filter += "|Panda3D Compressed Egg Format (*.egg.pz)|*.[eE][gG][gG].[pP][zZ];*.egg.pz" #filter += "|Panda3D Binary Format (*.bam)|*.[bB][aA][mM];*.bam" #filter += "|Panda3D Compressed Binary Format (*.bam)|*.[bB][aA][mM].[pP][zZ];*.bam.pz" ''' # disabled by hypnos, making the loading work filter += "|MultiGen (*.flt)|*.[fF][lL][tT]" filter += "|Lightwave (*.lwo)|*.[lL][wW][oO]" filter += "|AutoCAD (*.dxf)|*.[dD][xX][fF]" filter += "|VRML (*.wrl)|*.[wW][rR][lL]" filter += "|DirectX (*.x)|*.[xX]" filter += "|COLLADA (*.dae)|*.[dD][aA][eE]" ''' dlg = wx.FileDialog(self, "Load file", "", "", filter, wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: #self.filename = Filename.fromOsSpecific(dlg.GetPath()) p3dFilename = Filename.fromOsSpecific(dlg.GetPath()) self.filename = str(dlg.GetPath()) self.SetTitle(p3dFilename.getBasename() + " - Panda Editor") self.modified = False self.editorInstance.loadEggModelsFile( self.filename ) # Reset the camera if base.trackball != None: base.trackball.node().setPos(0, 30, 0) base.trackball.node().setHpr(0, 15, 0) self.onCenterTrackball() if p3dFilename.getExtension().lower() != "bam": self.filename = Filename() self.modified = True self.sceneGraphTree.reload() finally: dlg.Destroy()
def __init__(self): ShowBase.__init__(self) #Disable standard mouse camera movement #base.disableMouse() #Exit app on escape key base.accept("escape", sys.exit) #Get the location of MainGame.py projectdir = os.path.abspath(sys.path[0]) #convert it to Panda's unix-style notation. projectdir = Filename.fromOsSpecific(projectdir).getFullpath() #TODO - Load the level model here #base.wireframeOn() #self.environ = self.loader.loadModel(projectdir + "/models/levels/ThePlayground") #Load the default environment model from the panda Tutorial self.environ = self.loader.loadModel(projectdir + "/models/levels/environment") #Reparent the model to the root of the Scenegraph, aka the "render" node #this allows for the object to actually appear on screen self.environ.reparentTo(self.render) #Scale and position the level/environment model self.environ.setScale(0.25, 0.25, 0.25) self.environ.setPos(-8, 42, 0) #TODO add camera controls to a function that can be added to the taskMgr #Handle camera controls here controls = BasicControls() #controls.startMovement() self.taskMgr.add(controls.movement, 'movement') self.taskMgr.add(controls.walk, 'walk')
def get_path_modelo(nome_modelo): from pandac.PandaModules import Filename import sys winfile = sys.path[0] + "\\Modelos\\" + nome_modelo pandafile = Filename.fromOsSpecific(winfile) return pandafile
def changeMap(self, newMap="map.png"): # self.frameMap["image"] = newMap # self.frameMap.setImage() self.frameMap.clearTexture() TexturePool.releaseTexture(self.tex) self.tex = loader.loadTexture( Filename.fromOsSpecific(os.path.join(self.path, newMap))) self.frameMap["frameTexture"] = self.tex
def exportScripts(self, file): outputLines = [] tab = " " outputLines.append("SCRIPTS_LIST = []\n\n") #whole file for script, asset in self.editor.lib.scripts.iteritems(): #writing a script file to the whole file filename = self.editor.lib.scripts[script].getFullFilename() scriptFile = open(filename.toOsSpecific()) lines = scriptFile.readlines() mainArguments = self.getArgumentsFromScriptFile(lines) scriptFunctionName = script if (len(mainArguments) == 0): prefix = "world" else: prefix = "world, " functionHeader = "\ndef " + scriptFunctionName + "(" + prefix + ",".join( mainArguments) + "):\n" mainFunc = "main(" + prefix + ",".join(mainArguments) + ")" mainFuncHeader = "def " + mainFunc + ":\n" outputLines.append(functionHeader) isReturn = False for line in lines: #print line if line.strip().startswith("#"): continue if line.strip().startswith("def main"): newline = mainFuncHeader elif line.find("Interface") != -1: newline = line.replace('Interface', "world.scriptInterface") else: newline = line if line.strip().startswith("return"): isReturn = True outputLines.append(tab + newline) if (isReturn): outputLines.append("\n" + tab + "return " + mainFunc) else: outputLines.append("\n" + tab + mainFunc) outputLines.append("\nSCRIPTS_LIST.append(" + scriptFunctionName + ")\n") scriptFile.close() scriptsFilename = Filename( Filename.fromOsSpecific(file).getDirname() + '/Scripts.py') try: scriptsFile = open(scriptsFilename.toOsSpecific(), 'w') except IOError: print "ERROR: Couldn't open the script file for writing" scriptsFile.writelines(outputLines) scriptsFile.close() return scriptsFilename
def makeBundle(startDir): fstartDir = Filename.fromOsSpecific(startDir) # Search for panda3d_mac along $PATH. path = DSearchPath() if 'PATH' in os.environ: path.appendPath(os.environ['PATH']) path.appendPath(os.defpath) panda3d_mac = path.findFile('panda3d_mac') if not panda3d_mac: raise StandardError, "Couldn't find panda3d_mac on path." # Construct a search path to look for the images. search = DSearchPath() # First on the path: an explicit $PLUGIN_IMAGES env var. if ExecutionEnvironment.hasEnvironmentVariable('PLUGIN_IMAGES'): search.appendDirectory(Filename.expandFrom('$PLUGIN_IMAGES')) # Next on the path: the models/plugin_images directory within the # current directory. search.appendDirectory('models/plugin_images') # Finally on the path: models/plugin_images within the model # search path. for dir in getModelPath().getDirectories(): search.appendDirectory(Filename(dir, 'plugin_images')) # Now find the icon file on the above search path. icons = search.findFile('panda3d.icns') if not icons: raise StandardError, "Couldn't find panda3d.icns on model-path." # Generate the bundle directory structure rootFilename = Filename(fstartDir) bundleFilename = Filename(rootFilename, 'Panda3D.app') if os.path.exists(bundleFilename.toOsSpecific()): shutil.rmtree(bundleFilename.toOsSpecific()) plistFilename = Filename(bundleFilename, 'Contents/Info.plist') plistFilename.makeDir() exeFilename = Filename(bundleFilename, 'Contents/MacOS/panda3d_mac') exeFilename.makeDir() iconFilename = Filename(bundleFilename, 'Contents/Resources/panda3d.icns') iconFilename.makeDir() # Copy in Info.plist, the icon file, and the compiled executable. shutil.copyfile( Filename(fstartDir, "panda3d_mac.plist").toOsSpecific(), plistFilename.toOsSpecific()) shutil.copyfile(icons.toOsSpecific(), iconFilename.toOsSpecific()) print panda3d_mac, exeFilename shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific()) os.chmod(exeFilename.toOsSpecific(), 0755) # All done! bundleFilename.touch() print bundleFilename.toOsSpecific()
def exportScripts(self, file): outputLines = [] tab = " " outputLines.append("SCRIPTS_LIST = []\n\n") #whole file for script, asset in self.editor.lib.scripts.iteritems(): #writing a script file to the whole file filename = self.editor.lib.scripts[script].getFullFilename() scriptFile = open(filename.toOsSpecific()) lines = scriptFile.readlines() mainArguments = self.getArgumentsFromScriptFile(lines) scriptFunctionName = script if(len(mainArguments) == 0): prefix = "world" else: prefix = "world, " functionHeader = "\ndef "+scriptFunctionName+"("+prefix+",".join(mainArguments)+"):\n" mainFunc = "main("+prefix+",".join(mainArguments)+")" mainFuncHeader = "def "+mainFunc+":\n" outputLines.append(functionHeader) isReturn = False for line in lines: #print line if line.strip().startswith("#"): continue if line.strip().startswith("def main"): newline = mainFuncHeader elif line.find("Interface")!=-1: newline = line.replace('Interface', "world.scriptInterface") else: newline = line if line.strip().startswith("return"): isReturn = True outputLines.append(tab+newline) if(isReturn): outputLines.append("\n"+tab+"return "+mainFunc) else: outputLines.append("\n"+tab+mainFunc) outputLines.append("\nSCRIPTS_LIST.append("+scriptFunctionName+")\n") scriptFile.close() scriptsFilename = Filename(Filename.fromOsSpecific(file).getDirname()+'/Scripts.py') try: scriptsFile = open(scriptsFilename.toOsSpecific(), 'w') except IOError: print "ERROR: Couldn't open the script file for writing" scriptsFile.writelines(outputLines) scriptsFile.close() return scriptsFilename
def onCreateObject(self, e): """Invoked when the user hits one of the buttons in the "Create" menu.""" modelParent = modelController.getSelectedObject() if modelParent == None: modelParent = render objectInstance = None if e.Id == ID_NODEPATH: objectInstance = NodePathWrapper.onCreateInstance(modelParent) elif e.Id == ID_MODEL: filter = "Panda3D Egg Format (*.egg)|*.[eE][gG][gG];*.egg" filter += "|Panda3D Binary Format (*.bam)|*.[bB][aA][mM];*.bam" filter += "|MultiGen (*.flt)|*.[fF][lL][tT];*.flt" filter += "|Lightwave (*.lwo)|*.[lL][wW][oO];*.lwo" filter += "|AutoCAD (*.dxf)|*.[dD][xX][fF];*.dxf" filter += "|VRML (*.wrl)|*.[wW][rR][lL];*.wrl" filter += "|DirectX (*.x)|*.[xX];*.x" filter += "|COLLADA (*.dae)|*.[dD][aA][eE];*.dae" dlg = wx.FileDialog(self, "Select model", "", "", filter, wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: objectInstance = NodePathWrapper.onCreateInstance(modelParent, Filename.fromOsSpecific(dlg.GetPath()).getFullpath()) finally: dlg.Destroy() elif e.Id == ID_TERRAIN: filter = "Portable Network Graphics (*.png)|*.[pP][nN][gG];*.png" dlg = wx.FileDialog(self, "Select heightfield", "", "", filter, wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: objectInstance = GeoMipTerrainNodeWrapper.onCreateInstance(modelParent, Filename.fromOsSpecific(dlg.GetPath()).getFullpath()) finally: dlg.Destroy() elif e.Id == ID_AMBIENT: objectInstance = AmbientLightNodeWrapper.onCreateInstance(modelParent) elif e.Id == ID_DIRECTIONAL: objectInstance = DirectionalLightNodeWrapper.onCreateInstance(modelParent) elif e.Id == ID_POINT: objectInstance = PointLightNodeWrapper.onCreateInstance(modelParent) elif e.Id == ID_SPOT: objectInstance = SpotLightNodeWrapper.onCreateInstance(modelParent) if objectInstance != None: objectInstance.reparentTo(modelParent) objectInstance.enableEditmode() modelController.selectObject(objectInstance) messenger.send(EVENT_SCENEGRAPH_REFRESH)
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'))) found = vfs.resolveFilename(filename, searchPath) if not found: raise "Couldn't find direct/http/favicon.ico" return vfs.readFile(filename, 1)
def makeBundle(startDir): fstartDir = Filename.fromOsSpecific(startDir) # Search for panda3d_mac along $PATH. path = DSearchPath() if 'PATH' in os.environ: path.appendPath(os.environ['PATH']) path.appendPath(os.defpath) panda3d_mac = path.findFile('panda3d_mac') if not panda3d_mac: raise StandardError, "Couldn't find panda3d_mac on path." # Construct a search path to look for the images. search = DSearchPath() # First on the path: an explicit $PLUGIN_IMAGES env var. if ExecutionEnvironment.hasEnvironmentVariable('PLUGIN_IMAGES'): search.appendDirectory(Filename.expandFrom('$PLUGIN_IMAGES')) # Next on the path: the models/plugin_images directory within the # current directory. search.appendDirectory('models/plugin_images') # Finally on the path: models/plugin_images within the model # search path. for dir in getModelPath().getDirectories(): search.appendDirectory(Filename(dir, 'plugin_images')) # Now find the icon file on the above search path. icons = search.findFile('panda3d.icns') if not icons: raise StandardError, "Couldn't find panda3d.icns on model-path." # Generate the bundle directory structure rootFilename = Filename(fstartDir) bundleFilename = Filename(rootFilename, 'Panda3D.app') if os.path.exists(bundleFilename.toOsSpecific()): shutil.rmtree(bundleFilename.toOsSpecific()) plistFilename = Filename(bundleFilename, 'Contents/Info.plist') plistFilename.makeDir() exeFilename = Filename(bundleFilename, 'Contents/MacOS/panda3d_mac') exeFilename.makeDir() iconFilename = Filename(bundleFilename, 'Contents/Resources/panda3d.icns') iconFilename.makeDir() # Copy in Info.plist, the icon file, and the compiled executable. shutil.copyfile(Filename(fstartDir, "panda3d_mac.plist").toOsSpecific(), plistFilename.toOsSpecific()) shutil.copyfile(icons.toOsSpecific(), iconFilename.toOsSpecific()) print panda3d_mac, exeFilename shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific()) os.chmod(exeFilename.toOsSpecific(), 0755) # All done! bundleFilename.touch() print bundleFilename.toOsSpecific()
def buildDmg(startDir): fstartDir = Filename.fromOsSpecific(startDir) rootFilename = Filename(fstartDir, 'bundle') output = Filename(fstartDir, 'nppanda3d.dmg') output.unlink() cmd = 'hdiutil create -fs HFS+ -srcfolder "%(dir)s" -volname "%(volname)s" "%(output)s"' % { 'dir' : rootFilename.toOsSpecific(), 'volname' : 'nppanda3d', 'output' : output.toOsSpecific(), } os.system(cmd)
def buildDmg(startDir): fstartDir = Filename.fromOsSpecific(startDir) rootFilename = Filename(fstartDir, 'bundle') output = Filename(fstartDir, 'nppanda3d.dmg') output.unlink() cmd = 'hdiutil create -fs HFS+ -srcfolder "%(dir)s" -volname "%(volname)s" "%(output)s"' % { 'dir': rootFilename.toOsSpecific(), 'volname': 'nppanda3d', 'output': output.toOsSpecific(), } os.system(cmd)
def onChooseFile(self, evt): dlg = wx.FileDialog(None, "Choose a project to merge with.", wildcard="*.proj", style=wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.file = Filename.fromOsSpecific(dlg.GetPath()) self.txtPrefix.SetValue(self.file.getBasenameWoExtension()) self.txtPath.SetValue(self.file.toOsSpecific()) self.txtPrefix.Enable(True) self.chkParentToNewNode.Enable(True) self.btnMerge.Enable(True) dlg.Destroy()
def onChooseFile(self, evt): dlg = wx.FileDialog(None, "Choose a project to merge with.", wildcard="*.proj", style=wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.file = Filename.fromOsSpecific(dlg.GetPath()) self.txtPrefix.SetValue(self.file.getBasenameWoExtension()) self.txtPath.SetValue(self.file.toOsSpecific()) self.txtPrefix.Enable(True) self.chkParentToNewNode.Enable(True) self.btnMerge.Enable(True) dlg.Destroy()
def onSaveAs(self, evt = None): dlg = wx.FileDialog(self, "Save file as", "", "", "Panda3D Binary Format (*.bam)|.[bB][aA][mM];*.bam", wx.SAVE | wx.FD_OVERWRITE_PROMPT) try: if dlg.ShowModal() == wx.ID_OK: self.onNew() self.filename = Filename.fromOsSpecific(dlg.GetPath()) self.SetTitle(self.filename.getBasename() + " - Panda Editor") self.modified = False self.editorInstance.saveEggModelsFile(self.filename.getFullpath()) finally: dlg.Destroy()
def onAddAnim(self, evt): fileType = "Egg files (*.egg;*.egg.pz)|*.egg;*.egg.pz" dlg = wx.FileDialog(self, "Select an Animation file", os.getcwd(), "", fileType, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: self.txtNewAnimLink.SetValue(dlg.GetPath()) self.txtAnimName.Enable(True) path = dlg.GetPath() fName = Filename.fromOsSpecific(path) self.txtAnimName.SetValue(fName.getBaseNameWoExtension())
def cogExists(filePrefix): searchPath = DSearchPath() if AppRunnerGlobal.appRunner: searchPath.appendDirectory(Filename.expandFrom('$TT_3_5_ROOT/phase_3.5')) else: basePath = os.path.expandvars('$TTMODELS') or './ttmodels' searchPath.appendDirectory(Filename.fromOsSpecific(basePath + '/built/phase_3.5')) filePrefix = filePrefix.strip('/') pfile = Filename(filePrefix) found = vfs.resolveFilename(pfile, searchPath) if not found: return False return True
def cogExists(filePrefix): searchPath = DSearchPath() if AppRunnerGlobal.appRunner: searchPath.appendDirectory(Filename.expandFrom('$TT_3_5_ROOT/phase_3.5')) else: basePath = os.path.expandvars('$TTMODELS') or './ttmodels' searchPath.appendDirectory(Filename.fromOsSpecific(basePath + '/built/phase_3.5')) filePrefix = filePrefix.strip('/') pfile = Filename(filePrefix) found = vfs.resolveFilename(pfile, searchPath) if not found: return False return True
def onAddAnim(self, evt): fileType = "Egg files (*.egg;*.egg.pz)|*.egg;*.egg.pz" dlg = wx.FileDialog(self, "Select an Animation file", os.getcwd(), "", fileType, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: self.txtNewAnimLink.SetValue(dlg.GetPath()) self.txtAnimName.Enable(True) path = dlg.GetPath() fName = Filename.fromOsSpecific(path) self.txtAnimName.SetValue(fName.getBaseNameWoExtension())
def newGame(self): ''' The select vehicle screen ''' base.enableParticles() self.countdown = COUNTDOWN_START # the countdown, when its over the game can be started self._notify.info("Initializing new game") # GlobPattern if we need a Panda Class self.vehicle_list = glob.glob("data/models/vehicles/*.egg") for index in range(len(self.vehicle_list)): self.vehicle_list[index] = Filename.fromOsSpecific( self.vehicle_list[index]).getFullpath() self._notify.debug("Vehicle list: %s" % (self.vehicle_list)) self.platform = loader.loadModel("data/models/platform.egg") # Loading-Text that gets displayed when loading a model text = TextNode("Loading") text.setFont(self.font) text.setText(_("Loading...")) text.setAlign(TextProperties.ACenter) self.loading = NodePath("LoadingNode") self.loading.attachNewNode(text) self.loading.setPos(0, 0, 2) # The countdown, its possible to start the game when its 0 text = TextNode("Countdown") text.setFont(self.font) text.setAlign(TextProperties.ACenter) text.setText(_(str(COUNTDOWN_START))) self.countdown_node = NodePath("Countdown") self.countdown_node.attachNewNode(text) self.countdown_node.setPos(0, 0, 4) # PreLoad the description that gets displayed when loading a model text = TextNode("name") text.setFont(self.font) text.setText(_("Loading...")) text.setAlign(TextProperties.ACenter) self.attributes = NodePath("AttributeNode") self.attributes.attachNewNode(text) self.unusedDevices = self._devices.devices[:] taskMgr.add(self.collectPlayer, "collectPlayer") # taskMgr.add(self.collectWii, "collectWii") self.screens = [] taskMgr.add(self.selectVehicle, "selectVehicle") self.color_red = Vec4(1, 0, 0, 0) self.color_green = Vec4(0, 1, 0, 0) self._notify.info("New game initialized")
def buildObject(self, model, scale, pos, hpr, has_lighting=True): """Builds a static object using the Panda3D loadModel function""" path = os.path.normpath("%s/%s" % (self.config_path, model)) if not os.path.exists(path): logging.error("The path '%s' does not exist" % path) sys.exit() path = Filename.fromOsSpecific(path) object = self.parent.loader.loadModel(path) object.setPos(*pos) object.setHpr(*hpr) object.setScale(scale) object.reparentTo(self.parent.render) static_object = PandaObject(object, has_lighting) return static_object
def __scanDirectoryRecursively(self, dirname): """ Generates a list of Filename objects: all of the files (not directories) within and below the indicated dirname. """ contents = [] for dirpath, dirnames, filenames in os.walk(dirname.toOsSpecific()): dirpath = Filename.fromOsSpecific(dirpath) if dirpath == dirname: dirpath = Filename('') else: dirpath.makeRelativeTo(dirname) for filename in filenames: contents.append(Filename(dirpath, filename)) return contents
def __scanDirectoryRecursively(self, dirname): """ Generates a list of Filename objects: all of the files (not directories) within and below the indicated dirname. """ contents = [] for dirpath, dirnames, filenames in os.walk(dirname.toOsSpecific()): dirpath = Filename.fromOsSpecific(dirpath) if dirpath == dirname: dirpath = Filename('') else: dirpath.makeRelativeTo(dirname) for filename in filenames: contents.append(Filename(dirpath, filename)) return contents
def buildObject(self, model, scale, pos, hpr, has_lighting=True): """Builds a static object using the Panda3D loadModel function""" path = os.path.normpath("%s/%s" % (self.config_path, model)) if not os.path.exists(path): logging.error("The path '%s' does not exist" % path) sys.exit() path = Filename.fromOsSpecific(path) object = self.parent.loader.loadModel(path) object.setPos(*pos) object.setHpr(*hpr) object.setScale(scale) object.reparentTo(self.parent.render) static_object = PandaObject(object, has_lighting) return static_object
def onSaveAs(self, evt=None): dlg = wx.FileDialog( self, "Save file as", "", "", "Panda3D Binary Format (*.bam)|.[bB][aA][mM];*.bam", wx.SAVE | wx.FD_OVERWRITE_PROMPT) try: if dlg.ShowModal() == wx.ID_OK: self.onNew() self.filename = Filename.fromOsSpecific(dlg.GetPath()) self.SetTitle(self.filename.getBasename() + " - Panda Editor") self.modified = False self.editorInstance.saveEggModelsFile( self.filename.getFullpath()) finally: dlg.Destroy()
def loadConversations(sceneFile, libraryFile): # Anton added 2/24 sceneFilename = Filename(sceneFile) libraryFilename = Filename.fromOsSpecific(os.getcwd()) + '/' + libraryFile lib = Library(Filename(libraryFilename.getDirname())) assetIndex = AssetIndex(lib) conversationAssets = assetIndex.conversations conversationObjects = {} for key, filename in conversationAssets.items(): xmlFilename = Filename(filename) doc = xml.dom.minidom.parse(xmlFilename.toOsSpecific()) Debug.debug(__name__,'loading '+str(xmlFilename.toOsSpecific())+'...') convo = Conversation.decode(doc) conversationObjects[key] = convo return conversationObjects
def makeBundle(startDir): fstartDir = Filename.fromOsSpecific(startDir) # Search for nppandad along $DYLD_LIBRARY_PATH. path = DSearchPath() if 'LD_LIBRARY_PATH' in os.environ: path.appendPath(os.environ['LD_LIBRARY_PATH']) if 'DYLD_LIBRARY_PATH' in os.environ: path.appendPath(os.environ['DYLD_LIBRARY_PATH']) nppanda3d = path.findFile('nppanda3d') if not nppanda3d: raise StandardError, "Couldn't find nppanda3d on path." # Generate the bundle directory structure rootFilename = Filename(fstartDir, 'bundle') if os.path.exists(rootFilename.toOsSpecific()): shutil.rmtree(rootFilename.toOsSpecific()) bundleFilename = Filename(rootFilename, 'nppanda3d.plugin') plistFilename = Filename(bundleFilename, 'Contents/Info.plist') plistFilename.makeDir() exeFilename = Filename(bundleFilename, 'Contents/MacOS/nppanda3d') exeFilename.makeDir() resourceFilename = Filename(bundleFilename, 'Contents/Resources/nppanda3d.rsrc') resourceFilename.makeDir() # Compile the .r file to an .rsrc file. os.system('/Developer/Tools/Rez -useDF -o %s %s' % (resourceFilename.toOsSpecific(), Filename(fstartDir, "nppanda3d.r").toOsSpecific())) if not resourceFilename.exists(): raise IOError, 'Unable to run Rez' # Copy in Info.plist and the compiled executable. shutil.copyfile( Filename(fstartDir, "nppanda3d.plist").toOsSpecific(), plistFilename.toOsSpecific()) shutil.copyfile(nppanda3d.toOsSpecific(), exeFilename.toOsSpecific()) # All done! bundleFilename.touch() print bundleFilename.toOsSpecific()
def loadConversations(sceneFile, libraryFile): # Anton added 2/24 sceneFilename = Filename(sceneFile) libraryFilename = Filename.fromOsSpecific(os.getcwd()) + '/' + libraryFile lib = Library(Filename(libraryFilename.getDirname())) assetIndex = AssetIndex(lib) conversationAssets = assetIndex.conversations conversationObjects = {} for key, filename in conversationAssets.items(): xmlFilename = Filename(filename) doc = xml.dom.minidom.parse(xmlFilename.toOsSpecific()) Debug.debug(__name__, 'loading ' + str(xmlFilename.toOsSpecific()) + '...') convo = Conversation.decode(doc) conversationObjects[key] = convo return conversationObjects
def _initFromFilename(self, filepath, filename): vfs = VirtualFileSystem.getGlobalPtr() filename = Filename(filename) searchPath = DSearchPath() #searchPath.appendDirectory(Filename('.')) #searchPath.appendDirectory(Filename('etc')) #searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('~'))) #searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('$HOME'))) searchPath.appendDirectory( Filename.fromOsSpecific(os.path.expandvars(filepath))) found = vfs.resolveFilename(filename, searchPath) if not found: raise IOError, "File not found!" str = vfs.readFile(filename, 1) self._initFromString(str)
def findNewsDir(self): if self.NewsOverHttp: return self.NewsStageDir searchPath = DSearchPath() if AppRunnerGlobal.appRunner: searchPath.appendDirectory(Filename.expandFrom('$TT_3_5_ROOT/phase_3.5/models/news')) else: basePath = os.path.expandvars('$TTMODELS') or './ttmodels' searchPath.appendDirectory(Filename.fromOsSpecific(basePath + '/built/' + self.NewsBaseDir)) searchPath.appendDirectory(Filename(self.NewsBaseDir)) pfile = Filename(self.NewsIndexFilename) found = vfs.resolveFilename(pfile, searchPath) if not found: self.notify.warning('findNewsDir - no path: %s' % self.NewsIndexFilename) self.setErrorMessage(TTLocalizer.NewsPageErrorDownloadingFile % self.NewsIndexFilename) return None self.notify.debug('found index file %s' % pfile) realDir = pfile.getDirname() return realDir
def findNewsDir(self): if self.NewsOverHttp: return self.NewsStageDir searchPath = DSearchPath() if AppRunnerGlobal.appRunner: searchPath.appendDirectory(Filename.expandFrom("$TT_3_5_ROOT/phase_3.5/models/news")) else: basePath = os.path.expandvars("$TTMODELS") or "./ttmodels" searchPath.appendDirectory(Filename.fromOsSpecific(basePath + "/built/" + self.NewsBaseDir)) searchPath.appendDirectory(Filename(self.NewsBaseDir)) pfile = Filename(self.NewsIndexFilename) found = vfs.resolveFilename(pfile, searchPath) if not found: self.notify.warning("findNewsDir - no path: %s" % self.NewsIndexFilename) self.setErrorMessage(TTLocalizer.NewsPageErrorDownloadingFile % self.NewsIndexFilename) return None self.notify.debug("found index file %s" % pfile) realDir = pfile.getDirname() return realDir
def __init__(self, sound=1, server='', galaxy='', empire='', password='', shipBattle=None, glow=1): self.shutdownFlag = Event() props = WindowProperties() props.setTitle('%s (Game = %s)' % (windowtitle, galaxy)) base.win.requestProperties(props) Application.__init__(self, server=server, galaxy=galaxy, empire=empire, password=password, shipBattle=shipBattle, glow=glow) self.pandapath = Filename.fromOsSpecific(self.path).getFullpath() self.imagePath = self.pandapath + '/images/' self.soundPath = self.pandapath + '/sounds/' self.modelPath = self.pandapath + '/models/' self.sound = sound self.finalcard = None self.glowCamera = None self.glowOn = True if glow: self.setupGlowFilter() self.gameLoopInterval = Func(self.gameLoop) self.gameLoopInterval.loop() self.createSounds() self.playMusic()
def makeBundle(startDir): fstartDir = Filename.fromOsSpecific(startDir) # Search for nppandad along $DYLD_LIBRARY_PATH. path = DSearchPath() if 'LD_LIBRARY_PATH' in os.environ: path.appendPath(os.environ['LD_LIBRARY_PATH']) if 'DYLD_LIBRARY_PATH' in os.environ: path.appendPath(os.environ['DYLD_LIBRARY_PATH']) nppanda3d = path.findFile('nppanda3d') if not nppanda3d: raise StandardError, "Couldn't find nppanda3d on path." # Generate the bundle directory structure rootFilename = Filename(fstartDir, 'bundle') if os.path.exists(rootFilename.toOsSpecific()): shutil.rmtree(rootFilename.toOsSpecific()) bundleFilename = Filename(rootFilename, 'nppanda3d.plugin') plistFilename = Filename(bundleFilename, 'Contents/Info.plist') plistFilename.makeDir() exeFilename = Filename(bundleFilename, 'Contents/MacOS/nppanda3d') exeFilename.makeDir() resourceFilename = Filename(bundleFilename, 'Contents/Resources/nppanda3d.rsrc') resourceFilename.makeDir() # Compile the .r file to an .rsrc file. os.system('/Developer/Tools/Rez -useDF -o %s %s' % ( resourceFilename.toOsSpecific(), Filename(fstartDir, "nppanda3d.r").toOsSpecific())) if not resourceFilename.exists(): raise IOError, 'Unable to run Rez' # Copy in Info.plist and the compiled executable. shutil.copyfile(Filename(fstartDir, "nppanda3d.plist").toOsSpecific(), plistFilename.toOsSpecific()) shutil.copyfile(nppanda3d.toOsSpecific(), exeFilename.toOsSpecific()) # All done! bundleFilename.touch() print bundleFilename.toOsSpecific()
def setP3DFilename(self, p3dFilename, tokens, argv, instanceId, interactiveConsole, p3dOffset=0): """ 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() 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(PandaModules, 'readXmlStream'): stream = mf.openReadSubfile(i) self.p3dInfo = PandaModules.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: initAppForGui() self.initPackedAppEnvironment() # Mount the Multifile under self.multifileRoot. vfs.mount(mf, self.multifileRoot, vfs.MFReadOnly) VFSImporter.reloadSharedPackages() self.loadMultifilePrcFiles(mf, self.multifileRoot) self.gotP3DFilename = True # Send this call to the main thread; don't call it directly. messenger.send('AppRunner_startIfReady', taskChain='default')
includeRequires = False try: opts, args = getopt.getopt(sys.argv[1:], "n:N:v:o:t:P:csl:L:a:A:e:i:h") except getopt.error, msg: usage(1, msg or "Invalid option") for opt, arg in opts: if opt == "-n": shortname = arg.strip() elif opt == "-N": fullname = arg.strip() elif opt == "-v": version = arg.strip() elif opt == "-o": outputDir = Filename.fromOsSpecific(arg) elif opt == "-t": token = arg.strip().split("=", 1) tokens[token[0]] = token[1] elif opt == "-P": platforms.append(arg) elif opt == "-c": currentPlatform = True elif opt == "-s": includeRequires = True elif opt == "-l": licensename = arg.strip() elif opt == "-L": licensefile = Filename.fromOsSpecific(arg) elif opt == "-a": authorid = arg.strip()
def setP3DFilename(self, p3dFilename, tokens, argv, instanceId, interactiveConsole, p3dOffset = 0): """ 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() 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(PandaModules, 'readXmlStream'): stream = mf.openReadSubfile(i) self.p3dInfo = PandaModules.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: initAppForGui() self.initPackedAppEnvironment() # Mount the Multifile under self.multifileRoot. vfs.mount(mf, self.multifileRoot, vfs.MFReadOnly) VFSImporter.reloadSharedPackages() self.loadMultifilePrcFiles(mf, self.multifileRoot) self.gotP3DFilename = True # Send this call to the main thread; don't call it directly. messenger.send('AppRunner_startIfReady', taskChain = 'default')
def exportGame(self, opts): file = opts['path'] #print file #print opts #print os.getcwd() templateFile = open('ExportGameTemplate.py') #print base.le.currentProj.dir #copy the LEGame Assets to the project folder dest = Filename(Filename.fromOsSpecific(file).getDirname()+'/LEGameAssets').toOsSpecific()#base.le.currentProj.dir.toOsSpecific() src = "./LEGameAssets"#Filename.fromOsSpecific(os.getcwd()).getFullpath()+'/LEGameAssets' scriptsFilename = self.exportScripts(file) #if os.path.exists(dest): # shutil.rmtree(dest) if not os.path.isdir(dest): #shutil.rmtree(dest) shutil.copytree(src,dest)# dst, symlinks, ignore)base.le.currentProj.dir#.toOsSpecific() dest = Filename(Filename.fromOsSpecific(file).getDirname()+'/particles').toOsSpecific() src = "./particles" if not os.path.isdir(dest): #shutil.rmtree(dest) shutil.copytree(src,dest) # shutil.copy("./ConversationLine.py",dest) # shutil.copy("./Conversation.py",dest) # shutil.copy("./ConversationMgr.py",dest) # shutil.copy("./ConversationMgrBase.py",dest) # shutil.copy("./ConversationUI.py",dest) # shutil.copy("./JournalUI.py",dest) # shutil.copy("./JournalMgr.py",dest) # shutil.copy("./JournalMgrBase.py",dest) # shutil.copy("./JournalEntry.py",dest) # shutil.copy("./GameplayUI.py",dest) # shutil.copy("./UIBase.py",dest) lines = templateFile.readlines() outputLines = [] if opts['loadScreen']: outputLines.append("from direct.gui.OnscreenImage import OnscreenImage\n") for line in lines: if line.startswith('SCENE_FILE'): outputLines.append(line.replace('None',\ "'" + self.editor.currentProj.getOpeningScene().getFullpath() + "'")) elif line.startswith('LIBRARY_INDEX'): outputLines.append(line.replace('None',\ "'lib.index'")) elif line.startswith('JOURNAL_FILE'): outputLines.append(line.replace('None',\ "'" + self.editor.currentProj.journalFilename.getFullpath() + "'")) elif line.startswith('INVENTORY_FILE'): outputLines.append(line.replace('None',\ "'" + self.editor.currentProj.inventoryMapFilename.getFullpath() + "'")) elif line.startswith('GAMEPLAY_FOLDER'): filename = Filename.fromOsSpecific("'" + os.getcwd()+ "'") outputLines.append(line.replace('None',\ filename.getFullpath())) elif line.startswith('SCRIPTS_FILE'): outputLines.append(line.replace('None',\ "'" + scriptsFilename.getBasename () + "'")) outputLines.append('\nfrom '+scriptsFilename.getBasenameWoExtension()+' import *\n') elif line.strip().startswith('ShowBase.__init__'): outputLines.append(line) if opts['loadScreen']: path = base.le.lib.textures[ opts['loadScreen'] ].filename.getFullpath() outputLines.append("\n self.loadScreen = OnscreenImage(image = '" + path + "')\n") outputLines.append(" self.loadScreen.reparentTo(render2d)\n") outputLines.append(" taskMgr.step()\n") outputLines.append(" taskMgr.step()\n") outputLines.append(" self.accept(\"enter\",self.destroyLoadScreen)") else: #TODO: Change this back later pass #outputLines.append("\n self.gameplayUI = GameplayUI(self)") elif line.strip().startswith('def loadScenes(self):'): outputLines.append(line) for s in self.editor.currentProj.scenes.keys(): outputLines.append("\n self.scenes['"+s+"'] = '"+\ self.editor.currentProj.scenes[s].getFullpath()+"'") outputLines.append("\n") else: outputLines.append(line) f = open(file, 'w') f.writelines(outputLines) f.close() batFile = os.path.join(os.path.dirname(file), 'runWorld.bat') f = open(batFile, 'w') f.write('python "' + os.path.basename(file) + '"') #f.write('\npause') f.close()
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().cStr() 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 loadShader(self, name): fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), name) fn = Filename.fromOsSpecific(fn) fn.makeTrueCase() return Shader.load(fn)
def onAddToLibrary(self, evt=None): libFile =(base.le.lib.projDir + '/lib.index').toOsSpecific() while True: #make sure that the library file is writable try: f = open(libFile, 'a') f.close() except IOError as e: dlg = wx.MessageDialog(self, "The library file '" + libFile + "' could not be written.\ Make sure that it is not marked read-only and click OK.", caption = "Permission Denied", style = wx.OK|wx.CANCEL|wx.ICON_ERROR) if dlg.ShowModal() == wx.ID_CANCEL: self.Close() return else: break if os.path.exists((Filename.fromOsSpecific(Util.getTempDir()) + '/removedAssets/').toOsSpecific()): shutil.rmtree((Filename.fromOsSpecific(Util.getTempDir()) + '/removedAssets').toOsSpecific()) self.removedAssets = [] page = self.notebook.GetPage(self.notebook.GetSelection()) if page == self.meshTab: item = self.listMeshes.GetFirstSelected() if item == -1: return name = self.listMeshes.GetItemText(item) mesh = self.lib.meshes[name] while True: try: base.le.lib.checkMesh(mesh) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() return elif result == SKIP: if e.oldAsset.__class__.__name__ == 'Mesh': self.restoreAssets() return mesh.textures.remove(e.newAsset) mesh.textures.append(e.oldAsset) except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() return elif result == SKIP: if e.asset.__class__.__name__ == 'Mesh': self.restoreAssets() return mesh.textures.remove(e.asset) f = Filename.fromOsSpecific(e.destPath) f.makeRelativeTo(base.le.lib.projDir) mesh.textures.append(base.le.lib.filenameIndex[f]) else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addMesh(mesh, True) if mesh.thumbnail: thumbnailPath = base.le.lib.projDir + '/Models/Thumbnails/' oldThumbnailPath = self.lib.projDir + mesh.thumbnail.getFullpath() copy_vfs(oldThumbnailPath.toOsSpecific(), thumbnailPath.toOsSpecific()) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.actorTab: item = self.listActors.GetFirstSelected() if item == -1: return name = self.listActors.GetItemText(item) actor = self.lib.actors[name] anims = copy(actor.anims.values()) for anim in anims: while True: try: base.le.lib.checkAnimation(anim) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() return elif result == SKIP: anims.remove(e.newAsset) anims.append(e.oldAsset) except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() return elif result == SKIP: self.anims.remove(e.asset) f = Filename.fromOsSpecific(e.destPath) f.makeRelativeTo(base.le.lib.projDir) self.anims.append(base.le.lib.filenameIndex[f]) else: break while True: try: base.le.lib.checkActor(actor) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() elif result == SKIP: if e.oldAsset.__class__.__name__ == 'Actor': self.restoreAssets() return actor.textures.remove(e.newAsset) actor.textures.append(e.oldAsset) except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() elif result == SKIP: if e.asset.__class__.__name__ == 'Actor': self.restoreAssets() return actor.textures.remove(e.asset) f = Filename.fromOsSpecific(e.destPath) f.makeRelativeTo(base.le.lib.projDir) actor.textures.append(base.le.lib.filenameIndex[f]) else: break while True: try: base.le.lib.checkActor(actor) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() self.Close() return elif result == SKIP: if e.oldAsset.__class__.__name__ == 'Actor': self.restoreAssets() return actor.textures.remove(e.newAsset) actor.textures.append(e.oldAsset) except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL: self.restoreAssets() return elif result == SKIP: if e.asset.__class__.__name__ == 'Actor': self.restoreAssets() return actor.textures.remove(e.asset) f = Filename.fromOsSpecific(e.destPath) f.makeRelativeTo(base.le.lib.projDir) actor.textures.append(base.le.lib.filenameIndex[f]) else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) for anim in anims: base.le.lib.addAnimation(anim) base.le.lib.addActor(actor, True) if actor.thumbnail: thumbnailPath = base.le.lib.projDir + '/Models/Thumbnails/' oldThumbnailPath = self.lib.projDir + actor.thumbnail.getFullpath() copy_vfs(oldThumbnailPath.toOsSpecific(), thumbnailPath.toOsSpecific()) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.textureTab: item = self.listTextures.GetFirstSelected() if item == -1: return name = self.listTextures.GetItemText(item) texture = self.lib.textures[name] while True: try: base.le.lib.checkTexture(texture) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addTexture(texture,True) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.animTab: item = self.listAnims.GetFirstSelected() if item == -1: return name = self.listAnims.GetItemText(item) anim = self.lib.animations[name] while True: try: base.le.lib.checkAnimation(anim) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addAnimation(anim) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.shaderTab: item = self.listShaders.GetFirstSelected() if item == -1: return name = self.listShaders.GetItemText(item) shader = self.lib.shaders[name] while True: try: base.le.lib.checkShader(shader) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addShader(shader, True) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.soundTab: item = self.listSounds.GetFirstSelected() if item == -1: return name = self.listSounds.GetItemText(item) sound = self.lib.sounds[name] while True: try: base.le.lib.checkSound(sound) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() self.Close() return except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() self.Close() return else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addSound(sound, True) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.terrainTab: item = self.listTerrains.GetFirstSelected() if item == -1: return name = self.listTerrains.GetItemText(item) terrain = self.lib.terrains[name] while True: try: base.le.lib.checkTerrain(terrain) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() self.Close() return except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() self.Close() return else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addTerrain(terrain, True) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.conversationTab: item = self.listConversations.GetFirstSelected() if item == -1: return name = self.listConversations.GetItemText(item) conversation = self.lib.conversations[name] while True: try: base.le.lib.checkConversation(conversation) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addConversation(conversation) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) elif page == self.scriptTab: item = self.listScripts.GetFirstSelected() if item == -1: return name = self.listScripts.GetItemText(item) script = self.lib.scripts[name] while True: try: base.le.lib.checkScript(script) except Library.DuplicateNameError as e: dialog = DuplicateNameDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return except Library.FileCollisionError as e: dialog = FileCollisionDialog(self, -1, e) result = dialog.ShowModal() dialog.Destroy() if result == CANCEL or result == SKIP: self.restoreAssets() return else: break base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) base.le.lib.addScript(script) base.le.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) if not base.le.saved: base.le.fNeedToSave = True base.le.ui.libraryUI.update() base.le.ui.storyObjUI.update()
def __init__(self, hostUrl, appRunner = None, hostDir = None, rootDir = None, asMirror = False, perPlatform = None): """ You must specify either an appRunner or a hostDir to the HostInfo constructor. If you pass asMirror = True, it means that this HostInfo object is to be used to populate a "mirror" folder, a duplicate (or subset) of the contents hosted by a server. This means when you use this HostInfo to download packages, it will only download the compressed archive file and leave it there. At the moment, mirror folders do not download old patch files from the server. If you pass perPlatform = True, then files are unpacked into a platform-specific directory, which is appropriate when you might be downloading multiple platforms. The default is perPlatform = False, which means all files are unpacked into the host directory directly, without an intervening platform-specific directory name. If asMirror is True, then the default is perPlatform = True. """ assert appRunner or rootDir or hostDir self.__setHostUrl(hostUrl) self.appRunner = appRunner self.rootDir = rootDir if rootDir is None and appRunner: self.rootDir = appRunner.rootDir if hostDir and not isinstance(hostDir, Filename): hostDir = Filename.fromOsSpecific(hostDir) self.hostDir = hostDir self.asMirror = asMirror self.perPlatform = perPlatform if perPlatform is None: self.perPlatform = asMirror # Initially false, this is set true when the contents file is # successfully read. self.hasContentsFile = False # This is the time value at which the current contents file is # no longer valid. self.contentsExpiration = 0 # Contains the md5 hash of the original contents.xml file. self.contentsSpec = FileSpec() # descriptiveName will be filled in later, when the # contents file is read. self.descriptiveName = None # A list of known mirrors for this host, all URL's guaranteed # to end with a slash. self.mirrors = [] # A map of keyword -> altHost URL's. An altHost is different # than a mirror; an altHost is an alternate URL to download a # different (e.g. testing) version of this host's contents. # It is rarely used. self.altHosts = {} # This is a dictionary of packages by (name, version). It # will be filled in when the contents file is read. self.packages = {} if self.appRunner and self.appRunner.verifyContents != self.appRunner.P3DVCForce: # Attempt to pre-read the existing contents.xml; maybe it # will be current enough for our purposes. self.readContentsFile()
from panda3d.core import ConfigVariableInt from panda3d.core import ConfigVariableDouble from panda3d.core import loadPrcFile from pandac.PandaModules import Filename import logging logging.basicConfig(level=logging.INFO, format='*(%(threadName)-10s) %(filename)s:%(lineno)-4d %(message)s',) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('debug messages working') logging.basicConfig(level=logging.ERROR, format='*(%(threadName)-10s) %(filename)s:%(lineno)-4d %(message)s',) loadPrcFile("config/config.prc") MYDIR = os.path.abspath(sys.path[0]) MYDIR = Filename.fromOsSpecific(MYDIR).getFullpath() logging.info(('running from:' + MYDIR)) if AppRunnerGlobal.appRunner is None: RUNTYPE = 'python' else: logging.info("dom" + str(AppRunnerGlobal.appRunner.dom)) if AppRunnerGlobal.appRunner.dom: RUNTYPE = 'website' else: RUNTYPE = 'local' def getConfigInt(name, default): output = ConfigVariableInt(name, default).getValue() if RUNTYPE != 'python': if AppRunnerGlobal.appRunner.getTokenInt(name):
def onDetails(self, evt, item): assetName = self.treeLibrary.GetItemText(item) parent = self.treeLibrary.GetItemParent(item) assetType = self.treeLibrary.GetItemText(parent) if assetType == "Meshes": asset = self.lib.meshes[assetName] elif assetType == "Textures": asset = self.lib.textures[assetName] elif assetType == "Actors": asset = self.lib.actors[assetName] elif assetType == "Animations": asset = self.lib.animations[assetName] elif assetType == "Shaders": asset = self.lib.shaders[assetName] elif assetType == "Sounds": asset = self.lib.sounds[assetName] elif assetType == "Terrains": asset = self.lib.terrains[assetName] dlg = EditAssetUI(self, asset) updateNeeded = False if dlg.ShowModal() == wx.ID_OK: newAssetName = Util.toAssetName(dlg.txtAssetName.GetValue()) if newAssetName != asset.name: try: if assetType == "Meshes": self.lib.renameMesh(asset.name, newAssetName) elif assetType == "Textures": self.lib.renameTexture(asset.name, newAssetName) elif assetType == "Actors": self.lib.renameActor(asset.name, newAssetName) elif assetType == "Animations": self.lib.renameAnimation(asset.name, newAssetName) elif assetType == "Shaders": self.lib.renameShader(asset.name, newAssetName) elif assetType == "Sounds": self.lib.renameSound(asset.name, newAssetName) elif assetType == "Terrains": self.lib.renameTerrain(asset.name, newAssetName) except LELibrary.DuplicateNameError: alert = wx.MessageDialog(self, "Name already in use. Aborting operation.",\ caption="Duplicate Name", style=wx.OK|wx.ICON_HAND) alert.ShowModal() return else: updateNeeded = True if dlg.txtNewFileLink.GetValue(): dest = Filename.fromOsSpecific(dlg.txtNewFileLink.GetValue()) dest.setDirname(asset.getFullFilename().getDirname()) if not os.path.exists(dest.toOsSpecific()): try: asset.relink(dlg.txtNewFileLink.GetValue()) updateNeeded = True except IOError as e: print e alert = wx.MessageDialog(self, "Could not copy file to '" + e.filename + "'. Permission denied.",\ caption="File Error", style=wx.OK|wx.ICON_HAND) alert.ShowModal() else: destFilename = Filename(dest) destFilename.makeRelativeTo(self.lib.projDir) if destFilename in self.lib.filenameIndex: if self.lib.filenameIndex[destFilename] != asset: alert = wx.MessageDialog(self, "Cannot overwrite other asset named '" + self.lib.filenameIndex[destFilename].name + "'.",\ caption = "Cannot overwrite file", style=wx.OK|wx.ICON_HAND) alert.ShowModal() return alert = wx.MessageDialog(self, "Overwrite file: " + dest.toOsSpecific() + " ?",\ caption="Overwrite File?", style=wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION) if alert.ShowModal() == wx.ID_YES: try: asset.relink(dlg.txtNewFileLink.GetValue()) updateNeeded = True except IOError as e: print e alert = wx.MessageDialog(self, "Could not copy file to '" + e.filename + "'. Permission denied.",\ caption="File Error", style=wx.OK|wx.ICON_HAND) alert.ShowModal() if assetType == "Actors": if dlg.txtNewAnimLink.GetValue(): try: # Create the animation asset newAnim = Library.Animation( dlg.txtAnimName.GetValue(), Filename.fromOsSpecific( dlg.txtNewAnimLink.GetValue())) self.editor.lib.addAnimation(newAnim) # Add the animation asset to the actor's animations list asset.anims[dlg.txtAnimName.GetValue()] = newAnim updateNeeded = True except IOError as e: print e alert = wx.MessageDialog(self, "Could not copy file to '" + e.filename + "'. Permission denied.",\ caption="File Error", style=wx.OK|wx.ICON_HAND) alert.ShowModal() if updateNeeded: if self.editor.saved: dlg = wx.MessageDialog(self, "This will save the project.", style=wx.OK) dlg.ShowModal() self.editor.save() self.editor.load(self.editor.currentProj.filename, resetViews=False, setSaved=False) self.update()
def loadShader(self, name): fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), name) fn = Filename.fromOsSpecific(fn) fn.makeTrueCase() return Shader.load(fn)
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().cStr() 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) # 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