Exemplo n.º 1
0
    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'Pose')
        filecache.MetadataCacher.__init__(self, ['bvh'], 'pose_filecache.mhc')
        self.cache_format_version = '1c'  # Bump cacher version for updated format of pose metadata

        self.human = G.app.selectedHuman
        self.currentPose = None
        self.bvh_bone_length = None
        self.bvh_root_translation = None

        self.sysDataPath = getpath.getSysDataPath('poses')
        self.userDataPath = getpath.getDataPath('poses')
        if not os.path.exists(self.userDataPath):
            os.makedirs(self.userDataPath)
        self.paths = [self.userDataPath, self.sysDataPath]

        self.filechooser = self.addRightWidget(fc.IconListFileChooser(self.paths, ['bvh'], 'thumb', mh.getSysDataPath('poses/notfound.thumb'), name='Pose', noneItem=True))
        self.filechooser.setIconSize(50,50)
        self.filechooser.enableAutoRefresh(False)

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            gui3d.app.do(PoseAction("Change pose", self, self.currentPose, filename))

        self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
        self.addLeftWidget(self.filechooser.createTagFilter())

        self.skelObj = None
Exemplo n.º 2
0
    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'Material', label='Skin/Material')
        filecache.MetadataCacher.__init__(self, 'mhmat', 'material_filecache.mhc')
        self.cache_format_version = '1b'  # Override cache file version for materials, because we added metadata fields
        self.human = gui3d.app.selectedHuman

        self.materials = None

        self.filechooser = self.addRightWidget(fc.IconListFileChooser(self.materials, 'mhmat', ['thumb', 'png'], mh.getSysDataPath('skins/notfound.thumb'), name='Material'))
        self.filechooser.setIconSize(50,50)
        self.filechooser.enableAutoRefresh(False)
        #self.filechooser.setFileLoadHandler(fc.MhmatFileLoader())
        #self.addLeftWidget(self.filechooser.createSortBox())

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            mat = material.fromFile(filename)
            human = self.human

            obj = self.humanObjSelector.getSelectedObject()
            if obj:
                gui3d.app.do(MaterialAction(obj, mat))

        self.humanObjSelector = self.addLeftWidget(HumanObjectSelector(self.human))
        @self.humanObjSelector.mhEvent
        def onActivate(value):
            self.reloadMaterialChooser()

        self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
        self.addLeftWidget(self.filechooser.createTagFilter())
Exemplo n.º 3
0
    def createFileChooser(self):
        """
        Overwrite to do custom initialization of filechooser widget.
        """
        #self.filechooser = self.addTopWidget(fc.FileChooser(self.paths, 'mhclo', 'thumb', mh.getSysDataPath(proxyName+'/notfound.thumb')))
        notfoundIcon = self.getNotFoundIcon()
        if not os.path.isfile(notfoundIcon):
            notfoundIcon = getpath.getSysDataPath('notfound.thumb')

        if self.multiProxy:
            clearIcon = None
        else:
            clearIcon = self.getClearIcon()
            if not os.path.isfile(clearIcon):
                clearIcon = getpath.getSysDataPath('clear.thumb')

        self.filechooser = fc.IconListFileChooser(
            self.paths,
            self.getFileExtension(),
            'thumb',
            notfoundIcon,
            clearIcon,
            name=self.label,
            multiSelect=self.multiProxy,
            noneItem=not self.multiProxy,
            stickyTags=gui3d.app.getSetting('makehumanTags'))
        self.addRightWidget(self.filechooser)

        self.filechooser.setIconSize(50, 50)
        self.filechooser.enableAutoRefresh(False)
        if not isinstance(self.getFileExtension(), str) and \
           len(self.getFileExtension()) > 1:
            self.filechooser.mutexExtensions = True
        #self.addLeftWidget(self.filechooser.createSortBox())

        if self.tagFilter:
            self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
            self.addLeftWidget(self.filechooser.createTagFilter())

        if self.descriptionWidget:
            descBox = self.addLeftWidget(gui.GroupBox('Description'))
            self.descrLbl = descBox.addWidget(gui.TextView(''))
            self.descrLbl.setSizePolicy(gui.QtWidgets.QSizePolicy.Ignored,
                                        gui.QtWidgets.QSizePolicy.Preferred)
            self.descrLbl.setWordWrap(True)

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            self.proxyFileSelected(filename)

        if self.multiProxy:

            @self.filechooser.mhEvent
            def onFileDeselected(filename):
                self.proxyFileDeselected(filename)

            @self.filechooser.mhEvent
            def onDeselectAll(value):
                self.deselectAllProxies()
Exemplo n.º 4
0
    def onAssetTypeChange(self, item=None):

        assetType = str(item)

        self.FileChooser.hide()
        self.FileChooser2.hide()

        self.FileChooser.setFileLoadHandler(fc.TaggedFileLoader(self))

        del self.assetFolder[:]
        if assetType == "Materials":
            for type in ['clothes', 'hair', 'teeth', 'eyebrows', 'eyelashes']:
                if os.getenv('MH_ADVANCED', 0) == '1':
                    self.assetFolder += [
                        mhapi.locations.getSystemDataPath(type),
                        mhapi.locations.getUserDataPath(type)
                    ]
                else:
                    self.assetFolder += [mhapi.locations.getUserDataPath(type)]
                self.extensions = 'mhmat'
        elif assetType == "Models":
            self.assetFolder = [mhapi.locations.getUserHomePath('models')]
            self.extensions = "mhm"

        else:
            if os.getenv('MH_ADVANCED', 0) == '1':
                self.assetFolder = [
                    mhapi.locations.getSystemDataPath(assetType.lower()),
                    mhapi.locations.getUserDataPath(assetType.lower())
                ]
            else:
                self.assetFolder = [
                    mhapi.locations.getUserDataPath(assetType.lower())
                ]
            self.extensions = mhapi.assets.typeToExtension[assetType.lower()]

        self.selectedType = assetType
        self.TagFilter.clearAll()
        if assetType == "Models" or assetType == "Materials":
            self.FileChooser2.extensions = self.extensions
            self.FileChooser2.setPaths(self.assetFolder)
            self.FileChooser2.refresh()
            self.FileChooser2.show()
            self.TagFilter.setDisabled(True)
        else:
            self.FileChooser.extensions = self.extensions
            self.FileChooser.setPaths(self.assetFolder)
            self.FileChooser.refresh()
            self.FileChooser.show()
            self.TagFilter.setDisabled(False)
Exemplo n.º 5
0
    def createFileChooser(self):
        """
        Overwrite to do custom initialization of filechooser widget.
        """
        #self.filechooser = self.addTopWidget(fc.FileChooser(self.paths, 'mhclo', 'thumb', mh.getSysDataPath(proxyName+'/notfound.thumb')))
        notfoundIcon = self.getNotFoundIcon()
        if not os.path.isfile(notfoundIcon):
            notfoundIcon = getpath.getSysDataPath('notfound.thumb')

        if self.multiProxy:
            clearIcon = None
        else:
            clearIcon = self.getClearIcon()
            if not os.path.isfile(clearIcon):
                clearIcon = getpath.getSysDataPath('clear.thumb')

        self.filechooser = fc.IconListFileChooser(self.paths,
                                                  self.getFileExtension(),
                                                  'thumb',
                                                  notfoundIcon,
                                                  clearIcon,
                                                  name=self.label,
                                                  multiSelect=self.multiProxy,
                                                  noneItem=not self.multiProxy)
        self.addRightWidget(self.filechooser)

        self.filechooser.setIconSize(50, 50)
        self.filechooser.enableAutoRefresh(False)
        if not isinstance(self.getFileExtension(), basestring) and \
           len(self.getFileExtension()) > 1:
            self.filechooser.mutexExtensions = True
        #self.addLeftWidget(self.filechooser.createSortBox())

        if self.tagFilter:
            self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
            self.addLeftWidget(self.filechooser.createTagFilter())

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            self.proxyFileSelected(filename)

        if self.multiProxy:

            @self.filechooser.mhEvent
            def onFileDeselected(filename):
                self.proxyFileDeselected(filename)

            @self.filechooser.mhEvent
            def onDeselectAll(value):
                self.deselectAllProxies()
Exemplo n.º 6
0
    def __init__(self, category):

        gui3d.TaskView.__init__(self, category, 'Load')

        self.modelPath = None

        self.fileentry = self.addTopWidget(
            gui.FileEntryView(label='Select Folder:',
                              buttonLabel='Browse',
                              mode='dir'))
        self.fileentry.filter = 'MakeHuman Models (*.mhm)'

        # Declare new settings
        gui3d.app.addSetting('loaddir', mh.getPath("models"))

        @self.fileentry.mhEvent
        def onFileSelected(event):
            self.filechooser.setPaths([event.path])
            self.filechooser.refresh()
            # Remember load folder
            gui3d.app.setSetting('loaddir', formatPath(event.path))

        loadpath = gui3d.app.getSetting('loaddir')
        self.filechooser = fc.IconListFileChooser(
            loadpath,
            'mhm',
            'thumb',
            mh.getSysDataPath('notfound.thumb'),
            sort=HumanFileSort())
        filecache.MetadataCacher.__init__(self, ['mhm'],
                                          'models_filecache.mhc')
        self.addRightWidget(self.filechooser)
        self.addLeftWidget(self.filechooser.createSortBox())
        self.fileLoadHandler = fc.TaggedFileLoader(
            self, useNameTags=mh.getSetting('useNameTags'))
        self.filechooser.setFileLoadHandler(self.fileLoadHandler)
        self.addLeftWidget(self.filechooser.createTagFilter())

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            if gui3d.app.currentFile.modified:
                gui3d.app.prompt(
                    "Load",
                    "You have unsaved changes. Are you sure you want to close the current file?",
                    "Yes", "No", lambda: gui3d.app.loadHumanMHM(filename))
            else:
                gui3d.app.loadHumanMHM(filename)
