def make_user_dir():
    """
    Make sure MakeHuman folder storing per-user files exists.
    """
    import getpath
    userDir = getpath.getPath()
    if not os.path.isdir(userDir):
        os.makedirs(userDir)
    userDataDir = getpath.getPath('data')
    if not os.path.isdir(userDataDir):
        os.makedirs(userDataDir)
Пример #2
0
def loadProxy(human, path, type="Clothes"):
    try:
        npzpath = os.path.splitext(path)[0] + '.mhpxy'
        try:
            if not os.path.isfile(npzpath):
                log.message('compiled proxy file missing: %s', npzpath)
                raise RuntimeError('compiled proxy file missing: %s', npzpath)
            if os.path.isfile(path) and os.path.getmtime(path) > os.path.getmtime(npzpath):
                log.message('compiled proxy file out of date: %s', npzpath)
                raise RuntimeError('compiled file out of date: %s', npzpath)
            proxy = loadBinaryProxy(npzpath, human, type)
        except Exception as e:
            showTrace = not isinstance(e, RuntimeError)
            log.warning("Problem loading binary proxy: %s", e, exc_info=showTrace)
            proxy = loadTextProxy(human, path, type)    # TODO perhaps proxy type should be stored in .mhclo file too
            if getpath.isSubPath(npzpath, getpath.getPath()):
                # Only write compiled binary proxies to user data path
                try:
                    saveBinaryProxy(proxy, npzpath)
                except StandardError:
                    log.notice('unable to save compiled proxy: %s', npzpath, exc_info=True)
            else:
                log.debug('Not writing compiled proxies to system paths (%s).', npzpath)
    except:
        log.error('Unable to load proxy file: %s', path, exc_info=True)
        return None

    return proxy
Пример #3
0
    def __init__(self, category, proxyName, tabLabel = None, multiProxy = False, tagFilter = False):
        if not tabLabel:
            tabLabel = proxyName.capitalize()
        proxyName = proxyName.lower().replace(" ", "_")
        gui3d.TaskView.__init__(self, category, tabLabel)

        self.proxyName = proxyName
        self.label = tabLabel
        self.multiProxy = multiProxy
        self.tagFilter = tagFilter

        self.homeProxyDir = getpath.getPath(os.path.join('data', proxyName))
        self.sysProxyDir = mh.getSysDataPath(proxyName)

        if not os.path.exists(self.homeProxyDir):
            os.makedirs(self.homeProxyDir)

        self.paths = [self.homeProxyDir , self.sysProxyDir]

        self.human = gui3d.app.selectedHuman

        self._proxyCache = dict()
        self._proxyFileCache = None
        self._proxyFilePerUuid = None

        self.selectedProxies = []

        self.createFileChooser()
Пример #4
0
def _getFilePath(filename, folder = None):
    if not filename or not isinstance(filename, basestring):
        return filename

    # Ensure unix style path
    filename.replace('\\', '/')

    searchPaths = []

    # Search within current folder
    if folder:
        searchPaths.append(folder)

    from getpath import findFile, getPath, getSysDataPath, getSysPath, getDataPath
    searchPaths.extend([getDataPath(), getSysDataPath(), getPath(), getSysPath()])

    # Search in user / sys data, and user / sys root folders
    path = findFile(filename, searchPaths, strict=True)
    if path:
        return os.path.abspath(path)

    # Treat as absolute path or search relative to application path
    if os.path.isfile(filename):
        return os.path.abspath(filename)

    # Nothing found
    return os.path.normpath(filename)
    def __init__(self, category, proxyName, tabLabel = None, multiProxy = False, tagFilter = False, descriptionWidget = False):
        if not tabLabel:
            tabLabel = proxyName.capitalize()
        proxyName = proxyName.lower().replace(" ", "_")
        self.proxyName = proxyName
        gui3d.TaskView.__init__(self, category, tabLabel)
        filecache.MetadataCacher.__init__(self, self.getFileExtension(), self.proxyName + '_filecache.mhc')

        self.label = tabLabel
        self.multiProxy = multiProxy
        self.tagFilter = tagFilter
        self.descriptionWidget = descriptionWidget

        self.homeProxyDir = getpath.getPath(os.path.join('data', proxyName))
        self.sysProxyDir = mh.getSysDataPath(proxyName)

        if not os.path.exists(self.homeProxyDir):
            os.makedirs(self.homeProxyDir)

        self.paths = [self.homeProxyDir , self.sysProxyDir]

        self.human = gui3d.app.selectedHuman

        self._proxyFilePerUuid = None

        self.selectedProxies = []

        self.createFileChooser()
Пример #6
0
def loadMesh(path, locX=0, locY=0, locZ=0, loadColors=1):
    """
    This function loads the specified mesh object into internal MakeHuman data 
    structures, and returns it. The loaded file should be in Wavefront OBJ 
    format.
    
    Parameters:
    -----------
   
    path:     
      *String*.  The file system path to the file containing the object to load.

    locX:
      *float* X location of loaded obj, default = 0

    locY:
      *float* Y location of loaded obj, default = 0

    locZ:
      *float* Z location of loaded obj, default = 0
    """
    name = os.path.basename(path)
    obj = module3d.Object3D(name)

    obj.path = path
    obj.x = locX
    obj.y = locY
    obj.z = locZ

    try:
        npzpath = os.path.splitext(path)[0] + '.npz'
        try:
            if not os.path.isfile(npzpath):
                log.message('compiled file missing: %s', npzpath)
                raise RuntimeError()
            if os.path.isfile(path) and os.path.getmtime(path) > os.path.getmtime(npzpath):
                log.message('compiled file out of date: %s', npzpath)
                raise RuntimeError()
            loadBinaryMesh(obj, npzpath)
        except:
            loadTextMesh(obj, path)
            if isSubPath(npzpath, getPath('')):
                # Only write compiled binary meshes to user data path
                try:
                    saveBinaryMesh(obj, npzpath)
                except Exception:
                    log.notice('unable to save compiled mesh: %s', npzpath)
            else:
                log.debug('Not writing compiled meshes to system paths (%s).', npzpath)
    except:
        log.error('Unable to load obj file: %s', path, exc_info=True)
        return False

    obj.updateIndexBuffer()
    obj.calcNormals()
        
    return obj
Пример #7
0
 def dumpMissingStrings(self):
     if not self.language:
         return
     path = os.path.join(getPath(''), "data", "languages", self.language + ".missing")
     pathdir = os.path.dirname(path)
     if not os.path.isdir(pathdir):
         os.makedirs(pathdir)
     with open(path, 'wb') as f:
         for string in self.missingStrings:
             f.write('"%s": "",\n' % string.replace('\n', '\\n').encode('utf8'))
    def storeCache(self):
        if self._filecache is None or len(self._filecache) == 0:
            return

        self._filecache.cleanup()

        cachedir = getpath.getPath('cache')
        if not os.path.isdir(cachedir):
            os.makedirs(cachedir)
        saveCache(self._filecache)
Пример #9
0
 def storeProxyFileCache(self):
     """
     Save MH cache file for the proxy files managed by this library.
     """
     import filecache
     if self._proxyFileCache == None or len(self._proxyFileCache) == 0:
         return
     saveDir = getpath.getPath('cache')
     if not os.path.isdir(saveDir):
         os.makedirs(saveDir)
     filecache.saveCache(self._proxyFileCache, os.path.join(saveDir, self.proxyName + '_filecache.mhc'))
Пример #10
0
    def storeCache(self):
        import filecache
        if self._skelFileCache is None or len(self._skelFileCache) == 0:
            return

        filecache.cleanupCache(self._skelFileCache)

        cachedir = getpath.getPath('cache')
        if not os.path.isdir(cachedir):
            os.makedirs(cachedir)
        filecache.saveCache(self._skelFileCache, os.path.join(cachedir, 'skeleton_filecache.mhc'))
