def __init__(self, filepath=None, chunkClass=Chunk, readCallback=None, modname=None, startEmpty=False): try: project() except: return self.modname = modname if (filepath is None) and (not startEmpty): filepath = Path(os.path.join(str(project()), 'gameinfo.gi')) # look for a gameinfo.txt instead, pick a gameinfo.gi as default if it doesn't exist. if not filepath.exists: filepath = Path(os.path.join(str(project()), 'gameinfo.txt')) if not filepath.exists: filepath = Path(os.path.join(str(project()), 'gameinfo.gi')) if filepath: # Get filename and mod name from path self.filename = os.path.split(str(filepath))[1] if not self.modname: self.modname = os.path.split(os.path.dirname(str(filepath)))[1] else: self.filename = None KeyValueFile.__init__(self, filepath, parseLine, chunkClass, readCallback, True)
def textureAsContentTexture(texturePath): ''' returns a resolved content texture filepath for some sort of texture path. it looks for psd first, and then for tga. if neither are found None is returned ''' if not isinstance(texturePath, Path): texturePath = Path(texturePath) xtns = ['psd', 'tga'] if texturePath.isAbs(): if texturePath.isUnder(content()): relPath = texturePath - content() else: relPath = texturePath - game() relPath = relPath[2:] else: relPath = texturePath if relPath.startswith('materials') or relPath.startswith( 'materialsrc'): relPath = relPath[1:] contentPath = 'materialsrc' / relPath for xtn in xtns: tmp = contentPath.expandAsContent(gameInfo, xtn) if tmp is None: continue return tmp return None
def read(self, filepath=None): ''' reads the actual file, and passes the data read over to the parseLines method ''' if filepath == None: filepath = self.filepath else: filepath = Path(filepath) self.parseLines(filepath.read())
def write(self, filepath=None, doP4=True): ''' writes the instance back to disk - optionally to a different location from that which it was loaded. NOTE: deals with perforce should the file be managed by p4 ''' if filepath is None: filepath = self.filepath else: filepath = Path(filepath) filepath.write(str(self), doP4=doP4)
def lsGamePath(path, recursive=False): ''' lists all files under a given 'valve path' - ie a game or content relative path. this method needs to iterate over all known search mods as defined in a project's gameInfo script ''' path = Path(path) files = [] for modPath in [ Path(os.path.join(base, path.asNative())) for base in gameInfo.getSearchPaths() ]: files += list(modPath.files(recursive=recursive)) return files
def content(): ''' returns a Path instance representing the %VCONTENT% path - path construction this way is super easy: somePropPath = content() / 'ep3/models/characters/alyx/maya/alyx_model.ma' ''' global _CONTENT try: return Path(os.environ['VCONTENT']) except KeyError: try: _CONTENT = Path.Join(os.environ['VPROJECT'], '../../content') return _CONTENT except KeyError: KeyError('%VPROJECT% not defined')
def getAddonFromFullPath(sFullPath): ''' Returns the name of the addon determined by examining the specified path Returns None if the specified file is not under an addon for the current game()/content() tree, calls getModAndAddonTupleFromFullPath() and returns 2nd component ''' fullPath = Path(sFullPath) return fullPath.addonName
def makeSource1TexturePath(filepath): ''' returns the path as if it were a source1 texture/material path - ie the path is relative to the materials, or materialsrc directory. if the materials or materialsrc directory can't be found in the path, the original path is returned ''' if not isinstance(filepath, Path): filepath = Path(filepath) try: idx = filepath.index('materials') except ValueError: try: idx = filepath.index('materialsrc') except ValueError: return filepath return filepath[idx + 1:]
def mod(): ''' returns the mod name of the current project ''' global _MOD try: _MOD = Path(os.environ['VPROJECT']).name() return _MOD except KeyError: raise KeyError('%VPROJECT% not defined')
def project(): ''' returns a Path instance representing the %VPROJECT% path - path construction this way is super easy: somePropPath = project() / 'models/props/some_prop.mdl' ''' global _PROJECT try: _PROJECT = Path(os.environ['VPROJECT']) return _PROJECT except KeyError: raise KeyError('%VPROJECT% not defined')
def contentPath(modRelativeContentPath): '''allows you do specify a path using mod relative syntax instead of a fullpath example: assuming vproject is set to d:/main/game/tf_movies contentPath( 'models/player/soldier/parts/maya/soldier_reference.ma' ) returns: d:/main/content/tf/models/player/soldier/parts/maya/soldier_reference.ma NOTE: None is returned in the file can't be found in the mod hierarchy ''' return Path(modRelativeContentPath).expandAsContent(gameInfo)
def gamePath(modRelativeContentPath): '''allows you do specify a path using mod relative syntax instead of a fullpath example: assuming vproject is set to d:/main/game/tf gamePath( 'models/player/soldier.mdl' ) returns: d:/main/game/tf/models/player/soldier.mdl NOTE: None is returned in the file can't be found in the mod hierarchy ''' return Path(modRelativeContentPath).expandAsGame(gameInfo)
def lsContentPath(path, recursive=False): ''' similar to lsGamePath except that it lists files under the content tree, not the game tree ''' path = Path(path) c = content() files = [] for modPath in [c / mod / path for mod in gameInfo.getSearchMods()]: files += list(modPath.files(recursive=recursive)) return files
def find_module(self, fullname, path=None): lastName = fullname.rsplit('.', 1)[-1] scriptName = lastName + '.py' if path is None: path = [] # not sure if there is a better way of asking python where it would look for a script/module - but I think this encapsulates the logic... # at least under 2.6. I think > 3 works differently? for d in (path + sys.path): pyFilepath = Path(d) / scriptName pyModulePath = Path(d) / lastName / '__init__.py' if pyFilepath.exists or pyModulePath.exists: for validPath in validPaths: if pyFilepath.isUnder(validPath): return None print("### importing a script outside of game!", pyFilepath) return None return None
def game(): ''' returns a Path instance representing the %VGAME% path - path construction this way is super easy: somePropPath = game() / mod() / 'models/props/some_prop.dmx' ''' global _GAME try: _GAME = Path.Join(os.environ['VPROJECT'], '..') return _GAME except KeyError: raise KeyError('%VPROJECT% not defined.') except PathError: raise PathError('%VPROJECT% is defined with an invalid path.')
def resolveMaterialPath(materialPath): ''' returns a resolved material path given some sort of material path ''' if not isinstance(materialPath, Path): materialPath = Path(materialPath) if materialPath.isAbs(): if materialPath.isUnder(content()): relPath = materialPath - content() else: relPath = materialPath - game() relPath = relPath[2:] else: relPath = materialPath if relPath.startswith('materials') or relPath.startswith( 'materialsrc'): relPath = relPath[1:] relPath = ('materials' + relPath).setExtension('vmt') relPath = relPath.expandAsGame(gameInfo) return relPath
def __init__(self, filepath=None, lineParser=parseLine, chunkClass=Chunk, readCallback=None, supportsComments=True, initial_data=None, string_buffer=None): ''' lineParser needs to return key,value ''' self.filepath = Path(filepath) self.data = self.value = [] if initial_data is not None: self.data.append(initial_data) self.key = None self.parent = None self.lineParser = lineParser self.chunkClass = chunkClass self.callback = readCallback self.supportsComments = supportsComments def nullCallback(*args): pass self.nullCallback = nullCallback # if no callback is defined, create a dummy one if self.callback is None: self.callback = nullCallback # if no line parser was given, then use a default one if self.lineParser is None: def simpleLineParse(line): toks = line.split() if len(toks) == 1: return toks[0], [] else: return toks[0], toks[1] self.lineParser = simpleLineParse # if a filepath exists, then read it if (filepath) and (os.path.exists(filepath)): self.read() if string_buffer: self.parseLines(string_buffer)
def textureAsGameTexture(texturePath): ''' returns a resolved game texture filepath given some sort of texture path ''' if not isinstance(texturePath, Path): texturePath = Path(texturePath) if texturePath.isAbs(): if texturePath.isUnder(content()): relPath = texturePath - content() else: relPath = texturePath - game() relPath = relPath[2:] else: relPath = texturePath if relPath.startswith('materials') or relPath.startswith( 'materialsrc'): relPath = relPath[1:] relPath = Path(Path('materials') + relPath).setExtension('vtf') relPath = relPath.expandAsGame(gameInfo) return relPath
def tools(engine='Source 2'): ''' returns the location of our tools. ''' global _TOOLS if engine == 'Source': if _TOOLS is None: try: _TOOLS = Path(os.environ['VTOOLS']) except KeyError: try: _TOOLS = Path.Join(os.environ['VGAME'], '/../../tools') except KeyError: try: _TOOLS = Path.Join(os.environ['VPROJECT'], '/../../../tools') except KeyError: raise KeyError( '%VGAME% or %VPROJECT% not defined - cannot determine tools path' ) else: if _TOOLS is None: try: _TOOLS = Path(os.environ['VTOOLS']) except KeyError: try: _TOOLS = Path.Join(os.environ['VGAME'], '/sdktools') except KeyError: try: _TOOLS = Path.Join(os.environ['VPROJECT'], '../sdktools') except KeyError: raise KeyError( '%VGAME% or %VPROJECT% not defined - cannot determine tools path' ) return _TOOLS
def getSearchPaths(self): return [ str(Path.Join('%VPROJECT%/../', modEntry)) for modEntry in self.getSearchMods() ]
def setFilepath(self, newFilepath): ''' this wrapper is here so to ensure the _filepath attribute is a Path instance ''' self._filepath = Path(newFilepath)
def asRelative(filepath): ''' ''' return str(Path(filepath).asRelative())
def setAddonFromFullPath(sFullPath): ''' Sets the addon from the specified path ''' fullPath = Path(sFullPath) setAddon(fullPath.addonName)
import re import shlex ### Platform WIN_32_SUFFIX = 'win32' WIN_64_SUFFIX = 'win64' # The mail server used to send mail MAIL_SERVER = 'exchange' DEFAULT_AUTHOR = '*****@*****.**' # Make sure there is a HOME var... try: os.environ['HOME'] = os.environ['USERPROFILE'] except KeyError: os.environ['HOME'] = str(Path('%HOMEDRIVE%/%HOMEPATH%')) _MOD = None def mod(): ''' returns the mod name of the current project ''' global _MOD try: _MOD = Path(os.environ['VPROJECT']).name() return _MOD except KeyError: raise KeyError('%VPROJECT% not defined')