Logo   Home Table of Contents    News  Dev Blogs  Gallery  Timeline  Legend  Tags  Sponsors 
Join us on... 
Banner

Current: Month Day, Year

9.1.1 Code of core/globenv.py

core/globenv provides all common global elements and functions. These can be used everwhere in the program. The file contains 3 classes:

Class globalObjects

It is the main class to contain "real globals", so variables which might be referenced everywhere.

If we need further, they will be defined here. To be sure they exist, the value will either be None, a certain number, an empty string or an empty dictionary or list. Variables must be mentioned here and should never be injected to avoid clashes. It is also easier to understand code. The elements are either added in __init__ or in reset(), the function called by init and which can be called, when system e.g. loads different mesh.

Classical this class is referenced with the parameter glob. It is mostly a parameter of all modules to make it accessible.

A hasattr is not needed for all mentioned elements.

Variables

namedescription
env a reference to environment, allows e.g. to access glob.env.logLine or access of all environment paramters and functions. env.last_error was the error of last load function etc.
app reference to QApplication
shaderInit a dictionary containing all shader pre-definitons filled from a shader file data/shaders/shader.json
subwindows a dictionary of opened subwindows
MainWindow reference to mainwindow (which is the global window with the 3 columns)
openGLWindow reference to QOpenGLWidget defined in opengl/main.py, our "canvas". Here you will find all graphical objects.
  • camera
  • light
  • objects
  • scene
  • shaders
  • and a function to redraw all buffers is done with Tweak()
openGLBlock global bool to avoid openGL output e.g. when texture is deleted etc. It is blocked while loading etc.
openGLWinUpdate global bool to allow only openGL update, should avoid double updates
midColumn reference to mid column mostly used for some changes like poseView(bool)
centralWidget is the whole widget used for e.g. Warnings and Errorboxes, a pyside6 problem, that these boxes cannot be connected to subwindows.
baseClass the current baseclass
closing bool value, application is closing (exit yes/no) needs that not to stay in infinite loop
openGLPreDraw Array of functions to be called before drawing main character.
openGLPostDraw Array of functions to be called after drawing main character.
drawFunction Dictionary of named draw functions.
pluginRepo Dictionary of attached plugins. Key is usually the absolute path, value can be anything, but normally the pointer to the plugin.
textureRepo the repository of the loaded textures
apiSocket contains the connected socket or is none
wireframemode contains the mode the wireframe is painted
project_changed is true when sth. has changed
cachedInfo the complete current cache
Targets reference to all targets
targetCategories contains the category object
targetMacros contains macrodefinitions (JSON structure, if available)
targetRepo contains a dictionary of available targets
macroRepo contains a dictionary of available macros
missingTargets contains a list of missing targets after load
parallel for parallel processing. Should avoid more than one process at the time is running in parallel
lastdownload will contain the filename of last downloaded file
textSlot array of text slots for graphical window, like size age etc.
custom_props_list extension for "studio" assets

Methods:

nameparametersreturnsdescription
reset NoneNone Reset all global parameters, used for start and when mesh is changed.
showSubwindow name: unique name
parent: parent window
mclass: own class
*params: params needed for class
reference to window Show a subwindow, if it is already there it is raised only.

glob.showSubwindow("materialedit", self.parent, MHMaterialEditor, obj)

getSubwindow name: unique name reference to window get reference to a named subwindow. None if not available.

mw = glob.getSubwindow("material")

closeSubwindow name: unique name
destroy: bool
None close a named subwindow. Destroy window if needed otherwise it can be re-used.

glob.closeSubwindow("measure", True)

getCacheData NoneNone gets data from cache, user-settings will overwrite standard tags. The internal info is resetted and the list of cache entries is read. Entries are appended to self.cachedInfo. In case of double entries the first one is taken. Since the user folders are read first, an entry in system folder will not be added if already there.
noAssetsUsed NoneNone Sets elem.used in cache repo to False for all possible assets. This is called while loading a character.
getAssetByFilename path: absolute path of assetreference to elem returns a elem matched by a pathname. None if not available
hasAssetFolder folder: name of the folderboolean returns if an asset folder is in cache. function is not used atm.
rescanAssets asset_type: type of asset
force: boolean
reference to cached info rescan all assets to create a new cache. The image-selector usually only rescan their own assets. After download syncRepositories in mainwindow is called and all assets are rescanned with force option. When basemesh is changed, there is also a rescan. Without type parameter all assets are rescanned.