def addProxy(human, mhclofile, type):
    # TODO if eyes proxy is loaded, the one loaded by default should be removed

    if not os.path.isfile(mhclofile):
        mhclofile = getpath.findFile(mhclofile, 
                                     searchPaths = [getpath.getDataPath(), 
                                                    getpath.getSysDataPath(),
                                                    getpath.getPath(),
                                                    getpath.getSysPath()])
        if not os.path.isfile(mhclofile):
            #log.error("Proxy file %s does not exist (%s).", mhclofile, type)
            #return
            raise RuntimeError('Proxy file "%s" does not exist (%s).' % (mhclofile, type))

    import proxy
    pxy = proxy.loadProxy(human, mhclofile, type=type.capitalize())
    mesh,obj = pxy.loadMeshAndObject(human)

    if type == "proxymeshes":
        human.setProxy(pxy)
        return

    mesh,obj = pxy.loadMeshAndObject(human)

    if not mesh:
        raise RuntimeError('Failed to load proxy mesh "%s"', pxy.obj_file)

    def _adaptProxyToHuman(pxy, obj):
        mesh = obj.getSeedMesh()
        pxy.update(mesh)
        mesh.update()
        # Update subdivided mesh if smoothing is enabled
        if obj.isSubdivided():
            obj.getSubdivisionMesh()

    _adaptProxyToHuman(pxy, obj)
    obj.setSubdivided(human.isSubdivided())

    if type == "hair":
        human.hairProxy = pxy
    elif type == "eyes":
        human.eyesProxy = pxy
    elif type == "eyebrows":
        human.eyebrowsProxy = pxy
    elif type == "eyelashes":
        human.eyelashesProxy = pxy
    elif type == "teeth":
        human.teethProxy = pxy
    elif type == "tongue":
        human.tongueProxy = pxy
    elif type == "clothes":
        human.addClothesProxy(pxy)
    else:
        raise RuntimeError("Unknown proxy type: %s" % type)
def applyMaterial(matFile, obj):
    if not os.path.isfile(matFile):
        matFile = getpath.findFile(matFile, 
                                   searchPaths = [getpath.getDataPath(), 
                                                  getpath.getSysDataPath(),
                                                  getpath.getPath(),
                                                  getpath.getSysPath()])
    if not os.path.isfile(matFile):
        raise RuntimeError('Material file "%s" does not exist.', matFile)
    else:
        import material
        obj.material = material.fromFile( matFile )
Пример #13
0
 def storeProxyFileCache(self):
     """
     Save MH cache file for the proxy files managed by this library.
     """
     if self._proxyFileCache == None or len(self._proxyFileCache) == 0:
         return
     saveDir = getpath.getPath('cache')
     if not os.path.isdir(saveDir):
         os.makedirs(saveDir)
     f = open( os.path.join(saveDir, self.proxyName + '_filecache.mhc'), "wb")
     pickle.dump(self._proxyFileCache, f, protocol=2)
     f.close()
Пример #14
0
def loadMesh(path, loadColors=1, maxFaces=None, obj=None):
    """
    This function loads the specified mesh object into internal MakeHuman data 
    structures, and returns it. The loaded file should be in Wavefront OBJ 
    format.
    
    Parameters:
    -----------
   
    path:     
      *String*.  The file system path to the file containing the object to load.

    Note: loadColors is currently unused

    maxFaces:
      *uint* Number of faces per vertex (pole), None for default (min 4)
    """
    name = os.path.basename(path)
    if obj is None:
        obj = module3d.Object3D(name)
    if maxFaces:
        obj.MAX_FACES = maxFaces

    obj.path = path

    try:
        npzpath = os.path.splitext(path)[0] + '.npz'
        try:
            if not os.path.isfile(npzpath):
                log.message('compiled file missing: %s', npzpath)
                raise RuntimeError('compiled file missing: %s', npzpath)
            if os.path.isfile(path) and os.path.getmtime(path) > os.path.getmtime(npzpath):
                log.message('compiled file out of date: %s', npzpath)
                raise RuntimeError('compiled file out of date: %s', npzpath)
            loadBinaryMesh(obj, npzpath)
        except Exception as e:
            showTrace = not isinstance(e, RuntimeError)
            log.warning("Problem loading binary mesh: %s", e, exc_info=showTrace)
            loadTextMesh(obj, path)
            if isSubPath(npzpath, getPath('')):
                # Only write compiled binary meshes to user data path
                try:
                    saveBinaryMesh(obj, npzpath)
                except StandardError:
                    log.notice('unable to save compiled mesh: %s', npzpath)
            else:
                log.debug('Not writing compiled meshes to system paths (%s).', npzpath)
    except:
        log.error('Unable to load obj file: %s', path, exc_info=True)
        return False

    return obj
Пример #15
0
    def open(self):
        import io
        if self.debugpath is None:
            self.debugpath = getpath.getPath()

            if not os.path.exists(self.debugpath):
                os.makedirs(self.debugpath)

            self.debugpath = os.path.join(self.debugpath,
                                          "makehuman-debug.txt")
            self.debug = io.open(self.debugpath, "w", encoding="utf-8")
        else:
            self.debug = io.open(self.debugpath, "a", encoding="utf-8")
Пример #16
0
    def __init__(self):

        if sys.platform == 'win32':
            self.findPathsWindows()
        else:
            self.findPathsUnixoid()

        self._user_dir = getpath.getPath()
        if not os.path.isdir(self._user_dir):
            os.makedirs(self._user_dir)

        self._user_data_dir = getpath.getPath('data')
        if not os.path.isdir(self._user_data_dir):
            os.makedirs(self._user_data_dir)

        self._git_official_clone_location = os.path.abspath(
            os.path.join(self._user_dir, 'official_assets'))
        self._git_community_clone_location = os.path.abspath(
            os.path.join(self._user_dir, 'community_assets'))

        self.readOverridesFromEnvironment()

        if not os.path.isfile(self._git_command):
            print("\n\n\nCould not find git command\n\n")
            sys.exit(1)

        if not sys.platform == 'win32':
            if not self.testGitLfs():
                print(
                    "\n\n\nGIT LFS not detected. This routine requires LFS. See https://git-lfs.github.com/\n\n"
                )
                sys.exit(1)

        if os.path.isdir(self._git_official_clone_location):
            self.pullOfficialAssets()
        else:
            self.cloneOfficialAssets()

        self.copyOfficialAssets()
def get_platform_paths():
    global stdout_filename, stderr_filename
    import getpath

    home = getpath.getPath()

    if sys.platform == 'win32':
        stdout_filename = os.path.join(home, "python_out.txt")
        stderr_filename = os.path.join(home, "python_err.txt")

    elif sys.platform.startswith("darwin"):
        stdout_filename = os.path.join(home, "makehuman-output.txt")
        stderr_filename = os.path.join(home, "makehuman-error.txt")
Пример #18
0
def get_platform_paths():
    global stdout_filename, stderr_filename
    import getpath

    home = getpath.getPath()

    if sys.platform == 'win32':
        stdout_filename = os.path.join(home, "python_out.txt")
        stderr_filename = os.path.join(home, "python_err.txt")

    elif sys.platform.startswith("darwin"):
        stdout_filename = os.path.join(home, "makehuman-output.txt")
        stderr_filename = os.path.join(home, "makehuman-error.txt")