Exemplo n.º 7
0
    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'Expressions')
        self.extension = 'mhpose'
        filecache.MetadataCacher.__init__(self, self.extension,
                                          'expression_filecache.mhc')

        self.human = gui3d.app.selectedHuman
        self.selectedFile = None
        self.selectedPose = None
        self.face_bone_idxs = None

        self.base_bvh = None
        self.base_anim = None

        self._setting_pose = False

        self.sysDataPath = getpath.getSysDataPath('expressions')
        self.userPath = getpath.getDataPath('expressions')
        self.paths = [self.userPath, self.sysDataPath]
        if not os.path.exists(self.userPath):
            os.makedirs(self.userPath)

        self.filechooser = self.addRightWidget(fc.IconListFileChooser( \
                                                    self.paths,
                                                    self.extension,
                                                    'thumb',
                                                    name='Expression',
                                                    notFoundImage = getpath.getSysDataPath('notfound.thumb'),
                                                    noneItem = True,
                                                    doNotRecurse = False,
                                                    stickyTags = gui3d.app.getSetting('makehumanTags')))
        self.filechooser.setIconSize(50, 50)
        self.filechooser.enableAutoRefresh(False)

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            if filename:
                msg = 'Load expression'
            else:
                msg = "Clear expression"
            gui3d.app.do(
                ExpressionAction(msg, self.selectedFile, filename, self))

        self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
        self.addLeftWidget(self.filechooser.createTagFilter())
Exemplo n.º 8
0
    def __init__(self, category):
        super(AssetEditorTaskView, self).__init__(category, 'Asset Editor')

        # Preset Variables here:
        self.notfound = mhapi.locations.getSystemDataPath("notfound.thumb")

        assetTypes = [
            "Clothes", "Hair", "Models", "Teeth", "Tongue", "Eyes"
            "Eyebrows", "Eyelashes", "ProxyMeshes", "Materials"
        ]


        saveMsg = "When you click the save button, the asset will be written back to the original file, " \
                  "but a .bak file will be created with the original data."

        tagWarnMsg = 'Your asset has to many tags. The Asset Editor does not support more than 5 tags. ' \
                     'Edit the asset in a Texteditor.'

        self.selectedType = None
        self.asset = None
        self.strip = None
        self.resetAsset = None

        # self.assetFolder = [mhapi.locations.getSystemDataPath('clothes'), mhapi.locations.getUserDataPath('clothes')]
        self.assetFolder = [mhapi.locations.getUserDataPath('clothes')]
        self.extensions = "mhclo"

        self.history_ptr = {
            'current': 0,
            'head': 0,
        }

        self.history = {}

        self.linekeys = ['author', 'name', 'uuid', 'homepage']
        self.textkeys = ['license', 'description']
        self.intkeys = [
            'z_depth',
            'max_pole',
        ]
        self.booleankeys = [
            'shadeless', 'wireframe', 'transparent', 'alphaToCoverage',
            'backfaceCull', 'depthless', 'castShadows', 'receiveShadows'
        ]
        self.texturekeys = [
            'diffuseTexture', 'bumpmapTexture', 'normalmapTexture',
            'displacementmapTexture', 'specularmapTexture',
            'transparencymapTexture', 'aomapTexture'
        ]
        self.floatkeys = [
            'diffuseIntensity', 'bumpMapIntensity', 'normalMapIntensity',
            'displacementMapIntensity', 'specularMapIntensity',
            'transparencyMapIntensity', 'aoMapIntensity', 'shininess',
            'opacity', 'translucency'
        ]
        self.rgbkeys = [
            'diffuseColor', 'specularColor', 'emissiveColor', 'ambientColor'
        ]
        self.num3keys = ['x_scale', 'y_scale', 'z_scale']

        self.baseDict = {k: None for k in mhapi.assets.keyList}

        self.loadedFile = ['', '']

        # Define LeftWidget content here:

        # The SaveBox:

        self.SaveBox = self.addLeftWidget(QGroupBox("Save asset: "))

        self.SaveInfo = gui.TextView(saveMsg)
        self.SaveInfo.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)
        self.SaveInfo.setWordWrap(True)

        self.SaveButton = defaultButton('Save')
        self.SaveButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        SaveBoxLayout = QVBoxLayout(self.SaveBox)
        SaveBoxLayout.addWidget(self.SaveInfo)
        SaveBoxLayout.addWidget(self.SaveButton, 0, Qt.AlignHCenter)

        self.SaveBox.setLayout(SaveBoxLayout)

        self.SaveButton.setDisabled(True)

        # The ThumbnailBox:

        self.ThumbnailBox = gui.GroupBox("Thumbnail (if any)")
        self.Thumbnail = self.ThumbnailBox.addWidget(gui.TextView())
        self.Thumbnail.setPixmap(QPixmap(os.path.abspath(self.notfound)))
        self.Thumbnail.setGeometry(0, 0, 128, 128)
        self.addLeftWidget(self.ThumbnailBox)

        # Define RightWidget content here:

        # The ClothesTypeBox:

        self.ClothesTypeBox = self.addRightWidget(
            gui.GroupBox('Select Asset Type'))
        self.typeList = mhapi.ui.createComboBox(assetTypes,
                                                self.onAssetTypeChange)
        self.ClothesTypeBox.addWidget(self.typeList)

        # The TagFielChoose:

        filecache.MetadataCacher.__init__(self, self.getFileExtension(),
                                          'plugin_filecache.mhc')

        self.FileChooser = self.addRightWidget(
            fc.IconListFileChooser(self.assetFolder,
                                   self.extensions,
                                   'thumb',
                                   self.notfound,
                                   None,
                                   name='File Chooser',
                                   noneItem=False))
        self.FileChooser.setIconSize(50, 50)
        self.FileChooser.enableAutoRefresh(True)
        self.FileChooser.setFileLoadHandler(fc.TaggedFileLoader(self))
        self.TagFilter = self.FileChooser.createTagFilter()
        self.addLeftWidget(self.TagFilter)
        fc2Path = mhapi.locations.getUserHomePath("models")
        self.FileChooser2 = self.addRightWidget(
            fc.IconListFileChooser(fc2Path,
                                   'mhm',
                                   'thumb',
                                   self.notfound,
                                   None,
                                   name='File Chooser',
                                   noneItem=False))
        self.FileChooser2.setIconSize(50, 50)
        self.FileChooser2.enableAutoRefresh(True)
        self.FileChooser2.hide()

        # Define MainPanel (TopWidget) content here:

        self.MainPanel = QWidget()
        MainPanelLayout = QVBoxLayout()
        self.addTopWidget(self.MainPanel)
        self.MainPanel.setLayout(MainPanelLayout)
        button = QTabWidget

        # The ButtonGroupBox
        self.ButtonGroupBox = QGroupBox()

        ButtonGroupLayout = QHBoxLayout(self.ButtonGroupBox)
        ButtonGroupLayout.addStretch(1)

        MainPanelLayout.addWidget(self.ButtonGroupBox)

        # The RedoButton
        self.RedoButton = defaultButton('Redo')
        self.RedoButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        ButtonGroupLayout.addWidget(self.RedoButton)
        self.RedoButton.setDisabled(True)

        # The UndoButton
        self.UndoButton = defaultButton('Undo')
        self.UndoButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        ButtonGroupLayout.addWidget(self.UndoButton)
        self.UndoButton.setDisabled(True)

        # The ResetButton
        self.ResetButton = defaultButton('Reset')
        self.ResetButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        ButtonGroupLayout.addWidget(self.ResetButton)
        self.ResetButton.setDisabled(True)

        # The UpdateButton
        self.UpdateButton = defaultButton('Update')
        self.UpdateButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        ButtonGroupLayout.addWidget(self.UpdateButton)
        self.ButtonGroupBox.setLayout(ButtonGroupLayout)

        # The TabWidget:
        self.TabWidget = QTabWidget()
        MainPanelLayout.addWidget(self.TabWidget)

        # The InfoPanel

        # The InfoPanel
        self.InfoPanel = QWidget()
        self.tabInfoIndex = self.TabWidget.addTab(self.InfoPanel,
                                                  'General Info')
        InfoPanelLayout = QVBoxLayout(self.InfoPanel)

        # The AssetInfoBox
        self.AssetInfoBox = QFrame()
        AssetInfoLayout = QVBoxLayout(self.AssetInfoBox)

        # The AssetInfoText
        self.AssetInfoText = gui.TextView('')
        self.BestPracticeText = gui.TextView('')
        self.BestPracticeText.setWordWrap(True)

        AssetInfoLayout.addWidget(self.AssetInfoText)
        AssetInfoLayout.addWidget(self.BestPracticeText)
        AssetInfoLayout.addStretch(1)

        self.AssetInfoBox.setLayout(AssetInfoLayout)

        self.ScrollArea = QScrollArea()
        self.ScrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.ScrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.ScrollArea.setWidgetResizable(True)
        self.ScrollArea.setWidget(self.AssetInfoBox)
        ScrollLayout = QVBoxLayout(self.ScrollArea)
        ScrollLayout.addWidget(self.AssetInfoBox)
        self.ScrollArea.setLayout(ScrollLayout)

        InfoPanelLayout.addWidget(self.ScrollArea)

        self.InfoPanel.setLayout(InfoPanelLayout)

        self.setAssetInfoText(self.asset)

        # Define EditorPanel (TopWidget) content here:

        #The EditPanel
        self.EditPanel = QWidget()
        self.tabEditIndex = self.TabWidget.addTab(self.EditPanel,
                                                  'Edit Common Data')

        EditPanelLayout = QVBoxLayout(self.EditPanel)
        self.EditPanel.setLayout(EditPanelLayout)

        # The CommonDataEditBox
        self.CommonDataEditBox = QGroupBox()
        CommonDataEditLayout = QHBoxLayout()

        EditPanelLayout.addWidget(self.CommonDataEditBox)

        # The LineEditGroupBox with
        self.LineEditGroupBox = QFrame()
        LineEditGroupLayout = QGridLayout()
        self.LineEditGroupBox.sizeHint = lambda: QSize(450, 325)
        self.LineEditGroupBox.setSizePolicy(QSizePolicy.Minimum,
                                            QSizePolicy.Minimum)

        AuthorLabel = LineEditGroupLayout.addWidget(QLabel('Author :'), 0, 0,
                                                    1, 1)
        NameLabel = LineEditGroupLayout.addWidget(QLabel('Name :'), 1, 0, 1, 1)
        TagsLabel = LineEditGroupLayout.addWidget(QLabel('Tags :'), 2, 0, 1, 1)

        self.baseDict['author'] = QLineEdit('')
        LineEditGroupLayout.addWidget(self.baseDict['author'], 0, 1, 1, 1)
        self.baseDict['name'] = QLineEdit('')
        LineEditGroupLayout.addWidget(self.baseDict['name'], 1, 1, 1, 1)

        # The TagGroupBox and ...
        self.TagGroupBox = QGroupBox()
        LineEditGroupLayout.addWidget(self.TagGroupBox, 2, 1, 1, 1)
        TagGroupLayout = QVBoxLayout()

        self.baseDict['tag'] = [QLineEdit('') for i in range(5)]
        for i in self.baseDict['tag']:
            TagGroupLayout.addWidget(i)
        TagGroupLayout.addStretch(1)
        self.TagGroupBox.setLayout(TagGroupLayout)
        self.TagWarn = QLabel(tagWarnMsg)
        self.TagWarn.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.TagWarn.setWordWrap(True)
        self.TagWarn.setGeometry(self.TagGroupBox.geometry())
        self.TagWarn.hide()
        LineEditGroupLayout.addWidget(self.TagWarn, 2, 1, 1, 1)

        self.LineEditGroupBox.setLayout(LineEditGroupLayout)

        HomePageLabel = LineEditGroupLayout.addWidget(QLabel('Homepage :'), 3,
                                                      0, 1, 1)
        self.UUIDButton = gui.Button('UUID')
        LineEditGroupLayout.addWidget(self.UUIDButton, 4, 0, 1, 1)
        self.baseDict['homepage'] = QLineEdit('')
        LineEditGroupLayout.addWidget(self.baseDict['homepage'], 3, 1, 1, 1)
        self.baseDict['uuid'] = QLineEdit()
        LineEditGroupLayout.addWidget(self.baseDict['uuid'], 4, 1, 1, 1)

        # The TextEditGroupBox
        self.TextEditGroupBox = QFrame()
        TextEditGroupLayout = QGridLayout()

        DescriptionLabel = TextEditGroupLayout.addWidget(
            QLabel('Description :'), 0, 0, 1, 1)
        LicenseLabel = TextEditGroupLayout.addWidget(QLabel('License :'), 1, 0,
                                                     1, 1)
        self.baseDict['description'] = QTextEdit()
        TextEditGroupLayout.addWidget(self.baseDict['description'], 0, 1, 1, 1)
        self.baseDict['license'] = QTextEdit()
        TextEditGroupLayout.addWidget(self.baseDict['license'], 1, 1, 1, 1)
        self.baseDict['description'].setLineWrapMode(QTextEdit.NoWrap)
        self.baseDict['license'].setLineWrapMode(QTextEdit.NoWrap)
        self.baseDict['description'].sizeHint = lambda: QSize(450, 125)
        self.baseDict['license'].sizeHint = lambda: QSize(450, 125)
        self.baseDict['description'].setSizePolicy(QSizePolicy.Maximum,
                                                   QSizePolicy.Maximum)
        self.baseDict['license'].setSizePolicy(QSizePolicy.Maximum,
                                               QSizePolicy.Maximum)

        self.TextEditGroupBox.setLayout(TextEditGroupLayout)

        CommonDataEditLayout.addWidget(self.LineEditGroupBox)
        CommonDataEditLayout.addWidget(self.TextEditGroupBox)
        self.CommonDataEditBox.setLayout(CommonDataEditLayout)

        # The asset-type dependent EditPanel:

        self.ClothesPanel = QGroupBox()
        ClothesLayout = QVBoxLayout()
        self.ClothesPanel.setLayout(ClothesLayout)

        self.CNumberPanel = QFrame()
        CNumberPanelLayout = QHBoxLayout()
        self.CNumberPanel.setLayout(CNumberPanelLayout)

        self.scalePanel = QFrame()
        scalePanelLayout = QGridLayout()
        self.scalePanel.setLayout(scalePanelLayout)

        self.objPanel = QFrame()
        objPanelLayout = QHBoxLayout()
        self.objPanel.setLayout(objPanelLayout)

        self.CMaterialPanel = QFrame()
        CMaterialPanelLayout = QHBoxLayout()
        self.CMaterialPanel.setLayout(CMaterialPanelLayout)

        zdepthLabel = QLabel('Z-Depth :')
        self.baseDict['z_depth'] = QLineEdit()
        self.baseDict['z_depth'].sizeHint = lambda: QSize(40, 30)
        self.baseDict['z_depth'].setSizePolicy(QSizePolicy.Maximum,
                                               QSizePolicy.Maximum)
        self.zDepthSelect = mhapi.ui.createComboBox(
            sorted(zDepth, key=zDepth.__getitem__), self.onzDepthSelect)
        self.zDepthSelect.setSizePolicy(QSizePolicy.Maximum,
                                        QSizePolicy.Maximum)
        maxpoleLabel = QLabel('  max pole :')
        self.baseDict['max_pole'] = QLineEdit()
        self.baseDict['max_pole'].sizeHint = lambda: QSize(40, 30)
        self.baseDict['max_pole'].setSizePolicy(QSizePolicy.Maximum,
                                                QSizePolicy.Maximum)
        x_scaleLabel = QLabel('x_scale:')
        self.baseDict['x_scale'] = [QLineEdit(), QLineEdit(), QLineEdit()]
        y_scaleLabel = QLabel('y_scale:')
        self.baseDict['y_scale'] = [QLineEdit(), QLineEdit(), QLineEdit()]
        z_scaleLabel = QLabel('z_scale:')
        self.baseDict['z_scale'] = [QLineEdit(), QLineEdit(), QLineEdit()]
        objLabel = QLabel('Set Object File :')
        self.baseDict['obj_file'] = QLineEdit()
        self.objButton = gui.Button('[ ... ]')
        self.objButton.sizeHint = lambda: QSize(40, 30)
        self.objButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.objRelPathButton = gui.Button('To rel. Path...')
        self.objRelPathButton.sizeHint = lambda: QSize(90, 30)
        self.objRelPathButton.setSizePolicy(QSizePolicy.Fixed,
                                            QSizePolicy.Fixed)
        materialLabel = QLabel('Set Default Material :')
        self.baseDict['material'] = QLineEdit()
        self.MaterialButton = gui.Button('[ ... ]')
        self.MaterialButton.sizeHint = lambda: QSize(40, 30)
        self.MaterialButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.RelPathButton = gui.Button('To rel. Path...')
        self.RelPathButton.sizeHint = lambda: QSize(90, 30)
        self.RelPathButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        CNumberPanelLayout.addWidget(zdepthLabel)
        CNumberPanelLayout.addWidget(self.baseDict['z_depth'])
        CNumberPanelLayout.addWidget(self.zDepthSelect)
        CNumberPanelLayout.addWidget(maxpoleLabel)
        CNumberPanelLayout.addWidget(self.baseDict['max_pole'])
        CNumberPanelLayout.addStretch(1)

        scalePanelLayout.addWidget(x_scaleLabel, 0, 0, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['x_scale'][0], 0, 1, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['x_scale'][1], 0, 2, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['x_scale'][2], 0, 3, 1, 1)
        scalePanelLayout.addWidget(y_scaleLabel, 1, 0, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['y_scale'][0], 1, 1, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['y_scale'][1], 1, 2, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['y_scale'][2], 1, 3, 1, 1)
        scalePanelLayout.addWidget(z_scaleLabel, 2, 0, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['z_scale'][0], 2, 1, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['z_scale'][1], 2, 2, 1, 1)
        scalePanelLayout.addWidget(self.baseDict['z_scale'][2], 2, 3, 1, 1)
        scalePanelLayout.setColumnStretch(4, 75)

        objPanelLayout.addWidget(objLabel)
        objPanelLayout.addWidget(self.baseDict['obj_file'])
        objPanelLayout.addWidget(self.objButton)
        objPanelLayout.addWidget(self.objRelPathButton)

        CMaterialPanelLayout.addWidget(materialLabel)
        CMaterialPanelLayout.addWidget(self.baseDict['material'])
        CMaterialPanelLayout.addWidget(self.MaterialButton)
        CMaterialPanelLayout.addWidget(self.RelPathButton)

        ClothesLayout.addWidget(self.CNumberPanel)
        ClothesLayout.addWidget(self.scalePanel)
        ClothesLayout.addWidget(self.objPanel)
        ClothesLayout.addWidget(self.CMaterialPanel)

        EditPanelLayout.addWidget(self.ClothesPanel)
        EditPanelLayout.addStretch(1)

        # Advanced Panel

        self.AdvancedPanel = QFrame()
        AdvancedPanelLayout = QVBoxLayout()
        self.AdvancedPanel.setLayout(AdvancedPanelLayout)

        self.subFrame1 = QFrame()
        subFrame1Layout = QHBoxLayout()
        self.subFrame1.setLayout(subFrame1Layout)
        AdvancedPanelLayout.addWidget(self.subFrame1)

        self.bkPanel = QGroupBox()
        bkPanelLayout = QGridLayout()
        self.bkPanel.setLayout(bkPanelLayout)
        self.bkPanel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)

        #for i in range(3):
        #    bkPanelLayout.addWidget(QLabel(' Y   |   N  '), 0, i*2 + 1, 1, 1)
        i = 0
        for key in self.booleankeys:
            bkLabel = {i: [QLabel(key.capitalize()), QFrame(), QHBoxLayout()]}
            bkLabel[i][1].setLayout(bkLabel[i][2])
            self.baseDict[key] = [QRadioButton(': Y'), QRadioButton(': N')]
            bkLabel[i][2].addWidget(self.baseDict[key][0])
            bkLabel[i][2].addWidget(self.baseDict[key][1])
            bkLabel[i][2].addStretch(1)
            #bkPanelLayout.addWidget(bkLabel[i][1], (i // 3) + 1, (i % 3) * 2 + 1, 1, 1)
            #bkPanelLayout.addWidget(bkLabel[i][0], (i // 3) + 1, (i % 3) * 2, 1, 1)
            bkPanelLayout.addWidget(bkLabel[i][0], i, 0, 1, 1)
            bkPanelLayout.addWidget(bkLabel[i][1], i, 1, 1, 1)
            i += 1

        self.TexturesPanel = QGroupBox()
        TexturesPanelLayout = QGridLayout()
        self.TexturesPanel.setLayout(TexturesPanelLayout)
        subFrame1Layout.addWidget(self.TexturesPanel)

        subFrame1Layout.addWidget(self.bkPanel)

        i = 0
        for key in self.texturekeys:
            lineEdit = QLineEdit()
            self.baseDict[key] = lineEdit
            texturesPLabel = {
                i: [
                    QLabel(key.capitalize()),
                    QLabel(' : '), lineEdit,
                    defaultButton('[ ... ]', 40, 30),
                    defaultButton('To rel. Path...', 90, 30)
                ]
            }
            texturesPLabel[i][3].setSizePolicy(QSizePolicy.Fixed,
                                               QSizePolicy.Fixed)
            texturesPLabel[i][3].setObjectName(key)
            texturesPLabel[i][3].clicked.connect(self.onLoadTexture)
            texturesPLabel[i][4].setSizePolicy(QSizePolicy.Fixed,
                                               QSizePolicy.Fixed)
            texturesPLabel[i][4].setObjectName(key)
            texturesPLabel[i][4].clicked.connect(self.onRelTexturePathClicked)

            h = 0
            for widget in texturesPLabel[i]:
                # TexturesPanelLayout.addWidget(widget, i // 2, h + (i % 2) * 5, 1, 1)
                TexturesPanelLayout.addWidget(widget, i, h, 1, 1)
                h += 1
            i += 1

        self.subFrame2 = QFrame()
        subFrame2Layout = QHBoxLayout()
        self.subFrame2.setLayout(subFrame2Layout)
        AdvancedPanelLayout.addWidget(self.subFrame2)

        self.floatsPanel = QGroupBox()
        floatsPanelLayout = QGridLayout()
        self.floatsPanel.setLayout(floatsPanelLayout)
        subFrame2Layout.addWidget(self.floatsPanel)

        i = 0
        for key in self.floatkeys:
            self.baseDict[key] = QLineEdit()
            floatsPLabel = {
                i:
                [QLabel(key.capitalize()),
                 QLabel(' : '), self.baseDict[key]]
            }
            h = 0
            for widget in floatsPLabel[i]:
                # floatsPanelLayout.addWidget(widget, i // 2, h + (i % 2) * 3, 1, 1)
                floatsPanelLayout.addWidget(widget, i, h, 1, 1)
                h += 1
            i += 1

        self.rgbPanel = QGroupBox()
        rgbPanelLayout = QGridLayout()
        self.rgbPanel.setLayout(rgbPanelLayout)
        subFrame2Layout.addWidget(self.rgbPanel)

        i = 0
        for key in self.rgbkeys:
            self.baseDict[key] = [QLineEdit(), QLineEdit(), QLineEdit()]
            ed1, ed2, ed3 = self.baseDict[key]
            rgbPLabel = {
                i: [QLabel(key.capitalize()),
                    QLabel(' : '), ed1, ed2, ed3]
            }
            h = 0
            for widget in rgbPLabel[i]:
                # rgbPanelLayout.addWidget(widget, i // 2, h + (i % 2) * 5, 1, 1)
                rgbPanelLayout.addWidget(widget, i, h, 1, 1)
                h += 1
            i += 1

        self.ScrollArea2 = QScrollArea()
        self.ScrollArea2.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.ScrollArea2.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.ScrollArea2.setWidgetResizable(True)
        self.ScrollArea2.setWidget(self.AdvancedPanel)
        ScrollLayout2 = QVBoxLayout()
        ScrollLayout2.addWidget(self.AdvancedPanel)
        self.ScrollArea2.setLayout(ScrollLayout2)
        self.tabAdvancedIndex = self.TabWidget.addTab(
            self.ScrollArea2, 'Advanced Materials Data')

        self.TabWidget.setTabEnabled(self.tabEditIndex, False)
        self.TabWidget.setTabEnabled(self.tabAdvancedIndex, False)

        # Define Actions here:

        @self.RedoButton.mhEvent
        def onClicked(event):
            if self.history_ptr['current'] < self.history_ptr['head']:
                self.history[self.history_ptr['current']] = {
                    k: self.asset[k]
                    for k in self.asset.keys()
                }
                self.asset.clear()
                self.history_ptr['current'] += 1
                self.asset = {
                    k: self.history[self.history_ptr['current']][k]
                    for k in self.history[self.history_ptr['current']].keys()
                }
                self.setAssetInfoText(self.asset)
                self.UndoButton.setDisabled(False)
            if self.history_ptr['current'] == self.history_ptr['head']:
                self.RedoButton.setDisabled(True)
            self.setEditData()

        @self.UndoButton.mhEvent
        def onClicked(event):
            if self.history_ptr['current'] > 0:
                self.history[self.history_ptr['current']] = {
                    k: self.asset[k]
                    for k in self.asset.keys()
                }
                self.asset.clear()
                self.history_ptr['current'] -= 1
                self.asset = {
                    k: self.history[self.history_ptr['current']][k]
                    for k in self.history[self.history_ptr['current']].keys()
                }
                self.setAssetInfoText(self.asset)
                self.RedoButton.setDisabled(False)
            if self.history_ptr['current'] == 0:
                self.UndoButton.setDisabled(True)
            self.setEditData()

        @self.UpdateButton.mhEvent
        def onClicked(event):
            self.isUpdate = True
            self.history[self.history_ptr['current']] = {
                key: self.asset[key]
                for key in self.asset.keys()
            }
            self.history_ptr['current'] += 1
            self.history_ptr['head'] = self.history_ptr['current']

            self.UndoButton.setDisabled(False)
            self.SaveButton.setDisabled(False)
            self.ClothesTypeBox.setDisabled(False)
            self.ResetButton.setDisabled(False)

            if not self.tagWarn:
                taglist = []
                for lineEdit in self.baseDict['tag']:
                    if lineEdit.text().strip() != '':
                        taglist.append(lineEdit.text().strip())
                self.asset['tag'] = set(taglist)

            if not self.selectedType in ['Materials', 'Models']:
                self.asset['obj_file'] = self.baseDict['obj_file'].text()
                self.asset['material'] = self.baseDict['material'].text()
                for key in ['x_scale', 'y_scale', 'z_scale']:
                    self.asset[key] = self.getDigitStr(self.baseDict[key][0].text()) + ' ' + \
                                      self.getDigitStr(self.baseDict[key][1].text()) + ' ' + \
                                      self.getFloatStr(self.baseDict[key][2].text())
                    if self.asset[key].strip() == '': self.asset[key] = None

            for key in self.linekeys:
                self.asset[key] = self.baseDict[key].text()
            for key in self.textkeys:
                self.asset[key] = self.baseDict[key].toPlainText()
            if not (self.selectedType == 'Models'
                    or self.selectedType == 'Materials'):
                for key in self.intkeys:
                    self.asset[key] = self.getDigitStr(
                        self.baseDict[key].text())
            if self.selectedType == 'Materials':
                for key in self.booleankeys:
                    self.asset[key] = 'True' if self.baseDict[key][
                        0].isChecked() else 'False'
                for key in self.texturekeys:
                    self.asset[key] = self.baseDict[key].text()
                for key in self.floatkeys:
                    self.asset[key] = self.getFloatStr(
                        self.baseDict[key].text())
                for key in self.rgbkeys:
                    self.asset[key] = self.getDigitStr(self.baseDict[key][0].text()) + ' ' + \
                                      self.getDigitStr(self.baseDict[key][1].text()) + ' ' + \
                                      self.getFloatStr(self.baseDict[key][2].text())
                    if self.asset[key].strip() == '': self.asset[key] = None

            self.setAssetInfoText(self.asset)

        @self.ResetButton.mhEvent
        def onClicked(event):
            self.asset, self.strip = self.splitAssetDict(self.resetAsset)
            self.setAssetInfoText(self.asset)
            self.ResetButton.setDisabled(True)
            self.history.clear()
            self.history_ptr = {'head': 0, 'current': 0}
            self.UndoButton.setDisabled(True)
            self.RedoButton.setDisabled(True)
            self.SaveButton.setDisabled(True)
            self.setEditData()

        @self.SaveButton.mhEvent
        def onClicked(event):
            saveAsset = self.joinDict(self.asset, self.strip)
            if saveAsset:
                mhapi.assets.writeAssetFile(saveAsset, True)
                self.showMessage("Asset was saved as " +
                                 saveAsset["absolute path"] +
                                 "\n\nA backup file was created in " +
                                 saveAsset["absolute path"] + ".bak")

        @self.UUIDButton.mhEvent
        def onClicked(event):
            self.baseDict['uuid'].setText(uuid.uuid4())

        @self.FileChooser.mhEvent
        def onFileSelected(filename):
            self.loadedFile = os.path.split(filename)
            assetInfo = mhapi.assets.openAssetFile(filename)
            if assetInfo["thumb_path"]:
                self.Thumbnail.setPixmap(QPixmap(assetInfo["thumb_path"]))
            else:
                self.Thumbnail.setPixmap(QPixmap(self.notfound))
            self.Thumbnail.setGeometry(0, 0, 128, 128)
            self.resetAsset = assetInfo
            self.asset, self.strip = self.splitAssetDict(self.resetAsset)
            self.setAssetInfoText(self.asset)
            self.tagWarn = False
            self.history.clear()
            self.history_ptr = {'head': 0, 'current': 0}
            self.setEditData()
            self.UndoButton.setDisabled(True)
            self.RedoButton.setDisabled(True)
            self.ResetButton.setDisabled(True)
            self.TabWidget.setTabEnabled(self.tabEditIndex, True)
            self.TabWidget.setTabEnabled(self.tabAdvancedIndex, False)

        @self.FileChooser2.mhEvent
        def onFileSelected(filename):
            self.loadedFile = os.path.split(filename)
            assetInfo = mhapi.assets.openAssetFile(filename)
            if assetInfo["thumb_path"]:
                self.Thumbnail.setPixmap(QPixmap(assetInfo["thumb_path"]))
            else:
                self.Thumbnail.setPixmap(QPixmap(self.notfound))
            self.Thumbnail.setGeometry(0, 0, 128, 128)
            self.resetAsset = assetInfo
            self.asset, self.strip = self.splitAssetDict(self.resetAsset)
            self.setAssetInfoText(self.asset)
            self.isUpdate = False
            self.tagWarn = False
            self.history.clear()
            self.history_ptr = {'head': 0, 'current': 0}
            self.setAssetInfoText(self.asset)
            self.setEditData()
            self.UndoButton.setDisabled(True)
            self.RedoButton.setDisabled(True)
            self.ResetButton.setDisabled(True)
            self.TabWidget.setTabEnabled(self.tabEditIndex, True)
            if self.selectedType == 'Materials':
                self.TabWidget.setTabEnabled(self.tabAdvancedIndex, True)
            else:
                self.TabWidget.setTabEnabled(self.tabAdvancedIndex, False)

        @self.MaterialButton.mhEvent
        def onClicked(event):
            selectedFile = None
            FDialog = QFileDialog(None, '', self.loadedFile[0])
            FDialog.setFileMode(QFileDialog.ExistingFiles)
            FDialog.setFilter(
                'MakeHuman Material ( *.mhmat );; All files ( *.* )')
            if FDialog.exec_():
                selectedFile = FDialog.selectedFiles()[0]
            if selectedFile:
                materialFile = os.path.split(selectedFile)
                if materialFile[0] == self.loadedFile[0]:
                    self.baseDict['material'].setText(materialFile[1])
                else:
                    self.baseDict['material'].setText(selectedFile)

        @self.RelPathButton.mhEvent
        def onClicked(event):
            filepath, filename = os.path.split(
                self.baseDict['material'].text())
            if os.path.isfile(filepath + '/' + filename):
                rel_path = makeRelPath(filepath, self.loadedFile[0])
                if rel_path:
                    self.baseDict['material'].setText(rel_path + filename)
                else:
                    self.baseDict['material'].setText('Failure')
            else:
                self.baseDict['material'].setText('File not found')

        @self.objButton.mhEvent
        def onClicked(event):
            selectedFile = None
            FDialog = QFileDialog(None, '', self.loadedFile[0])
            FDialog.setFileMode(QFileDialog.ExistingFiles)
            FDialog.setFilter('Object Files ( *.obj );; All files ( *.* )')
            if FDialog.exec_():
                selectedFile = FDialog.selectedFiles()[0]
            if selectedFile:
                objFile = os.path.split(selectedFile)
                if objFile[0] == self.loadedFile[0]:
                    self.baseDict['obj_file'].setText(objFile[1])
                else:
                    self.baseDict['obj_file'].setText(selectedFile)

        @self.objRelPathButton.mhEvent
        def onClicked(event):
            filepath, filename = os.path.split(
                self.baseDict['obj_file'].text())
            if os.path.isfile(filepath + '/' + filename):
                rel_path = makeRelPath(filepath, self.loadedFile[0])
                if rel_path:
                    self.baseDict['obj_file'].setText(rel_path + filename)
                else:
                    self.baseDict['obj_file'].setText('Failure')
            else:
                self.baseDict['obj_file'].setText('File not found')
Exemplo n.º 9
0
    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'Skeleton')
        filecache.MetadataCacher.__init__(self, 'mhskel',
                                          'skeleton_filecache.mhc')

        self.human = gui3d.app.selectedHuman

        self.referenceRig = None

        self.selectedRig = None

        self.skelMesh = None
        self.skelObj = None

        self.jointsMesh = None
        self.jointsObj = None

        self.selectedJoint = None

        self.oldHumanMat = self.human.material
        self.oldPxyMats = dict()

        self.sysDataPath = getpath.getSysDataPath('rigs')
        self.userDataPath = getpath.getDataPath('rigs')
        if not os.path.exists(self.userDataPath):
            os.makedirs(self.userDataPath)
        self.paths = [self.userDataPath, self.sysDataPath]

        self.filechooser = self.addRightWidget(fc.IconListFileChooser( \
                                                    self.paths,
                                                    'mhskel',
                                                    'thumb',
                                                    name='Rig presets',
                                                    notFoundImage = mh.getSysDataPath('notfound.thumb'),
                                                    noneItem = True,
                                                    doNotRecurse = True))
        self.filechooser.setIconSize(50, 50)
        self.filechooser.enableAutoRefresh(False)

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            if filename:
                msg = "Change skeleton"
            else:
                msg = "Clear skeleton"
            gui3d.app.do(SkeletonAction(msg, self, self.selectedRig, filename))

        self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
        self.addLeftWidget(self.filechooser.createTagFilter())

        self.infoBox = self.addLeftWidget(gui.GroupBox('Rig info'))
        self.boneCountLbl = self.infoBox.addWidget(gui.TextView('Bones: '))
        self.infoBox.setSizePolicy(gui.QtGui.QSizePolicy.Preferred,
                                   gui.QtGui.QSizePolicy.Maximum)

        descBox = self.addLeftWidget(gui.GroupBox('Description'))
        self.descrLbl = descBox.addWidget(gui.TextView(''))
        self.descrLbl.setSizePolicy(gui.QtGui.QSizePolicy.Ignored,
                                    gui.QtGui.QSizePolicy.Preferred)
        self.descrLbl.setWordWrap(True)

        self.xray_mat = None

        # the reference skeleton
        self.referenceRig = self.human.getBaseSkeleton()
Exemplo n.º 10
0
    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'Skeleton')
        filecache.MetadataCacher.__init__(self, 'mhskel', 'skeleton_filecache.mhc')
        self.optionsSelector = None

        self.systemRigs = mh.getSysDataPath('rigs')
        self.userRigs = os.path.join(mh.getPath(''), 'data', 'rigs')
        self.rigPaths = [self.userRigs, self.systemRigs]
        if not os.path.exists(self.userRigs):
            os.makedirs(self.userRigs)

        self.human = gui3d.app.selectedHuman

        self.referenceRig = None

        self.selectedRig = None

        self.humanChanged = False   # Used for determining when joints need to be redrawn

        self.skelMesh = None
        self.skelObj = None

        self.jointsMesh = None
        self.jointsObj = None

        self.selectedJoint = None

        self.oldHumanMat = self.human.material
        self.oldPxyMats = dict()

        #
        #   Display box
        #

        '''
        self.displayBox = self.addLeftWidget(gui.GroupBox('Display'))
        self.showHumanTggl = self.displayBox.addWidget(gui.CheckBox("Show human"))
        @self.showHumanTggl.mhEvent
        def onClicked(event):
            if self.showHumanTggl.selected:
                self.human.show()
            else:
                self.human.hide()
        self.showHumanTggl.setSelected(True)

        self.showJointsTggl = self.displayBox.addWidget(gui.CheckBox("Show joints"))
        @self.showJointsTggl.mhEvent
        def onClicked(event):
            if not self.jointsObj:
                return
            if self.showJointsTggl.selected:
                self.jointsObj.show()
            else:
                self.jointsObj.hide()
        self.showJointsTggl.setSelected(True)
        '''

        self.sysDataPath = getpath.getSysDataPath('rigs')
        self.userDataPath = getpath.getDataPath('rigs')
        if not os.path.exists(self.userDataPath):
            os.makedirs(self.userDataPath)
        self.paths = [self.userDataPath, self.sysDataPath]

        #
        #   Preset box
        #

        self.filechooser = self.addRightWidget(fc.IconListFileChooser( \
                                                    self.paths,
                                                    'mhskel',
                                                    'thumb',
                                                    name='Rig presets',
                                                    notFoundImage = mh.getSysDataPath('notfound.thumb'), 
                                                    noneItem = True, 
                                                    doNotRecurse = True))
        self.filechooser.setIconSize(50,50)
        self.filechooser.enableAutoRefresh(False)

        @self.filechooser.mhEvent
        def onFileSelected(filename):
            if filename:
                msg = "Change skeleton"
            else:
                msg = "Clear skeleton"
            gui3d.app.do(SkeletonAction(msg, self, self.selectedRig, filename))

        self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
        self.addLeftWidget(self.filechooser.createTagFilter())

        self.infoBox = self.addLeftWidget(gui.GroupBox('Rig info'))
        self.boneCountLbl = self.infoBox.addWidget(gui.TextView('Bones: '))
        self.infoBox.setSizePolicy(gui.QtGui.QSizePolicy.Preferred, gui.QtGui.QSizePolicy.Maximum)

        descBox = self.addLeftWidget(gui.GroupBox('Description'))
        self.descrLbl = descBox.addWidget(gui.TextView(''))
        self.descrLbl.setSizePolicy(gui.QtGui.QSizePolicy.Ignored, gui.QtGui.QSizePolicy.Preferred)
        self.descrLbl.setWordWrap(True)

        self.xray_mat = None

        # the reference skeleton
        self.referenceRig = self.human.getBaseSkeleton()
Exemplo n.º 11
0
    def __init__(self, category):
        gui3d.TaskView.__init__(self, category, 'AutoPose')
        #super(PoseLibraryAotu1TaskView, self).__init__(category, 'clothes', multiProxy = True, tagFilter = True)
        filecache.MetadataCacher.__init__(self, ['bvh'], 'pose_filecache.mhc')
        self.cache_format_version = '1c'  # Bump cacher version for updated format of pose metadata
        box1 = self.addLeftWidget(gui.GroupBox('ImageMatch'))
        self.aButtonC1 = box1.addWidget(gui.Button('L.UpArm'))
        self.aButtonC2 = box1.addWidget(gui.Button('L.LowArm'))
        self.aButtonC3 = box1.addWidget(gui.Button('R.UpArm'))
        self.aButtonC4= box1.addWidget(gui.Button('R.LowArm'))
        self.aButtonC5 = box1.addWidget(gui.Button('L.UpLeg'))
        self.aButtonC6 = box1.addWidget(gui.Button('L.LowLeg'))
        self.aButtonC7 = box1.addWidget(gui.Button('R.UpLeg'))
        self.aButtonC8 = box1.addWidget(gui.Button('R.LowLeg'))
        box = self.addLeftWidget(gui.GroupBox('AngleRotate'))
        self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5'))
        self.InitButton = box.addWidget(gui.Button('Init Pose'))
        @self.InitButton.mhEvent
        def onClicked(event):
            chushihua()
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            #gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepath1))
            #anim = self.loadBvh(fileout, convertFromZUp="auto")                          
            log.message("Init Pose.")
        self.aButton = box.addWidget(gui.Button('BVH'))        
      #  self.aButton1 = box.addWidget(gui.Button('Save RGBImage'))
        self.aButton2 = box.addWidget(gui.Button('Save Image'))
        #self.aButton3 = box.addWidget(gui.Button('AotuPoseImage'))
        self.aSliderLabel = box.addWidget(gui.TextView('****************************'))
        a1=[0]
        a2=[0]
        a3=[0]
        a4=[0]
        a5=[0] 
        a6=[0]
        a7=[0]
        a8=[0]
        deltvalue1=[100]
        deltvalue2=[100]
        deltvalue3=[100]
        deltvalue4=[100]
        deltvalue5=[100]
        deltvalue6=[100]
        deltvalue7=[100]
        deltvalue8=[100]
        deltva1=[0]
        deltva2=[0]
        deltva3=[0]
        deltva4=[0]
        deltva5=[0]
        deltva6=[0]
        deltva7=[0]
        deltva8=[0]
        self.aSlider = box.addWidget(gui.Slider(value=0.5, label=['upperarm01.L',' %.3f']))   
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.5)*100)
            a1[0]=(value-0.5)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto")

        log.message(str(a1[0]))    
        self.aSlider= box.addWidget(gui.Slider(value=0.5, label=['lowerarm01.L',' %.3f']))
       # self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5'))
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.5)*100)
            #global a2
            a2[0]=(value-0.5)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto") 
            #return a2

       # laL=onChange()
        self.aSlider= box.addWidget(gui.Slider(value=0.5, label=['upperarm01.R',' %.3f']))
      #  self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5'))  
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.5)*100)
            #global a3
            a3[0]=(value-0.5)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto") 
            #return a3

       # ulL=onChange(value)
        self.aSlider = box.addWidget(gui.Slider(value=0.5, label=['lowerarm01.R',' %.3f']))
        #self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5'))  
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.5)*100)
           # global a4
            a4[0]=(value-0.5)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto") 
            #return a4
        
       # llL=onChange(value)
        self.aSlider = box.addWidget(gui.Slider(value=0.5, label=['upperleg01.L',' %.3f']))
       # self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5'))  
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.5)*100)
            #global a5
            a5[0]=(value-0.5)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto") 
            #return a5
         
        #uaR=onChange(value)
        self.aSlider = box.addWidget(gui.Slider(value=0.0, label=['lowerleg01.L',' %.3f']))
       # self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5')) 
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.0)*100)
           # global a6
            a6[0]=(value-0.0)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto") 
            #return a6
        
        #laR=onChange(value)
        self.aSlider = box.addWidget(gui.Slider(value=0.5, label=['upperleg01.R',' %.3f']))
      #  self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5'))  
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.5)*100)
           # global a7
            a7[0]=(value-0.5)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto") 
           # return a7;  

        #ulR=onChange(value)
        self.aSlider = box.addWidget(gui.Slider(value=0.0, label=['lowerleg01.R',' %.3f']))
       # self.aSliderLabel = box.addWidget(gui.TextView('Value is initialize=0.5'))   
        @self.aSlider.mhEvent
        def onChange(value):
            self.aSliderLabel.setTextFormat('AngleRotate is %.1f', (value-0.0)*100)
           # global a8
            a8[0]=(value-0.0)*100
            bvhanniu()
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
            anim = self.loadBvh(fileout, convertFromZUp="auto") 
            #return a8

        #llR=onChange(value)
        # We make the first one selected
        self.human = G.app.selectedHuman
        self.currentPose = None

        self.paths = [mh.getDataPath('Mydata'), mh.getSysDataPath('Mydata')]

        self.filechooser = self.addRightWidget(fc.IconListFileChooser(self.paths, ['bvh'], 'thumb', mh.getSysDataPath('poses/notfound.thumb'), name='Pose', noneItem=True))
        self.filechooser.setIconSize(50,50)
        self.filechooser.enableAutoRefresh(False)
        #filepath0=[str(0)]
        @self.filechooser.mhEvent
        def onFileSelected(filename):
            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filename))
            if not filename:
                self.human.resetToRestPose()

            else:
                anim = self.loadBvh(filename, convertFromZUp="auto") 


        self.filechooser.setFileLoadHandler(fc.TaggedFileLoader(self))
        self.addLeftWidget(self.filechooser.createTagFilter())
        log.message(self.paths)
        self.skelObj = None
        #filepath1=self.paths+'\\ORIGINAL MODEL.bvh'
        #filepath1=filepath0[0]
        fp = open(filepath1, "rU")
        bvh1=bvh.BVH()
        bvh2=bvh1._BVH__expectKeyword('HIERARCHY', fp)
        words = bvh1._BVH__expectKeyword('ROOT', fp)
        rootJoint = bvh1.addRootJoint(words[1])        
        bvh1._BVH__readJoint(bvh1.rootJoint, fp)
        self.convertFromZUp = bvh1._autoGuessCoordinateSystem()
        log.message("Automatically guessed coordinate system for BVH file %s (%s)" % (filepath1, "Z-up" if self.convertFromZUp else "Y-up"))
        if self.convertFromZUp:
            # Conversion needed: convert from Z-up to Y-up
            bvh1._BVH__cacheGetJoints()
            for joint in bvh1.jointslist:
                bvh1._BVH__calcPosition(joint, joint.offset)

        # Read motion
        bvh1._BVH__expectKeyword('MOTION', fp)
        words = bvh1._BVH__expectKeyword('Frames:', fp)
        self.frameCount = int(words[1])
        words = bvh1._BVH__expectKeyword('Frame', fp) # Time:
        self.frameTime = float(words[2])

        for i in range(self.frameCount):
            line = fp.readline()
            words = line.split()
            data = [float(word) for word in words]
            if i!=43:
                for joint in bvh1.getJointsBVHOrder():
                    data = bvh1._BVH__processChannelData(joint, data)

            else:
                data=int(90)


        bvh1._BVH__cacheGetJoints()
        bvh1.frameCount=self.frameCount
        # Transform frame data into transformation matrices for all joints
        for joint in bvh1.getJoints():
            joint.calculateFrames()  
        
     
     
        @self.aButtonC1.mhEvent
        def onClicked(event):
            chushihua()
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            
            OrigalIm = cv2.imread(filepicture) #先读目标图像
            for value in range(0,101,20):
                a1[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                anim = self.loadBvh(fileout, convertFromZUp="auto")
                #cv2.waitKey(10)
                #filenameImage=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameImage=fileResult+str(a1[0])+'DegreeLarm.png'
                #filenameIma=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma=fileResult+str(a1[0])+'DegreeLarm.png'
                width = G.windowWidth;
                height = G.windowHeight;
                
                Xdel=600   #原图为800x600  减除后为200x150
                Ydel=450
                width = width - Xdel;
                height = height - Ydel;
                #log.message(filenameImage)
                #mh.grabScreen(300,225,width,height,filenameImage)  #存盘
                
                mh.grabScreen(Xdel/2,Ydel/2,width,height,filenameImage)  #不存盘,全在内在操作,提高速度
                log.message("Saved screengrab to %s", filenameImage)
           
                img=cv2.imread(filenameImage)  #存盘
                height1,width1=img.shape[:2]
                #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]

                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                #cv2.imshow("img",imsave)
                #cv2.waitKey(10)
                #delt1=findcontours.GetDeltValue(imsave,OrigalIm)  #onpicture()                
                delt1=findcontours.CalDiff(imsave,OrigalIm)
                log.debug('delt1 (%d Degree): = %f', a1[0], delt1)                
                if delt1<=deltvalue1[0]:
                    deltvalue1[0]=delt1
                    deltva1[0]=value-50
                    filenameImaFit=filenameIma
                    bvhanniu(filepicbvh)
                    #gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
                    #anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
                    imsavefit=imsave

            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
            #anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
            a1[0]= deltva1[0]  #需要更新,不然后面姿态重置了
            bvhanniu()
            num1=(deltva1[0]+50)/5
            #result=cv2.imread(fileResult+str(num1)+'.png')
            #result=cv2.imread(filenameImaFit)
            result =imsavefit
            result2=cv2.imread(filepicture)            
            cv2.imshow("Result",result)
            cv2.imshow("Original",result2)            
            #cv2.waitKey(10)
            log.message(deltvalue1)
            log.message(num1)
            imsavefit = None
                        
        @self.aButtonC2.mhEvent
        def onClicked(event):
            chushihua()
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            for value in range(5,100,5):
                a2[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                #anim = self.loadBvh(fileout, convertFromZUp="auto")
                filenameImage='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                width = G.windowWidth;
                height = G.windowHeight;
                width = width - 3;
                height = height - 3;
                #log.message(filenameImage)
                mh.grabScreen(0,0,width,height,filenameImage)
                img=cv2.imread(filenameImage)
                height1,width1=img.shape[:2]
            #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]




                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                cv2.imshow("img",imsave)
                cv2.waitKey(10)
                delt2=onpicture()
                if delt2<=deltvalue2[0]:
                    deltvalue2[0]=delt2
                    deltva2[0]=value-50


            num2=(deltva2[0]+50)/5
            result=cv2.imread(fileResult+str(num2)+'.png')
            cv2.imshow("Result",result)
            cv2.waitKey(0)
            log.message(deltvalue2)
            log.message(num2)

        @self.aButtonC3.mhEvent
        def onClicked(event):
            chushihua()
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            for value in range(5,100,5):
                a3[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                #anim = self.loadBvh(fileout, convertFromZUp="auto")
                filenameImage='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                width = G.windowWidth;
                height = G.windowHeight;
                width = width - 3;
                height = height - 3;
                #log.message(filenameImage)
                mh.grabScreen(0,0,width,height,filenameImage)
                img=cv2.imread(filenameImage)
                height1,width1=img.shape[:2]
            #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]




                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                cv2.imshow("img",imsave)
                cv2.waitKey(10)
                delt3=onpicture()
                if delt3<=deltvalue3[0]:
                    deltvalue3[0]=delt3
                    deltva3[0]=value-50


            num3=(deltva3[0]+50)/5
            result=cv2.imread(fileResult+str(num3)+'.png')
            cv2.imshow("Result",result)
            cv2.waitKey(0)
            log.message(deltvalue3)
            log.message(num3)

        @self.aButtonC4.mhEvent
        def onClicked(event):
            chushihua()
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            for value in range(5,100,5):
                a4[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                #anim = self.loadBvh(fileout, convertFromZUp="auto")
                filenameImage='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                width = G.windowWidth;
                height = G.windowHeight;
                width = width - 3;
                height = height - 3;
                #log.message(filenameImage)
                mh.grabScreen(0,0,width,height,filenameImage)
                img=cv2.imread(filenameImage)
                height1,width1=img.shape[:2]
            #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]




                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                cv2.imshow("img",imsave)
                cv2.waitKey(10)
                delt4=onpicture()
                if delt4<=deltvalue4[0]:
                    deltvalue4[0]=delt4
                    deltva4[0]=value-50


            num4=(deltva4[0]+50)/5
            result=cv2.imread(fileResult+str(num4)+'.png')
            cv2.imshow("Result",result)
            cv2.waitKey(0)
            log.message(deltvalue4)
            log.message(num4)

        @self.aButtonC5.mhEvent
        def onClicked(event):
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            for value in range(5,100,5):
                chushihua()
                a5[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                #anim = self.loadBvh(fileout, convertFromZUp="auto")
                filenameImage='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                width = G.windowWidth;
                height = G.windowHeight;
                width = width - 3;
                height = height - 3;
                #log.message(filenameImage)
                mh.grabScreen(0,0,width,height,filenameImage)
                img=cv2.imread(filenameImage)
                height1,width1=img.shape[:2]
            #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]




                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                cv2.imshow("img",imsave)
                cv2.waitKey(10)
                delt5=onpicture()
                if delt5<=deltvalue5[0]:
                    deltvalue5[0]=delt5
                    deltva5[0]=value-50


            num5=(deltva5[0]+50)/5
            result=cv2.imread(fileResult+str(num5)+'.png')
            cv2.imshow("Result",result)
            cv2.waitKey(0)
            log.message(deltvalue5)
            log.message(num5)

        @self.aButtonC6.mhEvent
        def onClicked(event):
            #chushihua()
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            
            OrigalIm = cv2.imread(filepicture) #先读目标图像
            for value in range(49,101,10):
                a6[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                #anim = self.loadBvh(fileout, convertFromZUp="auto")
                #cv2.waitKey(10)
                #filenameImage=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameImage=fileResult+str(a6[0])+'DegreeLLeg.png'
                #filenameIma=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma=fileResult+str(a6[0])+'DegreeLLeg.png'
                width = G.windowWidth;
                height = G.windowHeight;
                
                Xdel=600   #原图为800x600  减除后为200x150
                Ydel=450
                width = width - Xdel;
                height = height - Ydel;
                #log.message(filenameImage)
                #mh.grabScreen(300,225,width,height,filenameImage)  #存盘
                
                mh.grabScreen(Xdel/2,Ydel/2,width,height,filenameImage)  #不存盘,全在内在操作,提高速度
                log.message("Saved screengrab to %s", filenameImage)
           
                img=cv2.imread(filenameImage)  #存盘
                height1,width1=img.shape[:2]
                #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]

                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                #cv2.imshow("img",imsave)
                #cv2.waitKey(10)
                #delt6=findcontours.GetDeltValue(imsave,OrigalIm)  #onpicture()
                delt6=findcontours.CalDiff(imsave,OrigalIm)
                log.debug('delt6 (%d Degree): = %f', a6[0], delt6)
                if delt6<=deltvalue6[0]:
                    deltvalue6[0]=delt6
                    deltva6[0]=value-50
                    filenameImaFit=filenameIma
                    bvhanniu(filepicbvh)
                    #gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
                    #anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
                    imsavefit=imsave

            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
            anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
            a6[0]= deltva6[0]  #需要更新,不然后面姿态重置了
            bvhanniu()
            num1=(deltva6[0]+50)/5
            #result=cv2.imread(fileResult+str(num1)+'.png')
            #result=cv2.imread(filenameImaFit)
            result =imsavefit
            result2=cv2.imread(filepicture)            
            cv2.imshow("Result",result)
            cv2.imshow("Original",result2)            
            #cv2.waitKey(10)
            log.message(deltvalue6)
            log.message(num1)
            imsavefit = None

        @self.aButtonC7.mhEvent
        def onClicked(event):
            #chushihua()
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            
            OrigalIm = cv2.imread(filepicture) #先读目标图像
            for value in range(0,60,10):
                a7[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                anim = self.loadBvh(fileout, convertFromZUp="auto")
                #cv2.waitKey(10)
                #filenameImage=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameImage=fileResult+str(a7[0])+'DegreeLLeg.png'
                #filenameIma=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma=fileResult+str(a7[0])+'DegreeLLeg.png'
                width = G.windowWidth;
                height = G.windowHeight;
                
                Xdel=600   #原图为800x600  减除后为200x150
                Ydel=450
                width = width - Xdel;
                height = height - Ydel;
                #log.message(filenameImage)
                #mh.grabScreen(300,225,width,height,filenameImage)  #存盘
                
                mh.grabScreen(Xdel/2,Ydel/2,width,height,filenameImage)  #不存盘,全在内在操作,提高速度
                log.message("Saved screengrab to %s", filenameImage)
           
                img=cv2.imread(filenameImage)  #存盘
                height1,width1=img.shape[:2]
                #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]

                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                #cv2.imshow("img",imsave)
                #cv2.waitKey(10)
                #delt7=findcontours.GetDeltValue(imsave,OrigalIm)  #onpicture()
                delt7=findcontours.CalDiff(imsave,OrigalIm)
                log.debug('delt7 (%d Degree): = %f', a7[0], delt7)
                if delt7<=deltvalue7[0]:
                    deltvalue7[0]=delt7
                    deltva7[0]=value-50
                    filenameImaFit=filenameIma
                    bvhanniu(filepicbvh)
                    #gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
                    anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
                    imsavefit=imsave

            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
            anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
            a7[0]= deltva7[0]  #需要更新,不然后面姿态重置了
            bvhanniu()
            num1=(deltva7[0]+50)/5
            #result=cv2.imread(fileResult+str(num1)+'.png')
            #result=cv2.imread(filenameImaFit)
            result =imsavefit
            result2=cv2.imread(filepicture)            
            cv2.imshow("Result",result)
            cv2.imshow("Original",result2)            
            #cv2.waitKey(10)
            log.message(deltvalue7)
            log.message(num1)
            imsavefit = None

        @self.aButtonC8.mhEvent
        def onClicked(event):
            #chushihua()
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(str(width))
            log.message(str(height))
            
            OrigalIm = cv2.imread(filepicture) #先读目标图像
            for value in range(61,71,10):
                a8[0]=value-50
                bvhanniu()
                gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, fileout))
                anim = self.loadBvh(fileout, convertFromZUp="auto")
                #cv2.waitKey(10)
                #filenameImage=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameImage=fileResult+str(a8[0])+'DegreeLLeg.png'
                #filenameIma=fileResult+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
                filenameIma=fileResult+str(a8[0])+'DegreeLLeg.png'
                width = G.windowWidth;
                height = G.windowHeight;
                
                Xdel=600   #原图为800x600  减除后为200x150
                Ydel=450
                width = width - Xdel;
                height = height - Ydel;
                #log.message(filenameImage)
                #mh.grabScreen(300,225,width,height,filenameImage)  #存盘
                
                mh.grabScreen(Xdel/2,Ydel/2,width,height,filenameImage)  #不存盘,全在内在操作,提高速度
                log.message("Saved screengrab to %s", filenameImage)
           
                img=cv2.imread(filenameImage)  #存盘
                height1,width1=img.shape[:2]
                #print height,width
                for i in range(height1):
                    for j in range(width1):
                        r,b,g= img[i][j]
                        rb=abs(r-b)
                        rg=abs(r-g)
                        bg=abs(b-g)
                        if rb<10 and rg<10 and bg<10:
                            img[i][j]=[0,0,0]
                        else:
                            img[i][j]=[255,255,255]

                imsave=normalize.Normalize(img)
                cv2.imwrite(filenameIma,imsave)
                #cv2.imshow("img",imsave)
                #cv2.waitKey(10)
                #delt8=findcontours.GetDeltValue(imsave,OrigalIm)  #onpicture()
                delt8=findcontours.CalDiff(imsave,OrigalIm)
                log.debug('delt8 (%d Degree): = %f', a8[0], delt8)
                if delt8<=deltvalue8[0]:
                    deltvalue8[0]=delt8
                    deltva8[0]=value-50
                    filenameImaFit=filenameIma
                    bvhanniu(filepicbvh)
                    gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
                    anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
                    imsavefit=imsave

            gui3d.app.do(AotuPose1("Change pose", self, self.currentPose, filepicbvh))
            anim = self.loadBvh(filepicbvh, convertFromZUp="auto")
            a8[0]= deltva8[0]  #需要更新,不然后面姿态重置了
            bvhanniu()
            num1=(deltva8[0]+50)/5
            #result=cv2.imread(fileResult+str(num1)+'.png')
            #result=cv2.imread(filenameImaFit)
            result =imsavefit
            result2=cv2.imread(filepicture)            
            cv2.imshow("Result",result)
            cv2.imshow("Original",result2)            
            #cv2.waitKey(10)
            log.message(deltvalue8)
            log.message(num1)
            imsavefit = None

        def chushihua():
            a1=[0]
            a2=[0]
            a3=[0]
            a4=[0]
            a5=[0] 
            a6=[0]
            a7=[0]
            a8=[0]
            deltvalue1=[100]
            deltvalue2=[100]
            deltvalue3=[100]
            deltvalue4=[100]
            deltvalue5=[100]
            deltvalue6=[100]
            deltvalue7=[100]
            deltvalue8=[100]
            deltva1=[0]
            deltva2=[0]
            deltva3=[0]
            deltva4=[0]
            deltva5=[0]
            deltva6=[0]
            deltva7=[0]
            deltva8=[0]

        def bvhanniu(filename = None):
            if filename is None:
                filename=fileout
            log.debug('FileName is %s',filename)
            f = open(filename, 'w')
            # Write structure
            f.write('HIERARCHY\n')
            bvh1._writeJoint(f, bvh1.rootJoint, 0)
            # Write animation
            f.write('MOTION\n')
            f.write('Frames: %s\n' % bvh1.frameCount)
            f.write('Frame Time: %f\n' % bvh1.frameTime)
            allJoints = [joint for joint in bvh1.getJointsBVHOrder() if not joint.isEndConnector()]
            jointsData = [joint.matrixPoses for joint in allJoints]
            nJoints = len(jointsData)
            nFrames = len(jointsData[0])
            totalChannels = sum([len(joint.channels) for joint in allJoints])

            frameData = []
            for fIdx in xrange(bvh1.frameCount):
                for joint in allJoints:
                    offset = fIdx * len(joint.channels)
                    frameData.extend(joint.frames[offset:offset + len(joint.channels)])
                frameData = [str(fl) for fl in frameData]
            
            frameData[37]=str(a1[0])
            frameData[43]=str(a2[0]+35)
            frameData[127]=str(a3[0])
            frameData[133]=str(a4[0]+35)
            frameData[433]=str(a5[0])
            frameData[439]=str(a6[0])
            frameData[508]=str(a7[0])
            frameData[514]=str(a8[0])
            for fIdx in xrange(bvh1.frameCount):
    
                frameData = [str(fl) for fl in frameData]             
                f.write('%s\n' % " ".join(frameData))

            f.close()
 
        #@self.aButton1.mhEvent
       # def onClicked(event):
          #  filenameImage='F:/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
           # width = G.windowWidth;
         #   height = G.windowHeight;
          #  width = width - 3;
          #  height = height - 3;
          #  log.message(filenameImage)
          #  mh.grabScreen(0,0,width,height,filenameImage)
        def dayinpicture():
            filenameImage='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
            filenameIma='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            #log.message(filenameImage)
            #mh.grabScreen(0,0,width,height,filenameImage)
            #img=cv2.imread(filenameImage)
            img=grabMyScreen(0,0,width,height)
            height1,width1=img.shape[:2]
            #print height,width
            for i in range(height1):
                for j in range(width1):
                    r,b,g= img[i][j]
                    rb=abs(r-b)
                    rg=abs(r-g)
                    bg=abs(b-g)
                    if rb<10 and rg<10 and bg<10:
                        img[i][j]=[0,0,0]
                    else:
                        img[i][j]=[255,255,255]




            imsave=normalize.Normalize(img)
            cv2.imwrite(filenameIma,imsave)

        @self.aButton2.mhEvent
        def onClicked(event):
            filenameImage='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
            filenameIma='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(filenameImage)
            mh.grabScreen(0,0,width,height,filenameImage)
            img=cv2.imread(filenameImage)
            height1,width1=img.shape[:2]
            #print height,width
            for i in range(height1):
                for j in range(width1):
                    r,b,g= img[i][j]
                    rb=abs(r-b)
                    rg=abs(r-g)
                    bg=abs(b-g)
                    if rb<10 and rg<10 and bg<10:
                        img[i][j]=[0,0,0]
                    else:
                        img[i][j]=[255,255,255]




            cv2.imwrite(filenameIma,img)
           # getcontourspoint.MainGetContourPoint(filenameImage,"F:/w1/lunkuo.txt")

        def onpicture():
            filenameImage='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
            filenameIma='F:/Aotu3DImage/'+str(time.strftime("%Y-%m-%d_%H.%M.%S"))+'.png'
            width = G.windowWidth;
            height = G.windowHeight;
            width = width - 3;
            height = height - 3;
            log.message(filenameImage)
            #mh.grabScreen(0,0,width,height,filenameImage)
            img=grabMyScreen(0,0,width,height)
            #log.message(str(imgs))
            #img=cv2.imread(filenameImage)
            height1,width1=img.shape[:2]
            #print height,width
            for i in range(height1):
                for j in range(width1):
                    r,b,g= img[i][j]
                    rb=abs(r-b)
                    rg=abs(r-g)
                    bg=abs(b-g)
                    if rb<10 and rg<10 and bg<10:
                        img[i][j]=[0,0,0]
                    else:
                        img[i][j]=[255,255,255]




           # cv2.imwrite(filenameIma,img)
            imsave=normalize.Normalize(img)
            delt=findcontours.GetDeltValue(imsave,filepicture)
            return delt

        def grabMyScreen(x, y, width, height,filename = None, productionRender=False):
            if width <= 0 or height <= 0:
                raise RuntimeError("width or height is 0")

            log.debug('grabScreen: %d %d %d %d', x, y, width, height)

    # Draw before grabbing, to make sure we grab a rendering and not a picking buffer
            glmodule.draw(productionRender)

            sx0 = x
            sy0 = G.windowHeight - y - height
            sx1 = sx0 + width
            sy1 = sy0 + height

            sx0 = max(sx0, 0)
            sx1 = min(sx1, G.windowWidth)
            sy0 = max(sy0, 0)
            sy1 = min(sy1, G.windowHeight)

            rwidth = sx1 - sx0
            rwidth -= rwidth % 4
            sx1 = sx0 + rwidth
            rheight = sy1 - sy0

            surface = np.empty((rheight, rwidth, 3), dtype = np.uint8)

            log.debug('glReadPixels: %d %d %d %d', sx0, sy0, rwidth, rheight)

            glmodule.glReadPixels(sx0, sy0, rwidth, rheight, GL_RGB, GL_UNSIGNED_BYTE, surface)

            if width != rwidth or height != rheight:
                surf = np.zeros((height, width, 3), dtype = np.uint8) + 127
                surf[...] = surface[:1,:1,:]
                dx0 = (width - rwidth) / 2
                dy0 = (height - rheight) / 2
                dx1 = dx0 + rwidth
                dy1 = dy0 + rheight
                surf[dy0:dy1,dx0:dx1] = surface
                surface = surf

            surface = np.ascontiguousarray(surface[::-1,:,:])
        #surface = Image(data = surface)
            return surface

        @self.aButton.mhEvent
        def onClicked(event):
            f = open(filepath1, 'w')
            # Write structure
            f.write('HIERARCHY\n')
            bvh1._writeJoint(f, bvh1.rootJoint, 0)
            # Write animation
            f.write('MOTION\n')
            f.write('Frames: %s\n' % bvh1.frameCount)
            f.write('Frame Time: %f\n' % bvh1.frameTime)
            allJoints = [joint for joint in bvh1.getJointsBVHOrder() if not joint.isEndConnector()]
            jointsData = [joint.matrixPoses for joint in allJoints]
            nJoints = len(jointsData)
            nFrames = len(jointsData[0])
            totalChannels = sum([len(joint.channels) for joint in allJoints])
            frameData = []
            for fIdx in xrange(bvh1.frameCount):
                for joint in allJoints:
                    offset = fIdx * len(joint.channels)
                    frameData.extend(joint.frames[offset:offset + len(joint.channels)])
                frameData = [str(fl) for fl in frameData]

            for fIdx in xrange(bvh1.frameCount):    
                frameData = [str(fl) for fl in frameData]             
                f.write('%s\n' % " ".join(frameData))

            f.close()