cache = glob.rescanAssets(force=True)

markAssetByFileName path: absolute path of assetNone searches for asset name in repo and set it to "used".
unmarkAssetByFileName path: absolute path of assetNone searches for asset name in repo and set it to "not used".
gen_uuid Noneuuid Simply generates a UUID4 and returns it as a string.
readShaderInitJSON NoneshaderInit dictionary reads JSON file <system>/data/shaders/shader.json and returns dictionary.
setApplication appNone setter for self.app
setMainWindow windowNone setter for self.MainWindow
setTextSlot num: number of line
target: text
None sets one of the 5 textslots for e.g. age or gender.
generateBaseSubDirs basename: name of the baseokay: boolean generates all folders in user-data for a certain base. These are the base folders mentioned in the environment and "exports", "skins", "models", "target", "contarget", "dbcache", "downloads". If mkdir fails False is returned.
_insertInDrawFunction draw array
listelem
None Method inserts or appends a drawfunction (listelem) into draw_array. It considers second value of listelem as a priority. This is a helper method.
_createDrawFunctionIndex NoneNone Method to create a dictionary of drawfunctions This is a helper method.
registerDrawFunction toolname
drawfunćtion
priority
None Method insert drawfunction into an array, registered by "toolname". If priority is equal or greater than zero it is post-Draw function. Otherwise it is drawn before scene. While inserting, openGL is blocked.
unregisterDrawFunction toolnameNone Unregister the drawfunction named tool name. While deleting, openGL is blocked.

Class cacheRepoEntry

This class is used to create cacheRepo entries. It is just a constructor to have variables in form of attributes.

Variables

These variables are all preset by __init__ unless mentioned.
namedescription
name Asset name.
uuid uuid generated for this asset (can also be pathname)
folder Name of the folder (clothes, skins etc.)
path Absolute path of the asset
thumbfile Pathname of the thumb-file
author Name of the author
tag list of tags connected
used boolean value if asset is used, preset to false
obj_file Path of .obj wavefront file, create from dirname of path if obj_file is not none
mhbin_file in case path ends with .mhclo, it is the alternative pathname with mhbin

Class programInfo

This class should contain 'global environment parameters', usually referenced as self.env. Especially all pathnames and os-specific information. All parameters are assigned after start. No hasattr() needed. Methods are converter functions, JSON reader/writer and integrity test.

Variables

namedescription
mhclofolders list of all foldernames with mhclo like content, like "clothes", "eyebrows.
basefolders list of all foldernames for a base, like "clothes", "poses".
basename Name of the current base, like "hm08".
fileCache Reference to fileCache.
last_error Last error, can be used for all purposes, e.g while reading json.
verbose from args.verbose level of debugging
admin from args.admin, admin mode allows to also write system files.
noalphacover from args.nomultisampling, usage of alpha to coverage
noskybox from args.noskybox, usage of the skybox
recreate_repo from args.repository, forced recreate the repo on startup
uselog from args.l, force to write to logfile. If frozen, the uselog is set.
frozen set by pyInstaller etc. Frozen mode does not allow all features.
oldsysstdout to keep the old stdout channel, used when for pyInstaller.
oldsysstderr to keep the old stderr channel, used when for pyInstaller.
path_sys directory name of application (makehuman.py or .exe).
uenv reference to user-environment module.
sys_platform value of sys.platform
osindex 0: windows, 1: linux, 2: MacOS
ostype named platform, so "Windows", "Linux" or "MacOS"
platform_version value of platform.win32_ver, platform.mac_ver or linux distribution
platform_machine value of platform.machine()
platform_processor value of platform.processor()
platform_release value of platform.uname()[2]
config dictionary representation of the configuration.
path_userconf absolute pathname of user configuration file
path_usersession absolute pathname of user session file (to keep last session)
path_sysdata absolute pathname of system data folder.
path_userdata absolute pathname of user data folder.
path_version absolute pathname of makehuman2_version.json file containing all common parameters.
path_sysconf absolute pathname of makehuman2_default.conf containing presets when no configuration file is there.
path_sysicon absolute pathname of system icons.
path_home Home path of the user.
encodings array of locale.getpreferredencoding(), sys.getdefaultencoding(), sys.getfilesystemencoding()
sys_path value of sys.path
bin_path value of environment variable PATH
sys_executable value of sys.executable
sys_version value of sys.version (no linefeeds)
numpy_version current numpy version
QT_Info value of PySide6/QT
GL_Info value of openGL version
fhelp reference to FileHelper (own class to read different filetypes)

Methods:

nameparametersreturnsdescription
setVerboseBit bit: bit-numberNone set self.verbose to specific bit, in case of 0 all bits are set.
resetVerboseBit bit: bit-numberNone reset self.verbose to specific bit, in case of 0 all bits are reset.
helpVerbose Noneverbosedefinition return an array of tuple of bit number and text for each verbose option
showVersion NoneNone Output of option -V
formatPath pathpath formats path to unicode and replaces all backslashes.

matpath = env.formatPath(self.skinMaterialName)

fullPath pathpath Converts path including environment and all converted to a standard format (no backslashes).
normalizeName pathpath change a name to lower case, only allow a-z 0-9 - + _ =, it is used to create filenames compatible for Windows and Linux.

name = "{}_{:03d}".format(env.normalizeName(raw_name), material_cnt)

developmentPyCacheCleanup Nonepurged_paths

errors

deletes pyCaches, will change recreate caches on next start, return list of deleted paths and errors, if any.
mkdir foldersuccess (boolean) safe creation of a directory. possible errors are in last_error, returns boolean value for success. Accepts existent folder and also creates a special message when new folder is an existent file.

if env.mkdir(folder) is False:
   MessageBox(env.last_error)

copyfile source
dest
success (boolean) safe copy of a file, possible errors are in last_error, returns boolean value for success.
readJSON pathjson_object read a json file, possible errors are in last_error. In case of error, output is None.

if env.readJSON(path) is None:
   MessageBox(env.last_error)

writeJSON path

json_object

success (boolean) write a json file, possible errors are in last_error. Returns boolean value for success.
environment Nonesuccess (boolean) read the environment (conf-files) using the DOCUMENTS folder or home folder according to registry (Windows) or XDG-file (Linux). Returns True (all okay) or False (system cannot start)
generateFolders Nonesuccess (boolean) Create folders user folders and subfolder inside user folder (also openGL shader folders), returns false if problem, write results to logfile, in case of error set last_error.
initFileCache NoneNone Initializes file cache (database dbcache/repository.db in user folder)
reDirect log: forced by option -lNone Redirects standard error and standard output and keeps old values in oldsysstdout and oldsysstderr.
stdSysPath asset category
asset filename
path Returns absolut path of an asset and category with the help of the basename in system folder. If filename is not given, the asset folder is returned. If category is not given, path_sysdata is returned. Without basename, the returned result is None.

path = env.stdSysPath(type, "selection_filter.json")

stdUserPath asset category
asset filename
path Returns absolut path of an asset and category with the help of the basename in user folder. If filename is not given, the asset folder is returned. If category is not given, path_userdata is returned. Without basename, the returned result is None
stdLogo Nonepath Returns the path to the system icon
isSourceFileNewer destination
source
isnewer (bool) Function used to test if compilation is needed. If destination is not available, True is returned. In case of a non-existing source file, false is returned. Otherwise the modification dates of souce and destination are compared, and True is returnen, when source file is newer.
getFileList dirname
pattern
list of strings Returns a list of files with a certain pattern
getDataFileList extension
*subdirs
filebase (dictionary) Searches in system and user path for certain files with an extension, then creates an dictionary using the filename as key and the path as value.

floorlist = env.getDataFileList("png", "shaders", "floor")

getDataDirList search
*subdirs
filebase (dictionary) Searches in system and user path for certain files, then creates an dictionary using the filename as key and the path as value. Also scan directories in the folder.

skyboxlist = env.getDataDirList(None, "shaders", "skybox")

getParentDirName nameparent directory return parent directory name. Also replaces backslash. Returns empty string when less than 3 components.
existDataFile namesabsolute pathname Joins names to a path and checks in user and system folder if file exists. If that is the case, the absolute filename is returned. User folder is checked first. None is returned in case it is not found and last_error contains the name of the missing file.

pose_skelpath = env.existDataFile("rigs", env.basename, skelname)

existFileInBaseFolder base
subfolder
objpath
filename
absolute pathname The typical asset check. Calculate parent directory name from objpath as parentobj and checks if file is found in (subfolder, base, parentobj, filename) with existDataFile. If that yields None, check for "/" in filename and without first layer again using (subfolder, base, filename). This is the typical asset check.
existDataDir namesabsolute pathname Joins names to a path and checks in user and system folder if directory exists. If that is the case, the absolute directory name is returned. User folder is checked first. None is returned in case it is not found and last_error contains the name of the missing directory.

shaderpath = env.existDataDir("shaders", "skybox", skyboxname)

getDataDirs nameslist of directories Joins names to a path and checks in user and system folder if directory exists. All matching absolute paths will be returned.
latestDate old latest timestamp
filename
new latest timestamp Tests filename and if newer, latest is changed to modification time.
testFilesWithBinExtension files
current folder
category
ascext
binext
latest
filenames
latest Checks in current folder if a file with binary-extension exists. Then the ascii alternative is tested. If the ascii file is available and newer it will be appended to filenames, otherwise the binary file is appended. ASCII files without a binary files will be also appended to filenames. The latest date will be changed, when newer and is returned
testFilesWithExtension files
current folder
category
extension
latest
filenames
latest Checks in current folder if a file has a certain extension. In that case it will be appended to filenames. The latest date will be changed, when newer and is returned
getFilesFromAssetFolders ascext
subdir
binext
latest
filenames
Check either all asset folders or a specific one, when subdir is not None. Collects all files with the ASCII extension ascext using name and date. All folders for objects are allowed to have one subfolder. If a binary extension is allowed, check is done with testFilesWithBinExtension, otherwise with testFilesWithExtension. The complete list and the latest date is returned.
fileScanFolders subdirNone Function to scan all folers for assets and put assets into fileCache. If subdir is given only a certain folder is scanned. In case of a lastest date newer than date of the repository, the repository itself is recreated. For this the fhelp functions are used.
getCacheData NoneNone Gets data from database repository, user-settings, if available will overwrite standard tags.
getAvailableBases Nonelist of base names Returns a list of bases, base.obj or base.mhbin will be accepted.

baselist = env.getAvailableBases()

relMatFileName path
itype
path Create a relativ pathname from material. It is URI based and used in mhm file. According to itype it works different. 'base' of 'proxy' will yield in a material for 'skins', a common path materials is allowed as well.

asset.materialsource = env.relMatFileName(matelem.filename, obj.type)

manualScanFolder type
suffix
cache_ref
tags
None A file-list scanner for folders, will be used for props to create cache entries. Atm. only user folder is accepted.
dictFillGaps standard
testdict
changed (bool) Recursively add elements from standard if dictionaries have missing data. Allows additional lines for configuration files in future editions without need to re-enter all user information.
toUnit value
inchonly
size Calculate size using inches and feet (or only inches) when config["units"] is imperial. Otherwise value is in centimeters.
logLine level
line
None Write line to logfile when verbose matched level bitwise.

env.logLine(1, name + " does not exist, no reload.")

logTime ctime
line
None Used to log filetimes and printed when verbose level has 3rd bit.
dateFileName prefix
postfix
name Creates a filename with a date. Used for grab: env.dateFileName("grab-", ".png")
loadSession NoneNone Load last saved session when config["remember_session"] is set. Otherwise session is set to 1200x800
saveSession NoneNone Save last session (if desired)
convertToRichFile filenametext Converts a file to a rich file. Lines starting with "==" are converted to links.
cleanup NoneNone Cleanup the context. Logfiles are closed and sys.stdout and sys.stderr are resetted to old values.