Пример #19
0
    def open(self):
        from codecs import open
        if self.debugpath is None:
            self.home = os.path.expanduser('~')
            self.debugpath = getpath.getPath()

            if not os.path.exists(self.debugpath):
                os.makedirs(self.debugpath)

            self.debugpath = os.path.join(self.debugpath, "makehuman-debug.txt")
            self.debug = open(self.debugpath, "w", encoding="utf-8")
        else:
            self.debug = open(self.debugpath, "a", encoding="utf-8")
Пример #20
0
def applyMaterial(matFile, obj):
    if not os.path.isfile(matFile):
        matFile = getpath.findFile(matFile,
                                   searchPaths=[
                                       getpath.getDataPath(),
                                       getpath.getSysDataPath(),
                                       getpath.getPath(),
                                       getpath.getSysPath()
                                   ])
    if not os.path.isfile(matFile):
        raise RuntimeError('Material file "%s" does not exist.', matFile)
    else:
        import material
        obj.material = material.fromFile(matFile)
Пример #21
0
    def open(self):
        from codecs import open
        if self.debugpath is None:
            self.home = os.path.expanduser('~')
            self.debugpath = getpath.getPath()

            if not os.path.exists(self.debugpath):
                os.makedirs(self.debugpath)

            self.debugpath = os.path.join(self.debugpath,
                                          "makehuman-debug.txt")
            self.debug = open(self.debugpath, "w", encoding="utf-8")
        else:
            self.debug = open(self.debugpath, "a", encoding="utf-8")
Пример #22
0
 def loadProxyFileCache(self, restoreFromFile = True):
     """
     Initialize or update the proxy file cache for this proxy library.
     Will attempt to load a previous cache from file if restoreFromFile is true.
     """
     import filecache
     self._proxyFilePerUuid = None
     if restoreFromFile:
         try:
             cacheFile = getpath.getPath(os.path.join('cache', self.proxyName + '_filecache.mhc'))
             if os.path.isfile(cacheFile):
                 self._proxyFileCache = filecache.loadCache(cacheFile)
         except:
             log.debug("Failed to restore proxy list cache from file %s", cacheFile)
     self._proxyFileCache = proxy.updateProxyFileCache(self.paths, self.getFileExtension(), self._proxyFileCache, proxytype=self.getProxyType())
Пример #23
0
 def onClicked(event):
     filename = getpath.pathToUnicode(gui.QtWidgets.QFileDialog.getOpenFileName(gui3d.app.mainwin, directory=self.home,
                                      filter='Python files ( *.py );; All files ( *.* )')[0])
     if os.path.isfile(filename) and os.path.splitext(filename)[1] == '.py':
         try:
             shutil.copy2(filename, getpath.getPath('plugins'))
         except OSError as e:
             gui3d.app.prompt('Error', 'Failed to copy {0:s} to user plugins folder'.format(filename), 'OK')
         for child in self.userPluginBox.children:
             self.userPluginBox.removeWidget(child)
         updatePlugins = self.getUserPlugins()
         for i, plugin in enumerate(updatePlugins):
             self.userPluginBox.addWidget(UserPluginCheckBox(plugin), row=i, alignment=gui.QtCore.Qt.AlignTop)
         gui3d.app.prompt('Info', 'The plugin copied successfully. To activate check '
                          'the plugin in the list and restart MakeHuman.', 'OK', helpId='installPluginHelp')
     self.home = os.path.dirname(filename)
Пример #24
0
def _parse_args():
    if len(sys.argv) < 2:
        return dict()

    import argparse    # requires python >= 2.7
    parser = argparse.ArgumentParser()

    # optional arguments
    parser.add_argument("--skipscripts", action="store_true", help="Skip running scripts for compiling assets")
    parser.add_argument("--nodownload", action="store_true", help="Do not run download assets script")

    # positional arguments
    parser.add_argument("sourcePath", default=None, nargs='?', help="Root path of makehuman source directory")
    parser.add_argument("targetPath", default=getpath.getPath("build-prepare-export"), nargs='?', help="Path to export to")

    argOptions = vars(parser.parse_args())
    return argOptions
Пример #25
0
def loadProxy(human, path, type="Clothes"):
    try:
        npzpath = os.path.splitext(path)[0] + '.mhpxy'
        asciipath = os.path.splitext(path)[0] + getAsciiFileExtension(type)
        try:
            if not os.path.isfile(npzpath):
                log.message('compiled proxy file missing: %s', npzpath)
                raise RuntimeError('compiled proxy file missing: %s', npzpath)
            if os.path.isfile(asciipath) and os.path.getmtime(
                    asciipath) > os.path.getmtime(npzpath):
                log.message('compiled proxy file out of date: %s', npzpath)
                raise RuntimeError('compiled file out of date: %s', npzpath)
            proxy = loadBinaryProxy(npzpath, human, type)
        except Exception as e:
            showTrace = not isinstance(e, RuntimeError)
            log.warning("Problem loading binary proxy: %s",
                        e,
                        exc_info=showTrace)
            proxy = loadTextProxy(
                human, asciipath, type
            )  # TODO perhaps proxy type should be stored in .mhclo file too
            if getpath.isSubPath(npzpath, getpath.getPath()):
                # Only write compiled binary proxies to user data path
                try:
                    log.message('Compiling binary proxy file %s', npzpath)
                    saveBinaryProxy(proxy, npzpath)
                except Exception:
                    log.notice('unable to save compiled proxy: %s',
                               npzpath,
                               exc_info=True)
                    if os.path.isfile(npzpath):
                        # Remove file again, in case an empty file is left
                        try:
                            os.remove(npzpath)
                        except Exception as e:
                            log.warning(
                                "Could not remove empty file %s that was left behind (%s).",
                                npzpath, e)
            else:
                log.debug('Not writing compiled proxies to system paths (%s).',
                          npzpath)
    except:
        log.error('Unable to load proxy file: %s', path, exc_info=True)
        return None

    return proxy
Пример #26
0
 def loadProxyFileCache(self, restoreFromFile=True):
     """
     Initialize or update the proxy file cache for this proxy library.
     Will attempt to load a previous cache from file if restoreFromFile is true.
     """
     self._proxyFilePerUuid = None
     if restoreFromFile:
         try:
             cacheFile = getpath.getPath(
                 os.path.join('cache', self.proxyName + '_filecache.mhc'))
             if os.path.isfile(cacheFile):
                 self._proxyFileCache = pickle.load(open(cacheFile, "rb"))
         except:
             log.debug("Failed to restore proxy list cache from file %s",
                       cacheFile)
     self._proxyFileCache = mh2proxy.updateProxyFileCache(
         self.paths, self.getFileExtension(), self._proxyFileCache)
Пример #27
0
    def __init__(self, category, app):
        self.app = app
        gui3d.TaskView.__init__(self, category, 'Custom')
        self.targetsPath = getpath.getPath('data/custom')
        if not os.path.exists(self.targetsPath):
            os.makedirs(self.targetsPath)

        self.optionsBox = self.addRightWidget(gui.GroupBox('Options'))
        rescanButton = self.optionsBox.addWidget(
            gui.Button("Rescan targets' folder"))
        self.keepValues = self.optionsBox.addWidget(
            gui.CheckBox('Keep Values', app.getSetting('keepCustomValues')))

        self.folderBox = self.addRightWidget(gui.GroupBox('Folders'))
        self.targetsBox = self.addLeftWidget(gui.StackedBox())

        self.human = app.selectedHuman

        @rescanButton.mhEvent
        def onClicked(event):

            backUpModifiers = {}

            if self.keepValues.isChecked():
                for name, modifier in self.modifiers.items():
                    if modifier.getValue() != 0:
                        backUpModifiers[name] = modifier.getValue()

            self.searchTargets()

            if self.keepValues.isChecked():
                for name, value in backUpModifiers.items():
                    modifier = self.modifiers.get(name)
                    if modifier:
                        modifier.setValue(value)
                self.syncSliders()
                self.human.applyAllTargets()

            backUpModifiers.clear()

        self.folders = []
        self.sliders = []
        self.modifiers = {}

        self.searchTargets()
Пример #28
0
 def _preStartupConfigScan(self):
     """Run a very primitive scan in order to pick up settings which has
     to be known before we launch the QtApplication object."""
     iniPath = getPath("settings.ini")
     data = None
     if os.path.exists(iniPath):
         with open(iniPath, encoding='utf-8') as f:
             data = json.load(f)
     if data is None:
         for key in _PRE_STARTUP_KEYS:
             self.preStartupSettings[key] = None
     else:
         for key in _PRE_STARTUP_KEYS:
             if key in data:
                 self.preStartupSettings[key] = data[key]
                 # Would be nice to log this, but log has not been initialized yet
                 print("PRE STARTUP SETTING: " + key + " = " + str(data[key]))
             else:
                 self.preStartupSettings[key] = None
Пример #29
0
def getUserPlugins():

    pluginsToLoad = []
    user_path = getpath.getPath('plugins')

    for file in os.listdir(user_path):

        location = os.path.join(user_path, file)

        if os.path.isdir(location) and not file.startswith('_'):
            pLocation = os.path.join(location, '__init__.py')
            if os.path.isfile(pLocation):
                pluginsToLoad.append((file, pLocation))

        elif os.path.isfile(location) and file.endswith(
                '.py') and not file.startswith('_'):
            name = os.path.splitext(file)[0]
            pluginsToLoad.append((name, location))

    return pluginsToLoad
Пример #30
0
        def onClicked(event):

            filename = getpath.pathToUnicode(
                gui.QtWidgets.QFileDialog.getOpenFileName(
                    gui3d.app.mainwin,
                    directory=self.home,
                    filter='Zip files ( *.zip );; All files ( *.* )'))

            dest_path = getpath.getPath('plugins')
            if os.path.isfile(filename):
                result = self.decompress(filename, dest_path)
                if result == 1:
                    gui3d.app.prompt('Error',
                                     'Not a zip file {0:s}'.format(filename),
                                     'OK')
                elif result == 3:
                    gui3d.app.prompt(
                        'Warning',
                        'Potentially dangerous zip file, containing files with unsuitable path. '
                        'Inspect/fix the zip file before usage!', 'OK')
                elif result == -1:
                    gui3d.app.prompt(
                        'Error',
                        'Zip file {0:s} contains exiting files.'.format(
                            filename), 'OK')
                elif result == 0:
                    gui3d.app.prompt(
                        'Info',
                        'The plugin copied successfully. To activate check '
                        'the plugin in the list and restart MakeHuman.',
                        'OK',
                        helpId='installPluginHelp')
                    for child in self.userPluginBox.children:
                        self.userPluginBox.removeWidget(child)
                    updatePlugins = self.getUserPlugins()
                    for i, plugin in enumerate(updatePlugins):
                        self.userPluginBox.addWidget(
                            UserPluginCheckBox(plugin),
                            row=i,
                            alignment=gui.QtCore.Qt.AlignTop)
            self.home = os.path.dirname(filename)
Пример #31
0
def _getFilePath(filename, folder = None, altExtensions=None):
    if altExtensions is not None:
        # Search for existing path with alternative file extension
        for aExt in altExtensions:
            if aExt.startswith('.'):
                aExt = aExt[1:]
            aFile = os.path.splitext(filename)[0]+'.'+aExt
            aPath = _getFilePath(aFile, folder, altExtensions=None)
            if os.path.isfile(aPath):
                # Path found, return result with original extension
                orgExt = os.path.splitext(filename)[1]
                path = os.path.splitext(aPath)[0]+orgExt
                return os.path.normpath(path)

    if not filename or not isinstance(filename, basestring):
        return filename

    # Ensure unix style path
    filename.replace('\\', '/')

    searchPaths = []

    # Search within current folder
    if folder:
        searchPaths.append(folder)

    from getpath import findFile, getPath, getSysDataPath, getSysPath, getDataPath
    searchPaths.extend([getDataPath(), getSysDataPath(), getPath(), getSysPath()])

    # Search in user / sys data, and user / sys root folders
    path = findFile(filename, searchPaths, strict=True)
    if path:
        return os.path.abspath(path)

    # Treat as absolute path or search relative to application path
    if os.path.isfile(filename):
        return os.path.abspath(filename)

    # Nothing found
    return os.path.normpath(filename)
Пример #32
0
    def config():
        userDir = getPath('')
        defaults = dict(mhUserDir = userDir.replace('\\','/'))

        try:
            filename = os.path.join(userDir, "logging.ini")
            if os.path.isfile(filename):
                logging.config.fileConfig(filename, defaults)
                return
        except Exception:
            pass

        try:
            logging.config.fileConfig(getSysDataPath('logging.ini'), defaults)
            return
        except Exception:
            pass

        try:
            logging.basicConfig(level = logging.DEBUG)
            return
        except Exception:
            pass
Пример #33
0
 def onClicked(event):
     filename = getpath.pathToUnicode(
         gui.QtWidgets.QFileDialog.getOpenFileName(
             gui3d.app.mainwin,
             directory=self.home,
             filter='Python files ( *.py );; All files ( *.* )')[0])
     if os.path.isfile(filename) and os.path.splitext(
             filename)[1] == '.py':
         try:
             shutil.copy2(filename, getpath.getPath('plugins'))
         except OSError as e:
             gui3d.app.prompt(
                 'Error',
                 'Failed to copy {0:s} to user plugins folder'.format(
                     filename), 'OK')
         self.updatePluginList()
         gui3d.app.prompt(
             'Info',
             'The plugin copied successfully. To activate, check '
             'the plugin in the list and press the "Activate"-Button or restart MakeHuman.',
             'OK',
             helpId='installPluginHelp')
     self.home = os.path.dirname(filename)
Пример #34
0
    def config():
        userDir = getPath('')
        defaults = dict(mhUserDir = userDir.replace('\\','/'))

        try:
            filename = os.path.join(userDir, "logging.ini")
            if os.path.isfile(filename):
                logging.config.fileConfig(filename, defaults)
                return
        except Exception:
            pass

        try:
            logging.config.fileConfig(getSysDataPath('logging.ini'), defaults)
            return
        except Exception:
            pass

        try:
            logging.basicConfig(level = logging.DEBUG)
            return
        except Exception:
            pass
Пример #35
0
    def config():
        userDir = getPath("")
        defaults = dict(mhUserDir=userDir.replace("\\", "/"))

        try:
            filename = os.path.join(userDir, "logging.ini")
            if os.path.isfile(filename):
                logging.config.fileConfig(filename, defaults)
                return
        except Exception:
            pass

        try:
            logging.config.fileConfig(os.path.join("data", "logging.ini"), defaults)
            return
        except Exception:
            pass

        try:
            logging.basicConfig(level=logging.DEBUG)
            return
        except Exception:
            pass
    def __init__(self, category, app):
        self.app = app
        gui3d.TaskView.__init__(self, category, 'Custom')
        self.targetsPath = getpath.getPath('data/custom')
        if not os.path.exists(self.targetsPath):
            os.makedirs(self.targetsPath)

        self.optionsBox = self.addRightWidget(gui.GroupBox('Options'))
        rescanButton = self.optionsBox.addWidget(gui.Button("Rescan targets' folder"))

        self.folderBox = self.addRightWidget(gui.GroupBox('Folders'))
        self.targetsBox = self.addLeftWidget(gui.StackedBox())

        @rescanButton.mhEvent
        def onClicked(event):
            #TODO: undo any applied change here
            self.searchTargets()

        self.folders = []
        self.sliders = []
        self.modifiers = {}

        self.searchTargets()
Пример #37
0
    def __init__(self):

        self._git_command = gitutils.findPathToGit()

        self._user_dir = getpath.getPath()
        if not os.path.isdir(self._user_dir):
            os.makedirs(self._user_dir)

        self._user_data_dir = getpath.getDataPath()
        if not os.path.isdir(self._user_data_dir):
            os.makedirs(self._user_data_dir)

        self._git_official_clone_location = os.path.abspath(
            os.path.realpath(os.path.join(self._user_dir, 'official_assets')))

        self.readOverridesFromEnvironment()

        if self._git_command is None or not os.path.isfile(self._git_command):
            print("\n\n\nCould not find git command\n\n")
            sys.exit(1)

        if not gitutils.hasGitLFSSupport():
            print(
                "\n\n\nGIT LFS not detected. This routine requires LFS. See https://git-lfs.github.com/\n\n"
            )
            sys.exit(1)

        if os.path.isdir(self._git_official_clone_location):
            gitutils.pullRepo(self._git_official_clone_location,
                              self._git_official_assets_branch)
        else:
            gitutils.cloneRepo(self._git_official_assets_repo,
                               self._git_official_clone_location,
                               self._git_official_assets_branch,
                               extraargs=['--depth=1'])

        self.copyOfficialAssets()
    def __init__(self, category, app):
        self.app = app
        gui3d.TaskView.__init__(self, category, "Custom")
        self.targetsPath = getpath.getPath("data/custom")
        if not os.path.exists(self.targetsPath):
            os.makedirs(self.targetsPath)

        self.optionsBox = self.addRightWidget(gui.GroupBox("Options"))
        rescanButton = self.optionsBox.addWidget(gui.Button("Rescan targets' folder"))

        self.folderBox = self.addRightWidget(gui.GroupBox("Folders"))
        self.targetsBox = self.addLeftWidget(gui.StackedBox())

        self.human = app.selectedHuman

        @rescanButton.mhEvent
        def onClicked(event):
            self.searchTargets()

        self.folders = []
        self.sliders = []
        self.modifiers = {}

        self.searchTargets()
Пример #39
0
    def __init__(self, category, app):
        self.app = app
        gui3d.TaskView.__init__(self, category, 'Custom')
        self.targetsPath = getpath.getPath('data/custom')
        if not os.path.exists(self.targetsPath):
            os.makedirs(self.targetsPath)

        self.optionsBox = self.addRightWidget(gui.GroupBox('Options'))
        rescanButton = self.optionsBox.addWidget(gui.Button("Rescan targets' folder"))

        self.folderBox = self.addRightWidget(gui.GroupBox('Folders'))
        self.targetsBox = self.addLeftWidget(gui.StackedBox())

        self.human = app.selectedHuman

        @rescanButton.mhEvent
        def onClicked(event):
            self.searchTargets()

        self.folders = []
        self.sliders = []
        self.modifiers = {}

        self.searchTargets()
Пример #40
0
def listCustomFiles(config):
    files = []
    if config.useCustomTargets:
        folder = getPath('data/custom')
        files += readCustomFolder(folder, config)
    return files
Пример #41
0
def loadMesh(path, loadColors=1, maxFaces=None, obj=None):
    """
    This function loads the specified mesh object into internal MakeHuman data 
    structures, and returns it. The loaded file should be in Wavefront OBJ 
    format.
    
    Parameters:
    -----------
   
    path:     
      *String*.  The file system path to the file containing the object to load.

    Note: loadColors is currently unused

    maxFaces:
      *uint* Number of faces per vertex (pole), None for default (min 4)
    """
    if type(path) is bytes:
        path = path.decode('utf-8')
    log.debug("loadMesh in files3d received a raw path of %s", path)
    name = os.path.basename(path)
    if isinstance(name, bytes):
        name.decode('utf-8')
    log.debug("os.path.basename produce a name of: %s", name)
    log.debug("files3d loadMesh basename is %s", name)
    if obj is None:
        obj = module3d.Object3D(os.path.splitext(path)[0])
        log.message("obj name changed from None to %s",
                    module3d.Object3D(name))
    if maxFaces:
        obj.MAX_FACES = maxFaces

    obj.path = path

    try:
        import getpath
        path = getpath.getSysPath(path)
        log.message("Expanded path is found to be %s", path)
        npzpath = os.path.splitext(path)[0] + '.npz'

        log.debug("files3d loadMesh will attempt to load %s", npzpath)

        if not os.path.isfile(npzpath):
            log.message('compiled file missing: %s', npzpath)
            raise RuntimeError('compiled file missing: %s', npzpath)
        if os.path.isfile(
                path) and os.path.getmtime(path) > os.path.getmtime(npzpath):
            log.message('compiled file out of date: %s', npzpath)
            raise RuntimeError('compiled file out of date: %s', npzpath)
        loadBinaryMesh(obj, npzpath)

        log.message("files3d loadMesh attempting to load %s", npzpath)
        loadTextMesh(obj, path)
        if isSubPath(npzpath, getPath('')):
            # Only write compiled binary meshes to user data path
            saveBinaryMesh(obj, npzpath)
            log.debug('files3d just saved compiled mesh: %s', npzpath)
        else:
            log.debug("files3d using getpath('') could not find (%s).",
                      npzpath)
    except:
        log.error('Unable to load obj file: %s', path, exc_info=True)
        return False

    return obj
Пример #42
0
 def loadCache(self):
     filename = getpath.getPath(os.path.join('cache', self.cache_file))
     self._filecache = loadCache(filename, self.cache_format_version)
     self._filecache.get_metadata_filename = self.getMetadataFile
    def __init__(self, category, appFacs):
        gui3d.TaskView.__init__(self, category, 'Pain Face Generator')
        self.facs_human = appFacs.selectedHuman
        camera = G.app.modelCamera
        self.app = appFacs

        # self.targets_path_emotions_blender = getpath.getPath('data/FACSHuman/00 Emotions')
        self.targets_path_upper_face = getpath.getPath(
            'data/FACSHuman/01 Upper Face AUs')
        self.targets_path_lower_face = getpath.getPath(
            'data/FACSHuman/02 Lower Face AUs')
        self.targets_path_lip_jaw = getpath.getPath(
            'data/FACSHuman/03 Lip Parting and Jaw Opening')
        # self.targets_path_eye = getpath.getPath('data/FACSHuman/04 Eye Positions')
        # self.targets_path_head = getpath.getPath('data/FACSHuman/05 Head Positions')
        # self.targets_path_misc = getpath.getPath('data/FACSHuman/06 Miscellaneous AUs')

        self.last_directory_rendering = ''
        self.images_to_convert = ''
        self.video_destination = ''
        #self.video_background = 'black.jpg'
        self.renderingWidth = '500'
        self.renderingHeight = '500'
        self.images_set_dir_destination = ''

        # box_emotions_blender = self.addLeftWidget(gui.GroupBox('Emotions blender'))
        box_upper = self.addLeftWidget(gui.GroupBox('Upper Face AUs'))
        box_lower = self.addLeftWidget(gui.GroupBox('Lower Face AUs'))
        # box_head = self.addLeftWidget(gui.GroupBox('Head Positions'))
        # box_eye = self.addLeftWidget(gui.GroupBox('Eye Positions'))
        box_lip = self.addLeftWidget(
            gui.GroupBox('Lip Parting and Jaw Opening'))
        # box_misc = self.addLeftWidget(gui.GroupBox('Miscellaneous AUs'))
        box_weight = self.addRightWidget(gui.GroupBox('AU Matrix Weights'))
        box_gen = self.addRightWidget(gui.GroupBox('View and Generate Images'))
        box_tools = self.addRightWidget(gui.GroupBox('Tools'))
        # box_aus_code = self.addRightWidget(gui.GroupBox('Action Units coding'))

        # self.general_intensity = box_aus_code.addWidget(gui.Slider(value=100, min=0, max=100, label=['General Intensity : ','%d%%']), columnSpan = 2)
        # #self.general_intensity_progress_bar = box_tools.addWidget(gui.ProgressBar())
        # #self.general_intensity_progress_bar.setProgress(1)
        # self.txt_file_loaded = box_aus_code.addWidget(gui.TextView('- New facial code -'), columnSpan = 2)
        # self.load_facs_button = box_aus_code.addWidget(gui.BrowseButton('open', "Load FACS Code"), 3, 0)
        # self.save_facs_button = box_aus_code.addWidget(gui.BrowseButton('save', "Save FACS Code"), 3, 1)
        # # self.save_target_button = box_aus_code.addWidget(gui.BrowseButton('save', "Save target"))
        # self.generate_au_coding_button = box_aus_code.addWidget(gui.Button('Get AU\'s Code'), columnSpan = 2)
        # self.txt_coding = box_aus_code.addWidget(gui.TextView('AU\'s code generated :'), columnSpan = 2)
        # self.au_coding = box_aus_code.addWidget(gui.DocumentEdit(text='Neutral'), columnSpan = 2)
        # self.one_shot_button = box_tools.addWidget(gui.Button('Take one shot'), 1, 0)

        self.survey_img_button = box_weight.addWidget(
            gui.Button('Generate Survey Images'), columnSpan=2)
        self.au4_lab = box_weight.addWidget(gui.TextView('AU4 Weight'))
        self.au4_val = box_weight.addWidget(gui.TextEdit(text='0.8865'))
        self.au7_lab = box_weight.addWidget(gui.TextView('AU7 Weight'))
        self.au7_val = box_weight.addWidget(gui.TextEdit(text='0.7758'))
        self.au9_lab = box_weight.addWidget(gui.TextView('AU9 Weight'))
        self.au9_val = box_weight.addWidget(gui.TextEdit(text='2.6129'))
        self.au10_lab = box_weight.addWidget(gui.TextView('AU10 Weight'))
        self.au10_val = box_weight.addWidget(gui.TextEdit(text='3.6517'))

        self.reset_camera_button = box_gen.addWidget(
            gui.Button('Full face camera view'), columnSpan=2)
        self.master_slider = box_gen.addWidget(gui.Slider(
            value=0, min=0, max=100, label=['General Intensity : ', '%d%%']),
                                               columnSpan=2)
        self.one_shot_button = box_gen.addWidget(gui.Button('Take one shot'),
                                                 columnSpan=2)
        self.generate_set_button = box_gen.addWidget(
            gui.Button('generate pain image set'), columnSpan=2)

        self.one_shot_stereo_button = box_tools.addWidget(
            gui.Button('Stereoscopic shot'), columnSpan=2)
        self.au_set_gen_button = box_tools.addWidget(
            gui.BrowseButton('open', "Dir to img"), 2, 0)
        self.material_gen_button = box_tools.addWidget(
            gui.BrowseButton('open', "Images set"), 2, 1)
        self.material_gen_dir_button = box_tools.addWidget(gui.FileEntryView(
            'Browse', mode='dir'),
                                                           columnSpan=2)
        self.camera_slider_x = box_tools.addWidget(gui.Slider(
            value=0, min=-1, max=1, label=['camera x: ', '%2f']),
                                                   columnSpan=2)
        self.camera_slider_y = box_tools.addWidget(gui.Slider(
            value=0, min=-1, max=1, label=['camera y: ', '%2f']),
                                                   columnSpan=2)
        self.camera_slider_zoom = box_tools.addWidget(gui.Slider(
            value=0, min=4, max=9, label=['Zoom: ', '%2f']),
                                                      columnSpan=2)
        self.rotation_slider_z = box_tools.addWidget(gui.Slider(
            value=0, min=-90, max=90, label=['rotation z: ', '%2f']),
                                                     columnSpan=2)
        self.reset_button = box_tools.addWidget(
            gui.Button('Reset Facial Code'), columnSpan=2)
        self.full_set_button = box_tools.addWidget(
            gui.Button('Full set generation'), columnSpan=2)
        self.facsvatar_set_button = box_tools.addWidget(gui.BrowseButton(
            'open', 'FACAvatar rendering'),
                                                        columnSpan=2)

        self.facs_code_names_path = getpath.getDataPath('FACSHuman')
        self.facs_code_names_file = self.facs_code_names_path + '/au.json'
        self.facs_code_names = json.loads(
            open(self.facs_code_names_file).read())

        self.slidersValues = {
        }  #Keep a trace of values in the General intensity sliders function
        self.sliders = {}
        self.sliders_order = []
        self.labelSlider = {}
        #self.modifiers = {}
        self.au_timeline_values = {}  # For the animation functionality
        self.au_facs_loaded_file_values = {}  # For the animation functionality

        self.facs_code_names_path = getpath.getDataPath('FACSHuman')
        self.facs_code_names_file = self.facs_code_names_path + '/au.json'
        self.facs_code_names = json.loads(
            open(self.facs_code_names_file).read())

        # self.searchTargets(self.targets_path_emotions_blender, box_emotions_blender, 'Emotions Blender')
        self.searchTargets(self.targets_path_upper_face, box_upper,
                           'Upper Face AUs')
        self.searchTargets(self.targets_path_lower_face, box_lower,
                           'Lower Face AUs')
        self.searchTargets(self.targets_path_lip_jaw, box_lip,
                           'Lip Parting and Jaw Opening')
        # self.searchTargets(self.targets_path_eye, box_eye, 'Eye Positions')
        # self.searchTargets(self.targets_path_head, box_head, 'Head Positions')
        # self.searchTargets(self.targets_path_misc, box_misc, 'Miscellaneous AUs')

        @self.camera_slider_x.mhEvent
        def onChanging(value):
            pos = self.facs_human.getPosition()
            pos[0] = value
            self.facs_human.setPosition(pos)
            mh.redraw()

        @self.camera_slider_y.mhEvent
        def onChanging(value):
            pos = self.facs_human.getPosition()
            pos[1] = value
            self.facs_human.setPosition(pos)
            mh.redraw()

        @self.camera_slider_zoom.mhEvent
        def onChanging(value):
            camera.setZoomFactor(value)

        @self.rotation_slider_z.mhEvent
        def onChanging(value):
            pos = self.facs_human.getRotation()
            pos[1] = value
            self.facs_human.setRotation(pos)
            mh.redraw()

##########################################################################
# Generate all AUs images
##########################################################################

        @self.facsvatar_set_button.mhEvent
        def onClicked(path):
            self.generateFacsvatarDirSet(path)

##########################################################################
# Generate all AUs images
##########################################################################

        @self.au_set_gen_button.mhEvent
        def onClicked(path):
            self.generateDirSet(path)

##########################################################################
# Generate material images
##########################################################################

        @self.material_gen_button.mhEvent
        def onClicked(path):
            self.generateCompleteImagesSetFromDir(path)
##########################################################################
# Generate material images
##########################################################################

        @self.material_gen_dir_button.mhEvent
        def onFileSelected(event):
            # self.images_set_dir_destination = os.path.dirname(path)
            self.images_set_dir_destination = event.path
            # self.images_set_dir_destination = os.path.dirname(path)
            gui3d.app.statusPersist('Images destination : ' +
                                    str(self.images_set_dir_destination))

##########################################################################
# Reset button for camera's orientation to have full face view
# in order to have constant point of view for experiments
##########################################################################

        @self.reset_camera_button.mhEvent
        def onClicked(event):
            gui3d.app.setTargetCamera(131, 9, False)
            gui3d.app.axisView([0.0, 0.0, 0.0])
            pos = [0, 0.2, 0]
            self.facs_human.setPosition(pos)
            self.camera_slider_x.setValue(0)
            self.camera_slider_y.setValue(0.2)
            self.camera_slider_zoom.setValue(9)
            self.rotation_slider_z.setValue(0)
            self.rotation_slider_z.onChanging(0)
            self.rotation_slider_z.update()
            mh.redraw()
            gui3d.app.statusPersist('Camera updated')

        @self.one_shot_button.mhEvent
        def onClicked(event):
            self.renderFacsPicture()

##########################################################################
# Reset facial code and AUs button
##########################################################################

        @self.reset_button.mhEvent
        def onClicked(event):
            G.app.prompt('Confirmation',
                         'Do you really want to reset your Facial code ?',
                         'Yes', 'Cancel', self.resetFacialCodes)

##########################################################################
# Generate 81 images for the survey website
##########################################################################

        @self.survey_img_button.mhEvent
        def onClicked(event):
            weight = [0, 0.5, 1]
            for i4 in range(3):
                for i7 in range(3):
                    for i9 in range(3):
                        for i10 in range(3):
                            self.survey_img_gen(weight[i4], weight[i7],
                                                weight[i9], weight[i10])
                            time.sleep(0.5)
                            self.renderSurveyImg(i4, i7, i9, i10)

##########################################################################
# Generate and save 101 images for overall intensity = 0% to 100%
##########################################################################

        @self.generate_set_button.mhEvent
        def onClicked(event):
            for val in range(0, 101):
                self.generate_face_set(val)
                time.sleep(0.5)
                self.renderFacsPicture()


##########################################################################
# View pain expression change at various general intensities
##########################################################################

        @self.master_slider.mhEvent
        def onChange(value):
            self.masterslider_render(value, True)
Пример #44
0
 def loadCache(self):
     import filecache
     filename = getpath.getPath('cache/material_filecache.mhc')
     if os.path.isfile(filename):
         self._matFileCache = filecache.loadCache(filename)
Пример #45
0
    def projectLighting(self):

            dstImg = projection.mapLighting()
            #dstImg.resize(128, 128);

            dstImg.save(getPath('data/skins/lighting.png'))
Пример #46
0
 def loadCache(self):
     import filecache
     filename = getpath.getPath('cache/skeleton_filecache.mhc')
     if os.path.isfile(filename):
         self._skelFileCache = filecache.loadCache(filename)
Пример #47
0
    def __init__(self, app):
        camera = app.modelCamera

        #rendering properties
        self.camera = camera
        self.app = app
        #self.lastUndoItem = None
        #self.lastRotation = [0,0,0]
        #self.lastCameraPosition = [self.camera.eyeX, -self.camera.eyeY, self.camera.eyeZ]
        #self.firstTimeRendering = True
        self.renderResult = ""

        #resource paths
        self.renderPath = getPath('render/renderman_output')
        self.ribsPath = os.path.join(self.renderPath, 'ribFiles')
        self.usrShaderPath = os.path.join(self.ribsPath, 'shaders')
        
        #Texture paths
        self.usrTexturePath = os.path.join(self.ribsPath, 'textures')
        self.applicationPath = getSysPath()
        self.appTexturePath = getSysDataPath('textures')
        self.hairTexturePath = getSysDataPath('hairstyles')
        self.skinTexturePath = getPath('data/skins')
        
        #self.appObjectPath = os.path.join(self.applicationPath, 'data', '3dobjs')
        self.worldFileName = os.path.join(self.ribsPath,"world.rib").replace('\\', '/')
        self.lightsFolderPath = os.path.join(getSysDataPath('lights'), 'aqsis')       

        #mainscenefile
        self.sceneFileName = os.path.join(self.ribsPath, "scene.rib")

        #Human in the scene
        self.humanCharacter = RMRHuman(app.selectedHuman, "base.obj", app.selectedHuman.mesh, self.ribsPath)
        self.humanCharacter.materialInit()
        self.humanCharacter.subObjectsInit()
        
        #Rendering options
        #self.calcShadow = False
        #self.calcSSS = False

        ##Shadow path
        #self.shadowFileName = os.path.join(self.ribsPath,"shadow.rib").replace('\\', '/')

        ##SSS path        
        #self.bakeFilename = os.path.join(self.ribsPath,"skinbake.rib").replace('\\', '/')
        #self.lightmapFileName = os.path.join(self.ribsPath,"lightmap.rib").replace('\\', '/')
        #self.bakeTMPTexture = os.path.join(self.usrTexturePath,"bake.bake").replace('\\', '/')
        #self.bakeTexture = os.path.join(self.usrTexturePath,"bake.texture").replace('\\', '/')
        #self.lightmapTMPTexture = os.path.join(self.usrTexturePath,"lightmap.png").replace('\\', '/')
        #self.lightmapTexture = os.path.join(self.usrTexturePath,"lightmap.texture").replace('\\', '/')

        #Lights list
        self.lights = []

        #creating resources folders
        if not os.path.isdir(self.renderPath):
            os.makedirs(self.renderPath)
        if not os.path.isdir(self.ribsPath):
            os.makedirs(self.ribsPath)
        if not os.path.isdir(self.usrTexturePath):
            os.makedirs(self.usrTexturePath)
        if not os.path.isdir(self.usrShaderPath):
            os.makedirs(self.usrShaderPath)
Пример #48
0
        self.addMessage("Starting server thread.")
        self.workerthread = WorkerThread(socketConfig=self.socketConfig)
        self.workerthread.signalEvaluateCall.connect(self.evaluateCall)
        self.workerthread.signalAddMessage.connect(self.threadMessage)
        self.workerthread.start()

    def closeSocket(self):
        #self.addMessage("Closing socket.")
        if self.workerthread:
            self.workerthread.stopListening()
        self.workerthread = None


category = None
taskview = None
cfgFile = os.path.join(getpath.getPath(),'socket.cfg')


def load(app):
    socketConfig = {}
    if os.path.isfile(cfgFile):
        try:
            with open(cfgFile, 'r', encoding='utf-8') as f:
                socketConfig = json.loads(f.read())
        except json.JSONDecodeError:
            socketConfig = None
    category = app.getCategory('Community')
    taskview = category.addTask(SocketTaskView(category, socketConfig=socketConfig))


def unload(app):
Пример #49
0
def make_user_dir():
    import getpath
    userDir = getpath.getPath('')
    if not os.path.isdir(userDir):
        os.makedirs(userDir)
 def loadCache(self):
     filename = getpath.getPath(os.path.join('cache', self.cache_file))
     self._filecache = loadCache(filename, self.cache_format_version)
     self._filecache.get_metadata_filename = self.getMetadataFile
Пример #51
0
def addProxy(human, mhclofile, type):
    # TODO if eyes proxy is loaded, the one loaded by default should be removed

    if not os.path.isfile(mhclofile):
        mhclofile = getpath.findFile(mhclofile,
                                     searchPaths=[
                                         getpath.getDataPath(),
                                         getpath.getSysDataPath(),
                                         getpath.getPath(),
                                         getpath.getSysPath()
                                     ])
        if not os.path.isfile(mhclofile):
            #log.error("Proxy file %s does not exist (%s).", mhclofile, type)
            #return
            raise RuntimeError('Proxy file "%s" does not exist (%s).' %
                               (mhclofile, type))

    import proxy
    _proxy = proxy.readProxyFile(human, mhclofile, type=type.capitalize())

    if type == "proxymeshes":
        human.setProxy(_proxy)
        return

    mesh, obj = _proxy.loadMeshAndObject(human)

    if not mesh:
        raise RuntimeError('Failed to load proxy mesh "%s"', _proxy.obj_file)

    def _adaptProxyToHuman(pxy, obj):
        mesh = obj.getSeedMesh()
        pxy.update(mesh)
        mesh.update()
        # Update subdivided mesh if smoothing is enabled
        if obj.isSubdivided():
            obj.getSubdivisionMesh()

    _adaptProxyToHuman(_proxy, obj)

    # TODO oh so tedious...
    if type == "hair":
        human.hairProxy = _proxy
        human.hairObj = obj
    elif type == "eyes":
        human.eyesProxy = _proxy
        human.eyesObj = obj
    elif type == "genitals":
        human.genitalsProxy = _proxy
        human.genitalsObj = obj
    elif type == "eyebrows":
        human.eyebrowsProxy = _proxy
        human.eyebrowsObj = obj
    elif type == "eyelashes":
        human.eyelashesProxy = _proxy
        human.eyelashesObj = obj
    elif type == "teeth":
        human.teethProxy = _proxy
        human.teethObj = obj
    elif type == "tongue":
        human.tongueProxy = _proxy
        human.tongueObj = obj
    elif type == "clothes":
        human.clothesProxies[_proxy.uuid] = _proxy
        human.clothesObjs[_proxy.uuid] = obj
Пример #52
0
 def loadCache(self):
     import filecache
     filename = getpath.getPath('cache/skeleton_filecache.mhc')
     if os.path.isfile(filename):
         self._skelFileCache = filecache.loadCache(filename)
Пример #53
0
def listCustomFiles(config):
    files = []
    if config.useCustomTargets:
        folder = getPath('data/custom')
        files += readCustomFolder(folder, config)
    return files
Пример #54
0
    def projectLighting(self):

            dstImg = projection.mapLighting()
            #dstImg.resize(128, 128);

            dstImg.save(getPath('data/skins/lighting.png'))
Пример #55
0
def make_user_dir():
    import getpath
    userDir = getpath.getPath('')
    if not os.path.isdir(userDir):
        os.makedirs(userDir)
 def loadCache(self):
     import filecache
     filename = getpath.getPath('cache/material_filecache.mhc')
     if os.path.isfile(filename):
         self._matFileCache = filecache.loadCache(filename)
Пример #57
0
    def __init__(self, app):
        camera = app.modelCamera

        #rendering properties
        self.camera = camera
        self.app = app
        #self.lastUndoItem = None
        #self.lastRotation = [0,0,0]
        #self.lastCameraPosition = [self.camera.eyeX, -self.camera.eyeY, self.camera.eyeZ]
        #self.firstTimeRendering = True
        self.renderResult = ""

        #resource paths
        self.renderPath = getPath('render/renderman_output')
        self.ribsPath = os.path.join(self.renderPath, 'ribFiles')
        self.usrShaderPath = os.path.join(self.ribsPath, 'shaders')
        
        #Texture paths
        self.usrTexturePath = os.path.join(self.ribsPath, 'textures')
        self.applicationPath = getSysPath()
        self.appTexturePath = getSysDataPath('textures')
        self.hairTexturePath = getSysDataPath('hairstyles')
        self.skinTexturePath = getPath('data/skins')
        
        #self.appObjectPath = os.path.join(self.applicationPath, 'data', '3dobjs')
        self.worldFileName = os.path.join(self.ribsPath,"world.rib").replace('\\', '/')
        self.lightsFolderPath = os.path.join(getSysDataPath('lights'), 'aqsis')       

        #mainscenefile
        self.sceneFileName = os.path.join(self.ribsPath, "scene.rib")

        #Human in the scene
        self.humanCharacter = RMRHuman(app.selectedHuman, "base.obj", app.selectedHuman.mesh, self.ribsPath)
        self.humanCharacter.materialInit()
        self.humanCharacter.subObjectsInit()
        
        #Rendering options
        #self.calcShadow = False
        #self.calcSSS = False

        ##Shadow path
        #self.shadowFileName = os.path.join(self.ribsPath,"shadow.rib").replace('\\', '/')

        ##SSS path        
        #self.bakeFilename = os.path.join(self.ribsPath,"skinbake.rib").replace('\\', '/')
        #self.lightmapFileName = os.path.join(self.ribsPath,"lightmap.rib").replace('\\', '/')
        #self.bakeTMPTexture = os.path.join(self.usrTexturePath,"bake.bake").replace('\\', '/')
        #self.bakeTexture = os.path.join(self.usrTexturePath,"bake.texture").replace('\\', '/')
        #self.lightmapTMPTexture = os.path.join(self.usrTexturePath,"lightmap.png").replace('\\', '/')
        #self.lightmapTexture = os.path.join(self.usrTexturePath,"lightmap.texture").replace('\\', '/')

        #Lights list
        self.lights = []

        #creating resources folders
        if not os.path.isdir(self.renderPath):
            os.makedirs(self.renderPath)
        if not os.path.isdir(self.ribsPath):
            os.makedirs(self.ribsPath)
        if not os.path.isdir(self.usrTexturePath):
            os.makedirs(self.usrTexturePath)
        if not os.path.isdir(self.usrShaderPath):
            os.makedirs(self.usrShaderPath)
Пример #58
0
def loadMesh(path, locX=0, locY=0, locZ=0, loadColors=1, maxFaces=None):
    """
    This function loads the specified mesh object into internal MakeHuman data 
    structures, and returns it. The loaded file should be in Wavefront OBJ 
    format.
    
    Parameters:
    -----------
   
    path:     
      *String*.  The file system path to the file containing the object to load.

    locX:
      *float* X location of loaded obj, default = 0

    locY:
      *float* Y location of loaded obj, default = 0

    locZ:
      *float* Z location of loaded obj, default = 0

    Note: loadColors is currently unused

    maxFaces:
      *uint* Number of faces per vertex (pole), None for default (min 4)
    """
    name = os.path.basename(path)
    obj = module3d.Object3D(name)
    if maxFaces:
        obj.MAX_FACES = maxFaces

    obj.path = path
    obj.x = locX
    obj.y = locY
    obj.z = locZ

    try:
        npzpath = os.path.splitext(path)[0] + '.npz'
        try:
            if not os.path.isfile(npzpath):
                log.message('compiled file missing: %s', npzpath)
                raise RuntimeError('compiled file missing: %s', npzpath)
            if os.path.isfile(path) and os.path.getmtime(
                    path) > os.path.getmtime(npzpath):
                log.message('compiled file out of date: %s', npzpath)
                raise RuntimeError('compiled file out of date: %s', npzpath)
            loadBinaryMesh(obj, npzpath)
        except Exception as e:
            showTrace = not isinstance(e, RuntimeError)
            log.warning("Problem loading binary mesh: %s",
                        e,
                        exc_info=showTrace)
            loadTextMesh(obj, path)
            if isSubPath(npzpath, getPath('')):
                # Only write compiled binary meshes to user data path
                try:
                    saveBinaryMesh(obj, npzpath)
                except StandardError:
                    log.notice('unable to save compiled mesh: %s', npzpath)
            else:
                log.debug('Not writing compiled meshes to system paths (%s).',
                          npzpath)
    except:
        log.error('Unable to load obj file: %s', path, exc_info=True)
        return False

    return obj