def getLoadedDirname(self, mod): """ Returns the directory name that the indicated conventionally-loaded module must have been loaded from. """ fullname = mod.__name__ dirname = Filename.fromOsSpecific(mod.__file__).getDirname() parentname = None basename = fullname if '.' in fullname: parentname, basename = fullname.rsplit('.', 1) path = None if parentname: parent = sys.modules[parentname] path = parent.__path__ if path is None: path = sys.path for dir in path: pdir = Filename.fromOsSpecific(dir).cStr() if pdir + '/' + basename == dirname: # We found it! return dir # Couldn't figure it out. return None
def __init__(self, species, gender, head, features, torso_size, legs_size, path=""): """ Args: species (str): "cat", "dog", "duck", "mouse", "pig", "rabbit", "bear", "horse" or "monkey". gender (str): "m" (male) or "f" (female). head (str): "n" (normal) or "l" (long). features (str): "n" (normal) or "l" (long). torso_size (str): "s" (small), "m" (medium) or "l" (long). legs_size (str): "s" (small), "m" (medium) or "l" (long). path (str, optional): The file path to the Toontown phase files. Defaults to Panda3D's search path. """ global MODEL_PATH if path: self.path = pfile.fromOsSpecific("%s/" % path).getFullpath() else: self.path = pfile.fromOsSpecific("%s/" % MODEL_PATH).getFullpath() self.species = species self.gender = gender self.dimensions = torso_size, legs_size self.__make_actor( species, gender, head, features, torso_size, legs_size ) Actor.__init__(self, self.parts, self.animation) self.__initialize_actor()
def setInstanceInfo(self, rootDir, logDirectory, superMirrorUrl, verifyContents, main, respectPerPlatform): """ 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 self.respectPerPlatform = respectPerPlatform #self.notify.info("respectPerPlatform = %s" % (self.respectPerPlatform)) # Now that we have rootDir, we can read the config file. self.readConfigXml()
def create_object(self): from panda3d.core import Filename, NodePath, BitMask32 from direct.actor.Actor import Actor from panda3d.bullet import BulletRigidBodyNode, BulletCapsuleShape from game_system.resources import ResourceManager f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["TestAI"]["lp_char_bs.egg"])) model = Actor(f) bullet_node = BulletRigidBodyNode("TestAIBulletNode") bullet_nodepath = NodePath(bullet_node) bullet_node.set_angular_factor((0, 0, 1)) shape = BulletCapsuleShape(0.3, 1.4, 2) bullet_node.addShape(shape) bullet_node.setMass(1.0) model.reparentTo(bullet_nodepath) model.set_hpr(180, 0, 0) model.set_pos(0, 0, -1) bullet_nodepath.set_collide_mask(BitMask32.bit(0)) bullet_nodepath.set_python_tag("actor", model) return bullet_nodepath
def WritePRCFile(self): page = None customConfigVariables = ["", "motd", "hostname", "tcp-port", "backlog", "udp-port", "isPersistent"] if os.path.exists(prcFile): # load the existing config file page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) else: # create a new config file cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Net Core Pandaconfig") # config declarations page.makeDeclaration("motd", str(self.MOTD)) page.makeDeclaration("hostname", str(self.HOSTNAME)) page.makeDeclaration("tcp-port", str(self.TCPPORT)) page.makeDeclaration("backlog", str(self.BACKLOG)) page.makeDeclaration("udp-port", str(self.UDPPORT)) page.makeDeclaration("isPersistent", str(self.ISPERSISTENT)) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def WritePRCFile(self): page = None customConfigVariables = ["", "tcp-port","udp-port", "server-port", "server-ip","timeout-in-ms"] if os.path.exists(prcFile): # load the existing config file page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) else: # create a new config file cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Grim Net Pandaconfig") # config declarations page.makeDeclaration("udp-port", str(self.UDPPORT)) page.makeDeclaration("tcp-port", str(self.TCPPORT)) page.makeDeclaration("server-port", str(self.UDPPORTSERVER)) page.makeDeclaration("server-ip", str(self.SERVERIP)) page.makeDeclaration("timeout-in-ms", str(self.TIMEOUT)) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
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 __writeConfig(self): """Save current config in the prc file or if no prc file exists create one. The prc file is set in the prcFile variable""" page = None # These TODO tags are as a reminder for to add any new config # variables that may occur in the future #TODO: get values of configurations here particles = "#f" if not base.particleMgrEnabled else "#t" volume = str(round(base.musicManager.getVolume(), 2)) mute = "#f" if base.AppHasAudioFocus else "#t" #TODO: add any configuration variable name that you have added customConfigVariables = [ "", "particles-enabled", "audio-mute", "audio-volume"] if os.path.exists(prcFile): # open the config file and change values according to current # application settings page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) # NOTE: particles-enabled and audio-mute are custom variables and # have to be loaded by hand at startup # Particles page.makeDeclaration("particles-enabled", particles) # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", mute) else: # Create a config file and set default values cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("{} Pandaconfig".format(appName)) # set OpenGL to be the default page.makeDeclaration("load-display", "pandagl") # get the displays width and height w = self.pipe.getDisplayWidth() h = self.pipe.getDisplayHeight() # set the window size in the config file page.makeDeclaration("win-size", "{} {}".format(w, h)) # set the default to fullscreen in the config file page.makeDeclaration("fullscreen", "1") # particles page.makeDeclaration("particles-enabled", "#t") # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", "#f") # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def make_skelecog(suit_style, suit_name, path=""): """Return a skelecog version of any traditional cog as an Actor. Args: suit_style (str): The letter representing the suit style ("A", "B" or "C"). suit_name (str): The name of the boss' suit. path (str, optional): The file path to the Toontown phase files. Defaults to Panda3D's search path. Examples: from toontown import make_skelecog skelecog = make_skelecog("A", "cash") skelecog.loop("neutral") Returns: An instance of Panda3D's Actor class. """ if path: path = pfile.fromOsSpecific("%s/" % path).getFullpath() icon_dict = { "sell": ("Sales", (0.843, 0.745, 0.745, 1.0)), "cash": ("Money", (0.749, 0.769, 0.749, 1.0)), "law": ("Legal", (0.749, 0.776, 0.824, 1.0)), "boss": ("Corp", (0.863, 0.776, 0.769, 1.0)) } animation_dict = cog_animation(suit_style, path) skelecog = Actor( "%sphase_5/models/char/cog%s_robot-zero.bam" % (path, suit_style), animation_dict ) if icon_dict[suit_name.lower()][0] == "Corp": tie = loader.loadTexture( "%sphase_5/maps/cog_robot_tie_boss.jpg" % path ) else: idict = icon_dict[suit_name][0].lower() tie = loader.loadTexture( "%sphase_5/maps/cog_robot_tie_%s.jpg" % (path, idict) ) skelecog.findAllMatches("**/tie").setTexture(tie, 1) icons = loader.loadModel("%sphase_3/models/gui/cog_icons.bam" % path) icon = icons.find( "**/%sIcon" % icon_dict[suit_name][0] ).copyTo(skelecog.find("**/joint_attachMeter")) icon.setPosHprScale(0.02, 0.05, 0.04, 180.0, 0.0, 0.0, 0.51, 0.51, 0.51) icon.setColor(icon_dict[suit_name.lower()][1]) icons.removeNode() skelecog.reparentTo(render) return skelecog
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 Exception("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 Exception("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('%s %s' % (panda3d_mac, exeFilename)) shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific()) os.chmod(exeFilename.toOsSpecific(), 0o755) # All done! bundleFilename.touch() print(bundleFilename.toOsSpecific())
def goBack(self): self.tempDir = str(Filename.fromOsSpecific(self.currentDir)) filepathlist = self.tempDir.split("/") del filepathlist[-1] self.tempStr = os.path.sep.join(filepathlist) print self.tempStr self.currentDir = self.tempStr self.openFolderDir(self.tempStr)
def setWritePath(self, pth): """ Set a writable directory for generated files. This can be a string path name or a multifile with openReadWrite(). If no pathname is set then the root directory is used. Applications are usually installed system wide and wont have write access to the basePath. It will be wise to at least use tempfile like tempfile.mkdtemp(prefix='Shader-tmp'), or an application directory in the user's home/app dir.""" self.writePath = Filename.fromOsSpecific(pth).getFullpath()
def setupScene(self, modelName, position=(0,0,0), orientation=(0,0,0), scale=(1,1,1)): base_path = os.path.dirname(__file__) model_path = os.path.join(base_path, 'models', modelName) model_path = Filename.fromOsSpecific(model_path) self.sceneNP = self.loader.loadModel(model_path) self.sceneNP.setPosHprScale(position, orientation, scale) self.sceneNP.reparentTo(self.render) base.setBackgroundColor((.1, .1, .1, 0))
def convert_mb_file(self, event): fileDlg = wx.FileDialog(self, "choose a mb File", self.dirname, "", "*.mb", wx.OPEN | wx.MULTIPLE) if fileDlg.ShowModal() == wx.ID_OK: #self.dirname = fileDlg.GetDirectory() paths = fileDlg.GetPaths() for path in paths: self.mbFile = path self.eggFile = self.mbFile[:(len(self.mbFile)-2)] + "egg" self.mbFile = os.path.join(self.dirname, self.mbFile) self.eggFile = os.path.join(self.dirname, self.eggFile) self.mbFile = Filename.fromOsSpecific(self.mbFile) self.eggFile = Filename.fromOsSpecific(self.eggFile) self.version = self.versionList.GetStringSelection() self.type = self.typeList.GetStringSelection() self.fill_cmd() self.control.AppendText("##############################\n") self.control.AppendText("Executing cmd : \n") self.control.AppendText(self.cmd + "\n") self.control.AppendText("########## Please Wait ##########\n") self.control.AppendText("If you can't find the egg file...check your file path and your maya version\n") self.control.AppendText("It's not available if the file path includes Chinese ( : 3 )\n") self.exec_cmd() self.control.AppendText("OK!! Convert Successfull ( ^ _ ^ )> ")
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 __init__(self): self.hasConfig = False # if exist load the config file if os.path.exists(prcFile): loadPrcFile(Filename.fromOsSpecific(prcFile)) self.hasConfig = True # set the variables using the config files content or set a default value self.UDPPORT = ConfigVariableInt('udp-port', '6002').getValue() self.TCPPORT = ConfigVariableInt('tcp-port', '6000').getValue() self.UDPPORTSERVER = ConfigVariableInt('udp-port-server', '6001').getValue() self.SERVERIP = ConfigVariableString('server-ip', '127.0.0.1').getValue() self.TIMEOUT = ConfigVariableInt('timeout-in-ms', '3000').getValue()
def selectSource(self): print "Select source!" self.btn_showResult.setEnabled(False) filename = QtGui.QFileDialog.getOpenFileName(self, 'Select source file ', 'convert/', "P3D Scene File (*.egg *.bam *.pz)") filename = str(filename) if len(filename) < 1: # nothing selected pass else: self.ipt_source.setText( Filename.fromOsSpecific(filename).getFullpath())
def openModelFile(self, filepath): # Add a if type check in here so that it checks # if file.egg ask to open # el if not .egg say its not right is other type # else if dir open that dir and display the files # use open for lvlml type files and normal egg files get imported modelDir = Filename.fromOsSpecific(filepath) self.model = self.base.loader.loadModel(modelDir) self.model.reparentTo(self.base.gizmo.rootNp)
def _handleIncludes(self, source): """ Internal (recursive) method to parse #include's """ with open(source, "r") as handle: content = handle.readlines() newContent = "" includeIdentifier = "#include " # Iterate through lines for line_idx, line in enumerate(content): lineStrip = line.strip() if lineStrip.startswith(includeIdentifier): includePart = lineStrip[len(includeIdentifier):].strip() # Filename is surrounded by braces # Todo: maybe also support ->'<- additionally to ->"<- if includePart.startswith('"') and includePart.endswith('"'): # Special case if includePart == '"%ShaderAutoConfig%"': properIncludePart = "PipelineTemp/ShaderAutoConfig.include" else: # Extract include part properIncludePart = Filename.fromOsSpecific(join( self._GlobalShaderPath, includePart[1:-1])).toOsGeneric() # And check if file exists if isfile(properIncludePart): # Check for recursive includes if properIncludePart in self._GlobalIncludeStack: # print "BetterShader: Ignoring recursive # include:",properIncludePart pass else: self._GlobalIncludeStack.append(properIncludePart) newContent += "\n// FILE: '" + \ str(properIncludePart) + "' \n" newContent += self._handleIncludes( properIncludePart).strip() + "\n" else: print "BetterShader: Failed to load '" + str(properIncludePart) + "'!" else: print "BetterShader: Invalid include:", includePart continue newContent += line.rstrip() + "\n" return newContent
def make_boss(head, torso, path=""): """Return any cog boss as an Actor. Args: head (str): The name of the boss' suit to be used for its head. torse (str): The name of the boss' suit to be used for its torso. path (str, optional): The file path to the Toontown phase files. Defaults to Panda3D's search path. Examples: from toontown import make_boss CFO = make_boss("cash", "cash") CFO.loop("Ff_neutral") Returns: An instance of Panda3D's Actor class. """ if path: path = pfile.fromOsSpecific("%s/" % path).getFullpath() boss_dict = { "sell": "phase_9/models/char/sellbotBoss", "cash": "phase_10/models/char/cashbotBoss", "law": "phase_11/models/char/lawbotBoss", "boss": "phase_12/models/char/bossbotBoss" } head_dict, torso_dict, legs_dict = cog_animation("Boss", path) animation = { "head": head_dict, "torso": torso_dict, "legs": legs_dict } parts = { "head": "%s%s-head-zero.bam" % (path, boss_dict[head]), "torso": "%s%s-torso-zero.bam" % (path, boss_dict[torso]), "legs": "%sphase_9/models/char/bossCog-legs-zero.bam" % path } boss = Actor(parts, animation) treads = loader.loadModel( "%sphase_9/models/char/bossCog-treads.bam" % path ) boss.attach("head", "torso", "joint34") boss.attach("torso", "legs", "joint_pelvis") treads.reparentTo(boss.find("**/joint_axle")) boss.reparentTo(render) return boss
def setBlurredHeightmap(self, hmap_path): assert(self._parent) self.blurred_heightmap_tex = TexturePool.loadTexture(Filename.fromOsSpecific(hmap_path)) self.blurred_heightmap_tex.setWrapU(SamplerState.WMClamp) self.blurred_heightmap_tex.setWrapV(SamplerState.WMClamp) self.blurred_heightmap_tex.setFormat(Texture.F_r16) self.blurred_heightmap_tex.setKeepRamImage(False) self.blurred_heightmap_tex.setMinfilter(SamplerState.FTLinearMipmapLinear) self.blurred_heightmap_tex.setMagfilter(SamplerState.FTLinear) self.blurred_heightmap_tex.setAnisotropicDegree(0) print "set blurred heightmap" self._element_node.setShaderInput("blurredHeightmap", self.blurred_heightmap_tex)
def __init__(self): self.hasConfig = False # if exist load the config file if os.path.exists(prcFile): self.hasConfig = True loadPrcFile(Filename.fromOsSpecific(prcFile)) # set the variables using the config files content or set a default value self.MOTD = ConfigVariableString('motd', 'Welcome to net_core!').getValue() self.HOSTNAME = ConfigVariableString('hostname', '127.0.0.1').getValue() self.TCPPORT = ConfigVariableInt('tcp-port', '6000').getValue() self.BACKLOG = ConfigVariableInt('backlog', '10').getValue() self.UDPPORT = ConfigVariableInt('udp-port', '6001').getValue() self.ISPERSISTENT = ConfigVariableInt('isPersistent', '0').getValue()
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 getModelPath(modelName): """ Return the Panda3D path for a model. """ # Instructions for loading models at: # https://www.panda3d.org/manual/index.php/Loading_Models repository = os.path.abspath(sys.path[0]) repository = Filename.fromOsSpecific(repository).getFullpath() if not repository.endswith('/'): repository += '/' modelsDir = repository + 'assets/models/' return modelsDir + modelName
def create_object(config_parser, entity): file_name = config_parser['model_name'] print("SPAWN", entity) if "bam" not in file_name: entity_data = ResourceManager[entity.__class__.type_name] model_path = path.join(entity_data.absolute_path, file_name) panda_filename = Filename.fromOsSpecific(model_path) obj = base.loader.loadModel(panda_filename) else: obj = entity.create_object() obj.reparentTo(base.render) return obj
def create_object(self): from panda3d.core import Filename, NodePath, BitMask32 from panda3d.bullet import BulletRigidBodyNode, BulletPlaneShape from game_system.resources import ResourceManager f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["Plane"]["Plane.egg"])) model = loader.loadModel(f) bullet_node = BulletRigidBodyNode("BulletPlane") bullet_nodepath = NodePath(bullet_node) shape = BulletPlaneShape((0, 0, 1), 0) bullet_node.addShape(shape) bullet_node.setMass(1.0) bullet_nodepath.set_collide_mask(BitMask32.bit(0)) model.reparentTo(bullet_nodepath) return bullet_nodepath
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 create_object(self): from panda3d.core import Filename, NodePath, BitMask32 from direct.actor.Actor import Actor from panda3d.bullet import BulletRigidBodyNode, BulletBoxShape from game_system.resources import ResourceManager f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["Zombie"]["Zombie.egg"])) model = Actor(f) bullet_node = BulletRigidBodyNode("BulletPlane") bullet_nodepath = NodePath(bullet_node) shape = BulletBoxShape((1, 1, 1)) bullet_node.addShape(shape) bullet_node.setMass(1.0) model.reparentTo(bullet_nodepath) bullet_nodepath.set_python_tag("actor", model) bullet_nodepath.set_collide_mask(BitMask32.bit(0)) return bullet_nodepath
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 Exception("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 create_object(self): from panda3d.core import Filename, NodePath, BitMask32 from panda3d.bullet import BulletRigidBodyNode, BulletTriangleMesh, BulletTriangleMeshShape from game_system.resources import ResourceManager f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["Map"]["map.egg"])) model = loader.loadModel(f) bullet_node = BulletRigidBodyNode("MapCollision") bullet_nodepath = NodePath(bullet_node) mesh = BulletTriangleMesh() for geomNP in model.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNode.getTransform() for geom in geomNode.getGeoms(): mesh.addGeom(geom, True, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) bullet_node.addShape(shape) bullet_nodepath.set_collide_mask(BitMask32.bit(0)) model.reparentTo(bullet_nodepath) return bullet_nodepath
def __writeConfig(self): """Save current config in the prc file or if no prc file exists create one. The prc file is set in the prcFile variable""" page = None particles = str(base.particleMgrEnabled) textSpeed = str(base.textWriteSpeed) volume = str(round(base.musicManager.getVolume(), 2)) mouseSens = str(base.mouseSensitivity) customConfigVariables = [ "", "particles-enabled", "text-write-speed", "audio-mute", "audio-volume", "control-type", "mouse-sensitivity"] if os.path.exists(prcFile): page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) # Particles particles = "#f" if not base.particleMgrEnabled else "#t" page.makeDeclaration("particles-enabled", particles) # speed of the textwriter page.makeDeclaration("text-write-speed", textSpeed) # audio page.makeDeclaration("audio-volume", volume) mute = "#f" if base.AppHasAudioFocus else "#t" page.makeDeclaration("audio-mute", mute) # controls page.makeDeclaration("control-type", base.controlType) page.makeDeclaration("mouse-sensitivity", mouseSens) else: cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("%s Pandaconfig"%appName) page.makeDeclaration("load-display", "pandagl") # get the displays width and height w = self.pipe.getDisplayWidth() h = self.pipe.getDisplayHeight() # set the window size in the config file page.makeDeclaration("win-size", "%d %d"%(w, h)) # set the default to fullscreen in the config file page.makeDeclaration("fullscreen", "1") # particles page.makeDeclaration("particles-enabled", "#t") # speed of the textwriter page.makeDeclaration("text-write-speed", textSpeed) # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", "#f") # player controls page.makeDeclaration("control-type", base.controlType) page.makeDeclaration("mouse-sensitivity", mouseSens) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
# # PATHS AND CONFIGS # # set the application Name __builtin__.appName = "Ajaw" __builtin__.versionstring = "15.07" # TODO: use vfs for particle texture (asset) path setup home = os.path.expanduser("~") __builtin__.basedir = os.path.join(home, __builtin__.appName) if not os.path.exists(__builtin__.basedir): os.makedirs(__builtin__.basedir) prcFile = os.path.join(__builtin__.basedir, "%s.prc"%__builtin__.appName) if os.path.exists(prcFile): loadPrcFile(Filename.fromOsSpecific(prcFile)) __builtin__.rootdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) vfs = VirtualFileSystem.getGlobalPtr() vfs.mount( Filename(os.path.join(__builtin__.rootdir,"assets")), ".", VirtualFileSystem.MFReadOnly ) gettext.bindtextdomain(__builtin__.appName, "localedir") gettext.textdomain(__builtin__.appName) __builtin__._ = gettext.lgettext windowicon = os.path.join(__builtin__.rootdir,"assets","Icon.png") loadPrcFileData("", """ window-title GrimFang OWP - Ajaw cursor-hidden 0
def usage(code, msg=''): sys.stderr.write(usageText % {'prog': os.path.split(sys.argv[0])[1]}) sys.stderr.write(msg + '\n') sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], 'i:h') except getopt.error as msg: usage(1, msg) installDir = None for opt, arg in opts: if opt == '-i': installDir = Filename.fromOsSpecific(arg) elif opt == '-h': usage(0) else: print('illegal option: ' + arg) sys.exit(1) packageNames = args if not installDir: installDir = Filename('install') if not packageNames: # "None" means all packages. packageNames = None
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
from path import path # this loads the configuration in Config.prc from panda3d.core import Filename, getModelPath, loadPrcFile config_pth = path("Config.prc") if config_pth.isfile(): cp = Filename.fromOsSpecific(config_pth) cp.makeTrueCase() print "Loading config '%s'" % cp loadPrcFile(cp) getModelPath().appendDirectory("models") getModelPath().appendDirectory("textures") import sys from direct.showbase.ShowBase import ShowBase from panda3d.bullet import BulletBoxShape, BulletRigidBodyNode, BulletWorld from panda3d.bullet import BulletDebugNode class BlockTutorial(ShowBase): def __init__(self): # Step 2: Set up graphics ShowBase.__init__(self) self.setup_camera() self.load_block_model() # Step 3: Set up physics self.create_physics() self.load_block_physics()
def panda_path(path): return str(Filename.fromOsSpecific(str(path)))
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. Note that perPlatform is also restricted by the individual package's specification. """ 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()
img.setAlpha(x, y, val) def getChannel(img, x, y, channel): if channel == CHANNEL_AO: return img.getRed(x, y) elif channel == CHANNEL_ROUGHNESS: return img.getGreen(x, y) elif channel == CHANNEL_METALLIC: return img.getBlue(x, y) elif channel == CHANNEL_EMISSIVE: return img.getAlpha(x, y) armeFile = raw_input("ARME file: ") armeFilename = Filename.fromOsSpecific(armeFile) img = PNMImage() img.read(armeFilename) for i in range(4): name = getChannelName(i).lower() print("Writing", name) chImg = PNMImage(img.getReadXSize(), img.getReadYSize()) chImg.setNumChannels(1) chImg.setColorType(PNMImageHeader.CTGrayscale) for x in range(img.getReadXSize()): for y in range(img.getReadYSize()): val = getChannel(img, x, y, i) chImg.setXel(x, y, val) chImg.write(
omitDefaultCheckboxes = False try: opts, args = getopt.getopt(sys.argv[1:], 'n:N:v:o:t:P:csOl: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 == '-O': omitDefaultCheckboxes = True elif opt == '-l': licensename = arg.strip() elif opt == '-L': licensefile = Filename.fromOsSpecific(arg)
from panda3d.core import Filename, PNMImage jpgFile = raw_input("JPEG file: ") aFile = raw_input("Alpha file: ") fn = Filename.fromOsSpecific(jpgFile) fnrgb = Filename.fromOsSpecific(aFile) fnout = Filename(fn.getFullpathWoExtension() + ".png") image = PNMImage(fn) imagergb = PNMImage(fnrgb) image.set_num_channels(4) for x in xrange(image.get_x_size()): for y in xrange(image.get_y_size()): image.set_channel(x, y, 3, imagergb.getChannel(x, y, 0)) image.write(fnout)
import numpy as np from models.world_setup import world_setup, quad_setup from computer_vision.cameras_setup import cameras from environment.position2 import quad_sim from computer_vision.quadrotor_cv import computer_vision import matplotlib.pyplot as plt from models.camera_control import camera_control import math from sklearn.metrics import mean_squared_error from mpl_toolkits import mplot3d mydir = os.path.abspath(sys.path[0]) mydir = Filename.fromOsSpecific(mydir).getFullpath() frame_interval = 4 cam_names = ('cam_1', 'cam_2') class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) render = self.render
def __writeConfig(self): """Save current config in the prc file or if no prc file exists create one. The prc file is set in the prcFile variable""" page = None # #TODO: add any configuration variable names that you have added # to the dictionaries in the next lines. Set the current # configurations value as value in this dictionary and it's # name as key. configVariables = { # set the window size in the config file "win-size": ConfigVariableString( "win-size", "{} {}".format(self.dispWidth, self.dispHeight)).getValue(), # set the default to fullscreen in the config file "fullscreen": "#t" if ConfigVariableBool("fullscreen", True).getValue() else "#f", # particles "particles-enabled": "#t" if self.particleMgrEnabled else "#f", # audio "audio-volume": str(round(self.musicManager.getVolume(), 2)), "audio-music-active": "#t" if ConfigVariableBool("audio-music-active").getValue() else "#f", "audio-sfx-active": "#t" if ConfigVariableBool("audio-sfx-active").getValue() else "#f", # logging "notify-output": os.path.join(basedir, "game.log"), # window "framebuffer-multisample": "#t" if ConfigVariableBool("framebuffer-multisample").getValue() else "#f", "multisamples": str(ConfigVariableInt("multisamples", 8).getValue()), "texture-anisotropic-degree": str(ConfigVariableInt("texture-anisotropic-degree").getValue()), "textures-auto-power-2": "#t" if ConfigVariableBool("textures-auto-power-2", True).getValue() else "#f", } page = None # Check if we have an existing configuration file if os.path.exists(prcFile): # open the config file and change values according to current # application settings page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in configVariables.keys(): removeDecls.append(page.modifyDeclaration(dec)) for dec in removeDecls: page.deleteDeclaration(dec) else: # Create a config file and set default values cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Application Config") # always write custom configurations for key, value in configVariables.items(): page.makeDeclaration(key, value) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def __init__(self): ShowBase.__init__(self) gltf.patch_loader(self.loader) properties = WindowProperties() properties.setSize(1000, 750) self.disableMouse() self.environment = loader.loadModel("environment/island.gltf") self.environment.reparentTo(render) self.environment.setPos(0,0,-3) self.environment.setHpr(0,-90,0) """ I put this becase I think there is a default light that I cant reach and manupulate. thets why I setLightsOff first. Otherwise Ican't create or cast shadows etc. """ self.environment.setLightOff() mats = self.environment .findAllMaterials() mats[0].clearBaseColor() mats[1].clearBaseColor() mats[0].setShininess(200) mats[1].setShininess(100) """ In this block I create a textureBuffer and create camera on that buffer that its display region is upper right corner of the window I use that region to create saveScreenShot xxxx or create a numpy array out of it (numpy_image_data) second try is to make a screenshot directly from the buffer which is not so important Both works though """ self.useTrackball() # ambientLight = AmbientLight("ambient light") # ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) # self.ambientLightNodePath = render.attachNewNode(ambientLight) # render.setLight(self.ambientLightNodePath) # In the body of your code mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) # Turn it around by 45 degrees, and tilt it down by 45 degrees mainLight.setShadowCaster(True,1000,1000) self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) """ I put it here again""" self.environment.setLight(self.mainLightNodePath) pointLight = PointLight("point light") pointLight.setShadowCaster(True,1000,1000) self.pointLightNodePath = render.attachNewNode(pointLight) self.pointLightNodePath.setPos(0,0,10) render.setLight(self.pointLightNodePath) """ and again """ self.environment.setLight(self.pointLightNodePath) render.setShaderAuto() self.tempActor2 = Actor("models/cube.bam") self.tempActor2.reparentTo(render) self.tempActor2.setPos(-2, 2, -1) self.tempActor2.setScale(.2) self.monkey = Actor("models/monkey") self.monkey.set_scale(.25) self.monkey.reparentTo(render) self.monkey.set_pos(-7,-7,2) self.monkey.lookAt(self.tempActor2) self.monkey2 = Actor("models/monkey") self.monkey2.set_scale(.25) self.monkey2.reparentTo(render) self.monkey2.set_pos(0,3,1) self.monkey2.lookAt(self.tempActor2) tex=Texture() self.mybuffer = self.win.makeTextureBuffer("My Buffer", 512, 512,tex,to_ram=True) self.mybuffer.setSort(-100) mycamera = self.makeCamera(self.mybuffer,displayRegion=(.5,1,.5,1)) mycamera.reparentTo(self.monkey) tex2=Texture() mybuffer2 = self.win.makeTextureBuffer("My Buffer2", 512, 512,tex,to_ram=True) mybuffer2.setSort(-500) mycamera2 = self.makeCamera(mybuffer2,displayRegion=(0,.5,0,.5)) mycamera2.reparentTo(self.monkey2) self.graphicsEngine.renderFrame() print(self.mybuffer.getActiveDisplayRegions()) """shadows for cameras missing here in screenshot""" save_it=self.mybuffer.getActiveDisplayRegion(0).saveScreenshotDefault('1111') my_output=self.mybuffer.getActiveDisplayRegion(0).getScreenshot() numpy_image_data=np.array(my_output.getRamImageAs("RGB"), np.float32) """shadows for cameras missing here in screenshot""" save_it2=mybuffer2.getActiveDisplayRegion(0).saveScreenshotDefault('2222') my_output2=mybuffer2.getActiveDisplayRegion(0).getScreenshot() numpy_image_data2=np.array(my_output2.getRamImageAs("RGB"), np.float32) print(numpy_image_data) file_name=Filename.fromOsSpecific("save_gameDat_001.png") self.mybuffer.saveScreenshot(file_name) print('Cameras') print(self.camList) print('Number Of Display Regions') print(self.win.getNumDisplayRegions()) print('Active Display Regions') print(self.win.getActiveDisplayRegions()) print(self.win.getDisplayRegions()) print('Number Of Display Regions') print(self.win.getNumDisplayRegions()) self.keyMap = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.updateTask = taskMgr.add(self.update, "update")
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
# # PATHS AND CONFIGS # # set the application Name __builtin__.companyName = "Grimfang Studios" __builtin__.appName = "Tatakai no ikimono" __builtin__.versionstring = "15.12" home = os.path.expanduser("~") __builtin__.basedir = os.path.join(home, __builtin__.companyName, __builtin__.appName) if not os.path.exists(__builtin__.basedir): os.makedirs(__builtin__.basedir) prcFile = os.path.join(__builtin__.basedir, "%s.prc" % __builtin__.appName) if os.path.exists(prcFile): mainConfig = loadPrcFile(Filename.fromOsSpecific(prcFile)) loadPrcFileData( "", """ window-title %s cursor-hidden 0 notify-timestamp 1 #show-frame-rate-meter 1 model-path $MAIN_DIR/assets/ framebuffer-multisample 1 multisamples 8 texture-anisotropic-degree 0 """ % __builtin__.appName) # # PATHS AND CONFIGS END #
def load(self, path): # vignette mask self.vignette_mask = None self.vignette_mask_small = None vfile = os.path.join(path, "vignette-mask.jpg") if os.path.exists(vfile): print("loading vignette correction mask:", vfile) self.vignette_mask = cv2.imread(vfile, flags=cv2.IMREAD_ANYCOLOR|cv2.IMREAD_ANYDEPTH|cv2.IMREAD_IGNORE_ORIENTATION) self.vignette_mask_small = cv2.resize(self.vignette_mask, (512, 512)) files = [] for file in sorted(os.listdir(path)): if fnmatch.fnmatch(file, '*.egg'): # print('load:', file) files.append(file) print('Loading models:') for file in tqdm(files, smoothing=0.05, ascii=(os.name=='nt')): # load and reparent each egg file pandafile = Filename.fromOsSpecific(os.path.join(path, file)) model = self.loader.loadModel(pandafile) # model.set_shader(self.shader) # print(file) # self.pretty_print(model, ' ') model.reparentTo(self.render) self.models.append(model) tex = model.findTexture('*') if tex != None: tex.setWrapU(Texture.WM_clamp) tex.setWrapV(Texture.WM_clamp) self.base_textures.append(tex) # The egg model lists "dummy.jpg" as the texture model which # doesn't exists. Here we load the actual textures and # possibly apply vignette correction and adaptive histogram # equalization. print('Loading base textures:') for i, model in enumerate(tqdm(self.models, smoothing=0.05, ascii=(os.name=='nt'))): base, ext = os.path.splitext(model.getName()) image_file = None dir = os.path.join(proj.analysis_dir, 'models') tmp1 = os.path.join(dir, base + '.JPG') tmp2 = os.path.join(dir, base + '.jpg') if os.path.isfile(tmp1): image_file = tmp1 elif os.path.isfile(tmp2): image_file = tmp2 #print("texture file:", image_file) if False: tex = self.loader.loadTexture(image_file) else: rgb = cv2.imread(image_file, flags=cv2.IMREAD_ANYCOLOR|cv2.IMREAD_ANYDEPTH|cv2.IMREAD_IGNORE_ORIENTATION) rgb = np.flipud(rgb) # histogram matching if do_histogram: rgb = histogram.match_neighbors(rgb, base) # vignette correction if not self.vignette_mask_small is None: rgb = rgb.astype('uint16') + self.vignette_mask_small rgb = np.clip(rgb, 0, 255).astype('uint8') # adaptive equalization hsv = cv2.cvtColor(rgb, cv2.COLOR_BGR2HSV) hue, sat, val = cv2.split(hsv) aeq = clahe.apply(val) # recombine hsv = cv2.merge((hue,sat,aeq)) # convert back to rgb rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) tex = Texture(base) tex.setCompression(Texture.CMOff) tex.setup2dTexture(512, 512, Texture.TUnsignedByte, Texture.FRgb) tex.setRamImage(rgb) tex.setWrapU(Texture.WM_clamp) tex.setWrapV(Texture.WM_clamp) model.setTexture(tex, 1) self.base_textures[i] = tex self.sortImages() self.annotations.rebuild(self.view_size)
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)
from direct.task.Task import Task from pandac.PandaModules import WindowProperties from panda3d.core import loadPrcFile, loadPrcFileData, Filename, DSearchPath, VBase4 # thread coordination import framework.tickmodule import threading # network support import Queue import SocketServer print "done." print "Applying the engine configuration file/settings..." # load the selected engine configuration (studypath takes precedence over the SNAP root path) config_searchpath = DSearchPath() config_searchpath.appendDirectory(Filename.fromOsSpecific(opts.studypath)) config_searchpath.appendDirectory(Filename.fromOsSpecific('.')) loadPrcFile( config_searchpath.findFile(Filename.fromOsSpecific(opts.engineconfig))) # add a few more media search paths (in particular, media can be in the media directory, or in the studypath) loadPrcFileData('', 'model-path ' + opts.studypath + '/media') loadPrcFileData('', 'model-path ' + opts.studypath) loadPrcFileData('', 'model-path media') # override engine settings according to the command line arguments, if specified if opts.fullscreen is not None: loadPrcFileData('', 'fullscreen ' + opts.fullscreen) if opts.windowsize is not None: loadPrcFileData('', 'win-size ' + opts.windowsize.replace('x', ' ')) if opts.windoworigin is not None:
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 Exception( "Impossible, interactive_console set without allow_python_dev." ) self.interactiveConsole = interactiveConsole if self.allowPythonDev: # Set the fps text to remind the user that # allow_python_dev is enabled. ConfigVariableString('frame-rate-meter-text-pattern').setValue( 'allow_python_dev %0.1f fps') if self.guiApp: init_app_for_gui() self.initPackedAppEnvironment() # Mount the Multifile under self.multifileRoot. vfs.mount(mf, self.multifileRoot, vfs.MFReadOnly) self.p3dMultifile = mf VFSImporter.reloadSharedPackages() self.loadMultifilePrcFiles(mf, self.multifileRoot) self.gotP3DFilename = True self.p3dFilename = fname if p3dUrl: # The url from which the p3d file was downloaded is # provided if available. It is only for documentation # purposes; the actual p3d file has already been # downloaded to p3dFilename. self.p3dUrl = core.URLSpec(p3dUrl) # Send this call to the main thread; don't call it directly. messenger.send('AppRunner_startIfReady', taskChain='default')
def makeICO(self, fn): """ Writes the images to a Windows ICO file. Returns True on success. """ if not isinstance(fn, Filename): fn = Filename.fromOsSpecific(fn) fn.setBinary() # ICO files only support resolutions up to 256x256. count = 0 for size in self.images.keys(): if size < 256: count += 1 if size <= 256: count += 1 dataoffs = 6 + count * 16 ico = open(fn, 'wb') ico.write(struct.pack('<HHH', 0, 1, count)) # Write 8-bpp image headers for sizes under 256x256. for size, image in self.images.items(): if size >= 256: continue ico.write(struct.pack('<BB', size, size)) # Calculate row sizes xorsize = size if xorsize % 4 != 0: xorsize += 4 - (xorsize % 4) andsize = (size + 7) >> 3 if andsize % 4 != 0: andsize += 4 - (andsize % 4) datasize = 40 + 256 * 4 + (xorsize + andsize) * size ico.write(struct.pack('<BBHHII', 0, 0, 1, 8, datasize, dataoffs)) dataoffs += datasize # Write 24/32-bpp image headers. for size, image in self.images.items(): if size > 256: continue elif size == 256: ico.write(b'\0\0') else: ico.write(struct.pack('<BB', size, size)) # Calculate the size so we can write the offset within the file. if image.hasAlpha(): bpp = 32 xorsize = size * 4 else: bpp = 24 xorsize = size * 3 + (-(size * 3) & 3) andsize = (size + 7) >> 3 if andsize % 4 != 0: andsize += 4 - (andsize % 4) datasize = 40 + (xorsize + andsize) * size ico.write(struct.pack('<BBHHII', 0, 0, 1, bpp, datasize, dataoffs)) dataoffs += datasize # Now write the actual icon bitmap data. for size, image in self.images.items(): if size < 256: self._write_bitmap(ico, image, size, 8) for size, image in self.images.items(): if size <= 256: bpp = 32 if image.hasAlpha() else 24 self._write_bitmap(ico, image, size, bpp) assert ico.tell() == dataoffs ico.close() return True
def get_model_path(self, name): winpath = os.path.join(self.base_path, name) return Filename.fromOsSpecific(winpath).getFullpath()
import direct.directbase.DirectStart from panda3d.core import Filename,Texture from panda3d.core import AmbientLight,DirectionalLight from panda3d.core import NodePath,TextNode from panda3d.core import Point3,Vec3,Vec4 from direct.task.Task import Task from direct.actor.Actor import Actor from direct.gui.OnscreenText import OnscreenText from direct.showbase.DirectObject import DirectObject import sys, os, random # Figure out what directory contains this program MYDIR=os.path.abspath(sys.path[0]) MYDIR=Filename.fromOsSpecific(MYDIR).getFullpath() # Function to put instructions on the screen. def addInstructions(pos, msg): return OnscreenText(text=msg, style=1, fg=(1,1,1,1), pos=(-1.3, pos), align=TextNode.ALeft, scale = .05) # Function to put title on the screen. def addTitle(text): return OnscreenText(text=text, style=1, fg=(1,1,1,1), pos=(1.3,-0.95), align=TextNode.ARight, scale = .07) random.seed() base.setBackgroundColor(Vec4(0.0,0.0,0.0,1.0)) class World(DirectObject): def __init__(self):
def load_dc(self): # Load and parse toon.dc and otp.dc... from panda3d.core import Filename for dc in self.DC_FILES: full_path = os.path.join(self.root, dc) self.dcf.read(Filename.fromOsSpecific(full_path))
from panda3d.core import PNMImage, Filename inputFile = raw_input("Input linear image: ") inputFilename = Filename.fromOsSpecific(inputFile) outputFile = raw_input("Output sRGB image: ") outputFilename = Filename.fromOsSpecific(outputFile) img = PNMImage() img.read(inputFilename) img.applyExponent(1.0 / 2.2) img.write(outputFilename) print("Done")
def SetValueFromEvent(self, evt): ctrl = evt.GetEventObject() val = ctrl.GetValue() self.SetValue(Filename.fromOsSpecific(val))
def __init__(self, path): self.dir_path = Filename.fromOsSpecific(path)
def getdata(self, path): path = Filename(self.dir_path, Filename.fromOsSpecific(path)) vfile = vfs.getFile(path) if not vfile: raise IOError("Could not find '%s'" % (path)) return vfile.readFile(True)
def __init__(self, rendering: bool): """ Constructor :param rendering: boolean indicating whether to use RenderPipeline or default Panda3d as visualization-module. """ super().__init__(self) self.dir = Filename.fromOsSpecific( pyrado.PANDA_ASSETS_DIR).getFullpath() # Initialize RenderPipeline if rendering: sys.path.insert(0, pyrado.RENDER_PIPELINE_DIR) from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.render_pipeline.pre_showbase_init() self.render_pipeline.set_loading_screen_image( osp.join(self.dir, "logo.png")) self.render_pipeline.settings["pipeline.display_debugger"] = False self.render_pipeline.create(self) self.render_pipeline.daytime_mgr.time = "17:00" else: self.render_pipeline = None # Activate antialiasing self.render.setAntialias(AntialiasAttrib.MAuto) # Set window properties self.windowProperties = WindowProperties() self.windowProperties.setForeground(True) self.windowProperties.setTitle("Experiment") # Set background color self.setBackgroundColor(1, 1, 1) # Configuration of the lighting self.directionalLight1 = DirectionalLight("directionalLight") self.directionalLightNP1 = self.render.attachNewNode( self.directionalLight1) self.directionalLightNP1.setHpr(0, -8, 0) self.render.setLight(self.directionalLightNP1) self.directionalLight2 = DirectionalLight("directionalLight") self.directionalLightNP2 = self.render.attachNewNode( self.directionalLight2) self.directionalLightNP2.setHpr(180, -20, 0) self.render.setLight(self.directionalLightNP2) self.ambientLight = AmbientLight("ambientLight") self.ambientLightNP = self.render.attachNewNode(self.ambientLight) self.ambientLight.setColor((0.1, 0.1, 0.1, 1)) self.render.setLight(self.ambientLightNP) # Create a text node displaying the physic parameters on the top left of the screen self.text = TextNode("parameters") self.textNodePath = aspect2d.attachNewNode(self.text) self.text.setTextColor(0, 0, 0, 1) # black self.textNodePath.setScale(0.07) self.textNodePath.setPos(-1.9, 0, 0.9) # Configure trace self.trace = LineSegs() self.trace.setThickness(3) self.trace.setColor(0.8, 0.8, 0.8) # light grey self.lines = self.render.attachNewNode("Lines") self.last_pos = None # Adds one instance of the update function to the task-manager, thus initializes the animation self.taskMgr.add(self.update, "update")
def __init__(self, path): if isinstance(path, Filename): self.dir_path = Filename(path) else: self.dir_path = Filename.fromOsSpecific(path)
def usage(code, msg=''): sys.stderr.write(usageText % {'prog': os.path.split(sys.argv[0])[1]}) sys.stderr.write(msg + '\n') sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], 'i:p:h') except getopt.error as msg: usage(1, msg) installDir = None packageNames = [] for opt, arg in opts: if opt == '-i': installDir = Filename.fromOsSpecific(arg) elif opt == '-p': packageNames += arg.split(',') elif opt == '-h': usage(0) else: print('illegal option: ' + arg) sys.exit(1) if not packageNames: # No package names means allow all packages. packageNames = None inputDirs = [] for arg in args: