Beispiel #1
0
 def DelectNameSet(self):
     setName = self.select_set_list_qcombobox.currentText()
     deselectNodes = rt.getCurrentSelection()
     rt.select(rt.selectionSets[setName])
     rt.deselect(deselectNodes)
     rt.selectionSets[setName] = rt.getCurrentSelection()
     self.UpdateNameSet()
def animate_transform(thing):
    '''Records an animation on the provided object'''
    # select the object to animate so we will see the keyframes in the timeslider
    rt.select(thing)

    # animate
    with mx.animate(True):
        with mx.redraw(True):
            with mx.attime(30):
                thing.pos = rt.Point3(50, 0, 0)

            with mx.attime(60):
                thing.Pos = rt.Point3(100, 50, 0)

            with mx.attime(90):
                thing.Pos = rt.Point3(50, 100, 0)

            with mx.attime(120):
                thing.Pos = rt.Point3(0, 100, 0)

            with mx.attime(150):
                thing.Pos = rt.Point3(-50, 50, 0)

            with mx.attime(180):
                thing.Pos = rt.Point3(0, 0, 0)
Beispiel #3
0
 def SelectNameSet(self):
     name = self.select_set_list_qcombobox.currentText()
     #print(name)
     rt.clearSelection()
     if not self.IsSelectSetNewName(name):
         set_tiem = rt.selectionSets[name]
         rt.select(set_tiem)
     rt.redrawViews()
Beispiel #4
0
def splitLayersToFiles():
    if (not qtUtils.popup_Yes_No(
            "This operation could take some time....Are you sure?",
            "Confirm")):
        return
    rootLayer = layer.getAllRootLayer()
    for l in rootLayer:
        nodes = layer.getAllNodeInLayerTree(l)
        rt.select(nodes)
        newFilePath = rt.maxFilePath + l.name
        rt.saveNodes(nodes, newFilePath, quiet=True)
Beispiel #5
0
 def selectMode(self, target_node):
     if not rt.IsValidNode(self.m_biped_class.m_com):
         return self.ReStart()
     modifiers = QtWidgets.QApplication.keyboardModifiers()
     if modifiers == QtCore.Qt.ControlModifier:
         rt.selectMore(target_node)
     elif modifiers == QtCore.Qt.AltModifier:
         rt.deselect(target_node)
     else:
         rt.select(target_node)
     rt.redrawViews()
Beispiel #6
0
 def select(self, name='', index=0):
     node = self.GetNode(name, index)
     result = rt.IsValidNode(node)
     modifiers = QtWidgets.QApplication.keyboardModifiers()
     if node is not None and result:
         if modifiers == QtCore.Qt.ControlModifier:
             rt.selectMore(node)
         elif modifiers == QtCore.Qt.AltModifier:
             rt.deselect(node)
         else:
             rt.select(node)
     rt.redrawViews()
     return result
Beispiel #7
0
def select_nodes(max_nodes, add=False):
    """
    Select given Max nodes
    :param max_nodes: list<MaxPlus.INode>
    :param add: bool, Whether to add given node names to an existing selection or not
    """

    max_nodes = python.force_list(max_nodes)

    sel = list() if not add else list(rt.selection)
    for max_node in max_nodes:
        max_node = node.get_pymxs_node(max_node)
        sel.append(max_node)
    if not sel:
        return

    rt.select(sel)
    def _uvSnaps(self, assetName):
        originalSelection = rt.execute("selection as array")
        validShapes = rt.execute(
            "for o in selection where superClassOf o == geometryClass collect o"
        )

        if len(validShapes) > 10:
            msg = "There are %s objects for UV snapshots.\nAre you sure you want to include snapshots to the Asset?" % (
                len(validShapes))
            state = rt.queryBox(msg, title='Too many objects for UV Snapshot')
            if state:
                pass
            else:
                return

        assetDirectory = os.path.join(self.directory, assetName)
        UVdir = os.path.join(assetDirectory, "UV_snaps")

        if not os.path.isdir(os.path.normpath(UVdir)):
            os.makedirs(os.path.normpath(UVdir))

        rt.execute("max modify mode")

        for i in validShapes:
            objName = i.name
            UVpath = os.path.join(UVdir, '%s_uv.jpg' % objName)
            rt.select(i)
            defUnwrapMod = rt.Unwrap_UVW()
            rt.addModifier(i, defUnwrapMod)
            defUnwrapMod.setMapChannel = 1
            defUnwrapMod.renderuv_fillmode = 0
            defUnwrapMod.renderuv_seamColor = rt.Name("green")
            defUnwrapMod.renderuv_showframebuffer = False
            defUnwrapMod.renderuv_force2sided = False
            defUnwrapMod.renderuv_fillColor = rt.Name("black")
            defUnwrapMod.renderuv_showoverlap = False
            defUnwrapMod.renderuv_overlapColor = rt.Name("red")
            defUnwrapMod.renderuv_edgeColor = rt.Name("white")
            defUnwrapMod.renderuv_visibleedges = True
            defUnwrapMod.renderuv_invisibleedges = False
            defUnwrapMod.renderuv_seamedges = False
            defUnwrapMod.renderUV(UVpath)
            rt.deleteModifier(i, defUnwrapMod)

        rt.select(originalSelection)
Beispiel #9
0
def create_box_control(name, init_pos=None, length=10, width=10, height=10, color=None):
    """
    Creates a box control
    :param name: str
    :param init_pos:
    :param length:
    :param width:
    :param height:
    :param color:
    :return:
    """

    pos = init_pos or [0, 0, 0]
    if rt.classOf(pos) != rt.Point3:
        pos = rt.Point3(*pos)
    if color and rt.classOf(color) != rt.color:
        color = rt.color(*color)
    if not color:
        color = rt.yellow

    rt.setCommandPanelTaskMode(rt.Name('modify'))
    base_box = rt.Box(
        lengthsegs=1, widthsegs=1, heightsegs=1, length=length, width=width, height=height,
        mapcoords=True, pos=pos, isSelected=True)
    rt.select(base_box)
    rt.convertTo(base_box, rt.PolyMeshObject)
    rt.subobjectLevel = 2
    edge_bitarray = rt.BitArray()
    edge_indices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    edge_bitarray.count = len(edge_indices)
    for i, index in enumerate(edge_indices):
        edge_bitarray[i] = index
    base_box.EditablePoly.SetSelection(rt.Name('Edge'), edge_bitarray)
    ctrl_name = rt.uniquename(name)
    base_box.EditablePoly.createShape(ctrl_name, False, base_box)
    rt.subobjectLevel = 0
    rt.delete(base_box)
    box_ctrl = rt.getNodeByName(ctrl_name)
    rt.convertTo(box_ctrl, rt.SplineShape)
    box_ctrl.wirecolor = color
    rt.CenterPivot(box_ctrl)
    transform.reset_xform_and_collapse(box_ctrl, freeze=True)

    return box_ctrl
Beispiel #10
0
def select_nodes_by_name(names, add=False):
    """
    Selects nodes by name
    :param names: list<str>, names of nodes to select
    :param add: bool, Whether to add given node names to an existing selection or not
    """

    names = python.force_list(names)

    nodes = list() if not add else list(rt.selection)
    for n in names:
        node = get_node_by_name(n)
        if node:
            nodes.append(node)

    # Clear selection if need it
    if not add:
        rt.clearSelection()

    rt.select(nodes)
Beispiel #11
0
def createHelperBoneSystem():
    sysOption = config.SystemOption()

    regularMesh = rt.getNodeByName(sysOption.regularMeshName)
    referenceMesh = rt.getNodeByName(sysOption.referenceMeshName)

    primarySkinMod = 0

    for i in range(0, len(regularMesh.Modifiers)):
        if str(rt.classof(regularMesh.Modifiers[i])) == 'Skin':
            regularMesh.Modifiers[i].name = 'Skin_Original'
            primarySkinMod = regularMesh.Modifiers[i]
            break

    poseLearner = ln.PoseLearner(regularMesh, referenceMesh, primarySkinMod,
                                 sysOption)
    poseLearner.processStart()

    # re-select the mesh to refresh the modifiers list displaying
    rt.select(regularMesh)
Beispiel #12
0
    def createHelperBoneSystem(self):
        regularMesh = rt.getNodeByName('Regular')
        referenceMesh = rt.getNodeByName('Reference')

        primarySkinMod = 0

        for i in range(0, len(regularMesh.Modifiers)):
            if str(rt.classof(regularMesh.Modifiers[i])) == 'Skin':
                regularMesh.Modifiers[i].name = "Skin_Backup"
                primarySkinMod = regularMesh.Modifiers[i]
                break

        # primaryBoneNameList = ['Bip001 L Clavicle', 'Bip001 L UpperArm', 'Bip001 L Forearm']
        primaryBoneNameList = ['Root']
        poseLearner = ln.PoseLearner(regularMesh, referenceMesh, primarySkinMod, primaryBoneNameList, self.sysOption)

        poseLearner.processStart()

        # re-select the mesh to refresh the modifiers list displaying
        rt.select(regularMesh)
Beispiel #13
0
    def startTransfer(self):
        mxs.execute("max create mode")

        with pymxs.undo(True):

            for i in self.skinMeshes:
                skinSource = mxs.skinUtils.ExtractSkinData(i[0])
                skinSource = mxs.getNodeByName("SkinData_{}".format(i[0].name))

                count = mxs.skinOps.GetNumberBones(i[1])
                newBones = []

                for item in range(count):
                    # print(item +1, i[0].name, mxs.skinOps.GetBoneNode(i[1], item + 1))
                    try:
                        newBones.append(self.dict[mxs.skinOps.GetBoneNode(
                            i[1], item + 1)])
                    except:
                        pass

                oldSkin = i[1]
                oldSkin.enabled = False

                skinMod = mxs.Skin()
                skinMod.name = "Transfered Skin"

                mxs.addModifier(i[0], skinMod, before=i[2] - 1)

                for bone in newBones:
                    mxs.skinOps.addbone(skinMod, bone, 0)

                mxs.select(i[0])
                mxs.selectmore(skinSource)
                mxs.skinUtils.ImportSkinDataNoDialog(True, False, False, False,
                                                     False, 1.0, 0)

                mxs.delete(skinSource)
                mxs.clearSelection()

        mxs.execute("max modify mode")
Beispiel #14
0
def select_node(node, replace_selection=True, **kwargs):
    """
    Selects given object in the current scene
    :param replace_selection: bool
    :param node: str
    """

    node = node_utils.get_pymxs_node(node)

    if replace_selection:
        return rt.select(node)
    else:
        return rt.selectMore(node)
Beispiel #15
0
	
	print each.name
	
#get first selected

firstItem = rt.selection[0]

print firstItem.name

#create simple object

rt.sphere(radius=50, position=rt.point3(25, 25, 25), segments=8)

#select all objects

rt.select(rt.objects)

# with MaxPlus

MaxPlus.Core.GetRootNode().Children

#clear selection

rt.clearselection()


rt.select(firstItem)

print rt.firstItem.name

Beispiel #16
0
    def recreate(self):
        defaultSize = 2
        bones = mxs.Array()

        if len(self.result) > 0:
            self.newNodes = []
            self.dict = {}
            temp = mxs.Array()
            lastNode = None
            index = 0

            rootNode = mxs.BoneSys.createBone(mxs.point3(0, 0, 0),
                                              mxs.point3(0, 1, 0),
                                              mxs.point3(0, 1, 0))
            rootNode.transform = mxs.Matrix3(1)
            rootNode.size = 2
            rootNode.name = "rootBone"
            mxs.join(temp, rootNode)

        def new_create_constraints(node, nNode):

            posList = mxs.position_list()  # Create Pos_List
            const = mxs.Position_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Position",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

            posList = mxs.rotation_list()  # Create Pos_List
            const = mxs.Orientation_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Rotation",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

        def create_constraints(nNode, node):
            # Position
            posList = mxs.position_list()  # Create Pos_List
            const = mxs.Position_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Position",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

            # Rotation
            posList = mxs.rotation_list()  # Create Pos_List
            const = mxs.Orientation_Constraint()  # Create  Pos_Constraint
            const.appendTarget(nNode, 100)  # Add target to Constraint
            secsub = mxs.setPropertyController(node.controller, "Rotation",
                                               posList)  # Add PosList to node
            mxs.setPropertyController(secsub, 'Available', const)

        for obj in self.result:
            endPos = mxs.point3(0, 0, 0)

            if obj.children.count > 0:
                endPos = obj.children[0].transform.pos

            else:
                endPos = (mxs.transmatrix(mxs.point3(defaultSize, 0, 0)) *
                          obj.transform).pos

            zPos = (mxs.transmatrix(mxs.point3(0, 0, 1)) * obj.transform).pos
            d = mxs.BoneSys.createBone(obj.transform.pos, endPos, zPos)
            d.transform = obj.transform
            d.name = obj.name
            d.wirecolor = obj.wirecolor
            mxs.join(bones, d)
            self.dict[obj] = d
            self.newNodes.append(obj)

            # Create parent connections
            if mxs.isValidNode(obj.parent):
                d.parent = self.dict[obj.parent]

            else:
                d.parent = rootNode

            create_constraints(obj, d)

        mxs.select(bones)
        mxs.selectmore(rootNode)
        mxs.redrawViews()
Beispiel #17
0
 def SelectAllSceneObjects(self):
     rt.select(rt.objects)
Beispiel #18
0
 def changeSelection(self):
     item = self.lw_skiin.selectedItems()
     num = self.lw_skiin.row(item[0])
     mxs.select(self.skinMeshes[num][0])
     mxs.modPanel.setCurrentObject(self.skinMeshes[num][1])
Beispiel #19
0
    def buildWiperMesh(self, p1, p2):
        """
        Build the wiper mesh 

        Parameters
        ----------
            p1 : Point3
                the world position of the first dummy placed on the exterior part of the wiper
            p2 : Point3
                the world position of the second dummy placed on the exterior part of the wiper
        """

        animationLength = self.animInEndFrame - self.animInStartFrame + 1
        projectMeshVertices = []
        projectMeshFaces = []

        vColors = [rt.Point3(0, 0, 0) for i in range(animationLength * 2)]

        vert_count = 0

        if rt.DEBUG_MODE:
            print(
                "------------------------------------------------------------------"
            )

        #fill projectMeshVertices with the exterior points of the wiper for each frame
        f = self.animInStartFrame
        while f <= self.animInEndFrame:
            with at(f):
                projectMeshVertices.append(p1.transform.position)
                projectMeshVertices.append(p2.transform.position)
                f += 1

        # fill the vertexColors array during animation IN
        vIndex = 0
        f = self.animInStartFrame
        while f <= self.animInEndFrame:
            with at(f):
                self.setColorByFrame(f, vColors[vIndex])
                self.setColorByFrame(f, vColors[vIndex + 1])
                f += 1
                vIndex += 2

        # fill the vertexColors array during animation OUT
        vIndex = 0
        f = self.animOutEndFrame
        while f >= self.animOutStartFrame:
            with at(f):
                self.setColorByFrame(f, vColors[vIndex])
                self.setColorByFrame(f, vColors[vIndex + 1])
                f -= 1
                vIndex += 2

        axis = rt.Point3(1, 0, 0)
        result = rt.dot(p2.transform.position, axis)

        for i in range(1, len(projectMeshVertices) - 1):
            #build the triangle with the righ orientation
            if i % 2 != 0:
                projectMeshFaces.append(
                    rt.Point3(vert_count + 3, vert_count + 2, vert_count + 1))
            else:
                projectMeshFaces.append(
                    rt.Point3(vert_count + 2, vert_count + 3, vert_count + 1))

            vert_count += 1

        #build the mesh with an array of vertex and triangles
        projectionMesh = rt.mesh(vertices=rt.Array(*(projectMeshVertices)),
                                 faces=rt.Array(*(projectMeshFaces)))
        rt.defaultVCFaces(projectionMesh)

        #set the vertex color for each vertex
        for i in range(len(projectMeshVertices)):
            rt.setVertColor(projectionMesh, i + 1, vColors[i])

        if result > 0:
            rt.select(projectionMesh)
            rt.execute("max modify mode")
            normalModifier = rt.NormalModifier()
            rt.addModifier(projectionMesh, rt.NormalModifier())
            normal = rt.Name("Normal")
            projectionMesh.modifiers[normal].flip = True

        rt.maxOps.CollapseNode(projectionMesh, False)

        #quadrify
        rt.select(projectionMesh)
        rt.convertToPoly(projectionMesh)
        rt.execute("max modify mode")
        rt.PolyToolsModeling.Quadrify(True, False)
        edge = rt.Name("EDGE")
        edgeNumber = projectionMesh.EditablePoly.getNumEdges()
        edgeList = [1] if result < 0 else [2]
        edgeSelection = rt.BitArray(*(edgeList))
        rt.subObjectLevel = 2
        projectionMesh.EditablePoly.SetSelection(edge, edgeSelection)
        projectionMesh.EditablePoly.SelectEdgeRing()
        projectionMesh.connectEdgeSegments = 3
        rt.execute('macros.run "Ribbon - Modeling" "ConnectEdges"')

        return projectionMesh
    def saveAsset(self,
                  assetName,
                  exportUV=True,
                  exportOBJ=True,
                  exportFBX=True,
                  exportABC=True,
                  selectionOnly=True,
                  sceneFormat="max",
                  notes="N/A",
                  **info):
        """
        Saves the selected object(s) as an asset into the predefined library
        """
        # self.ssResolution = 1000
        if assetName == "":
            msg = "Asset Name cannot be empty"
            state = rt.messageBox(msg, title='Info')
            return

        if assetName in self.assetsList:
            msg = "This Asset already exists.\nDo you want to overwrite?"
            state = rt.queryBox(msg, title='Manager Question')
            if state:
                pass
            else:
                return

        originalSelection = self._getSelection(asMaxArray=True)
        originalPath = self._getSceneFile()

        dump, origExt = os.path.splitext(originalPath)

        assetDirectory = os.path.join(self.directory, assetName)

        assetAbsPath = os.path.join(assetDirectory,
                                    "%s%s" % (assetName, u'.%s' % sceneFormat))

        if selectionOnly:
            selection = self._getSelection(asMaxArray=True)
            if len(selection) == 0:
                msg = "No object selected"
                rt.messageBox(msg, title='Info')
                return
        else:
            rt.select(rt.objects)
            selection = self._getSelection(asMaxArray=True)

        # originalSelection = self._getSelection(asMaxArray=True)

        if not os.path.exists(assetDirectory):
            os.mkdir(assetDirectory)

        # GET TEXTURES
        # ------------

        if selectionOnly:

            possibleFileHolders = rt.execute("selection as Array")
            filteredBitmaps = self._getFileNodes(possibleFileHolders)

        else:
            allTexture = rt.usedMaps()
            allBitmap = rt.getClassInstances(rt.bitmapTexture)
            # this makes sure only the USED bitmaps will stored
            filteredBitmaps = [
                x for x in allBitmap if x.filename in allTexture
            ]

        textureDatabase = [
            x for x in self._buildPathDatabase(filteredBitmaps, assetDirectory)
        ]

        self._copyTextures(textureDatabase)

        # CREATE PREVIEWS
        # ---------------
        thumbPath, ssPath, swPath = self._createThumbnail(
            assetName, selectionOnly=selectionOnly, viewFit=True)

        # CREATE UV SNAPSHOTS
        # ----------------
        rt.select(selection)

        if exportUV:
            self._uvSnaps(assetName)

        # SAVE SOURCE
        # -----------
        fManager.SaveSelected(assetAbsPath)

        # EXPORT OBJ
        # ----------

        if exportOBJ:
            objFilePath = os.path.join(assetDirectory, "%s.obj" % assetName)
            if self._exportObj(objFilePath,
                               exportSettings=self.exportSettings):
                objName = "{0}.obj".format(assetName)
            else:
                objName = "N/A"
        else:
            objName = "N/A"

        # EXPORT FBX
        # ----------
        if exportFBX:
            fbxFilePath = os.path.join(assetDirectory, "%s.fbx" % assetName)
            frame = self._getCurrentFrame()

            if self._exportFbx(fbxFilePath,
                               exportSettings=self.exportSettings,
                               timeRange=[frame, frame]):
                fbxName = "{0}.fbx".format(assetName)
            else:
                fbxName = "N/A"
        else:
            fbxName = "N/A"

        # EXPORT ALEMBIC
        # --------------

        if exportABC:

            abcFilePath = os.path.join(assetDirectory, "%s.abc" % assetName)
            frame = self._getCurrentFrame()

            if self._exportAlembic(abcFilePath,
                                   exportSettings=self.exportSettings,
                                   timeRange=[frame, frame]):
                abcName = "{0}.abc".format(assetName)
            else:
                abcName = "N/A"
        else:
            abcName = "N/A"

        # NUMERIC DATA
        # ------------

        polyCount = sum(rt.getPolygonCount(x)[0] for x in selection)
        # polyCount = sum(rt.getPolygonCount(x)[0] for x in countLoop)
        tiangleCount = sum(rt.getPolygonCount(x)[1] for x in selection)
        # tiangleCount = sum(rt.getPolygonCount(x)[1] for x in countLoop)

        versionInfo = rt.maxversion()
        vInfo = [versionInfo[0], versionInfo[1], versionInfo[2]]

        # DATABASE
        # --------

        dataDict = {}
        dataDict['sourceProject'] = "3dsMax"
        dataDict['version'] = vInfo
        dataDict['assetName'] = assetName
        dataDict['objPath'] = objName
        dataDict['fbxPath'] = fbxName
        dataDict['abcPath'] = abcName
        dataDict['sourcePath'] = os.path.basename(assetAbsPath)
        dataDict['thumbPath'] = os.path.basename(thumbPath)
        dataDict['ssPath'] = os.path.basename(ssPath)
        dataDict['swPath'] = os.path.basename(swPath)
        dataDict['textureFiles'] = [x["Texture"] for x in textureDatabase]
        dataDict['Faces/Triangles'] = ("%s/%s" %
                                       (str(polyCount), str(tiangleCount)))
        dataDict['origin'] = originalPath
        dataDict['notes'] = notes

        self._setData(assetName, dataDict)

        rt.clearSelection()
        self._returnOriginal(textureDatabase)
        # self.scanAssets() # scanning issued at populate function on ui class
        rt.select(originalSelection)
        rt.messageBox("Asset Created Successfully", title='Info', beep=False)
Beispiel #21
0
    def createPreview(self, *args, **kwargs):
        """Creates a Playblast preview from currently open scene"""
        # rt = pymxs.runtime

        openSceneInfo = self.getOpenSceneInfo()
        if not openSceneInfo:
            msg = "This is not a base scene. Scene must be saved as a base scene before playblasting."
            # raise Exception([360, msg])
            self._exception(360, msg)
            return
            # logger.warning(msg)
            # return -1, msg

        # get view info
        viewportType = rt.viewport.getType()
        if str(viewportType) == "view_camera":
            currentCam = str(rt.getActiveCamera().name)
        else:
            currentCam = str(viewportType)

        validName = currentCam.replace("|", "__").replace(" ", "_")
        extension = "avi"

        # versionName = rt.getFilenameFile(rt.maxFileName) #
        versionName = rt.maxFilePath + rt.maxFileName  # abs path of the filename with extension
        relVersionName = os.path.relpath(
            versionName, start=openSceneInfo["projectPath"]
        )  # relative path of filename with ext

        if not os.path.isdir(os.path.normpath(openSceneInfo["previewPath"])):
            os.makedirs(os.path.normpath(openSceneInfo["previewPath"]))
        playBlastFile = os.path.join(
            openSceneInfo["previewPath"],
            "{0}_{1}_PB.{2}".format(self.niceName(versionName), validName,
                                    extension))
        relPlayBlastFile = os.path.relpath(playBlastFile,
                                           start=openSceneInfo["projectPath"])

        if os.path.isfile(playBlastFile):
            try:
                os.remove(playBlastFile)
            except WindowsError:
                msg = "The file is open somewhere else"
                logger.warning(msg)
                return -1, msg

        jsonInfo = self._loadJson(openSceneInfo["jsonFile"])
        if jsonInfo == -1:
            msg = "Database file is corrupted"
            return -1, msg
        # returns 0,"" if everything is ok, -1,msg if error

        pbSettings = self.loadPBSettings()
        originalValues = {"width": rt.renderWidth, "height": rt.renderHeight}

        originalSelection = rt.execute("selection as array")

        # change the render settings temporarily
        rt.renderWidth = pbSettings["Resolution"][0]
        rt.renderHeight = pbSettings["Resolution"][1]

        if pbSettings["PolygonOnly"]:
            dspGeometry = True
            dspShapes = False
            dspLights = False
            dspCameras = False
            dspHelpers = False
            dspParticles = False
            dspBones = False
        else:
            dspGeometry = True
            dspShapes = True
            dspLights = True
            dspCameras = True
            dspHelpers = True
            dspParticles = True
            dspBones = True

        dspGrid = pbSettings["ShowGrid"]
        dspFrameNums = pbSettings["ShowFrameNumber"]
        percentSize = pbSettings["Percent"]

        if pbSettings["WireOnShaded"]:
            rndLevel = rt.execute("#litwireframe")
        else:
            rndLevel = rt.execute("#smoothhighlights")

        if pbSettings["ClearSelection"]:
            rt.clearSelection()

        # find the path of where the avi file be created
        # if rt.maxFilePath:
        #     previewname = rt.getFilenameFile(rt.maxFileName)
        # else:
        #     previewname = "Untitled"

        # sourceClip = rt.GetDir(rt.execute("#preview")) + "\_scene.avi"

        # if os.path.isfile(sourceClip):
        #     try:
        #         os.remove(sourceClip)
        #     except WindowsError:
        #         msg = "Cannot continue creating preview.\n Close '%s' and try again" %sourceClip
        #         logger.error(msg)
        #         return -1, msg

        test = rt.createPreview(filename=playBlastFile,
                                percentSize=percentSize,
                                dspGeometry=dspGeometry,
                                dspShapes=dspShapes,
                                dspLights=dspLights,
                                dspCameras=dspCameras,
                                dspHelpers=dspHelpers,
                                dspParticles=dspParticles,
                                dspBones=dspBones,
                                dspGrid=dspGrid,
                                dspFrameNums=dspFrameNums,
                                rndLevel=rndLevel)

        # prior to version 2020, filename flag is not working
        if not os.path.isfile(playBlastFile):
            # find the path of where the avi file be created
            if rt.maxFilePath:
                previewname = rt.getFilenameFile(rt.maxFileName)
            else:
                previewname = "Untitled"

            sourceClip = rt.GetDir(rt.execute("#preview")) + "\_scene.avi"
            shutil.copy(sourceClip, playBlastFile)

            # if os.path.isfile(sourceClip):
            #     try:
            #         os.remove(sourceClip)
            #     except WindowsError:
            #         msg = "Cannot continue creating preview.\n Close '%s' and try again" %sourceClip
            #         logger.error(msg)
            #         return -1, msg

        # return
        # return the render width and height to original:
        rt.renderWidth = originalValues["width"]
        rt.renderHeight = originalValues["height"]

        rt.select(originalSelection)

        # shutil.copy(sourceClip, playBlastFile)

        if pbSettings["ConvertMP4"]:
            convertedFile = self._convertPreview(playBlastFile,
                                                 overwrite=True,
                                                 deleteAfter=False,
                                                 crf=pbSettings["CrfValue"])
            relPlayBlastFile = os.path.relpath(
                convertedFile, start=openSceneInfo["projectPath"])
            # os.startfile(convertedFile)
        else:
            relPlayBlastFile = os.path.relpath(
                playBlastFile, start=openSceneInfo["projectPath"])

        ## find this version in the json data

        for version in jsonInfo["Versions"]:
            if relVersionName == version["RelativePath"]:
                version["Preview"][currentCam] = relPlayBlastFile

        self._dumpJson(jsonInfo, openSceneInfo["jsonFile"])
        return 0, ""
Beispiel #22
0
 def _selectionChanged(self):
     selection = self.getSelectedRootList()
     selection = sceneUtils.getDescendantsOfMultiple(selection)
     rt.select(selection)
Beispiel #23
0
    def projectVertexColor(self, nodeToBake, nodeToProject, outputPath,
                           padding):
        """
        Project the vertex color of a given node to a given surface and bake the result in the given path 

        Parameters
        ----------
            nodeToBake : INode
                the node used to bake the texture
            nodeToProject : INode
                the node used to project the vertex color
            outputPath : str
                the path of the baked texture
        """
        rt.disableSceneRedraw()
        rt.select(nodeToBake)
        snap = rt.snapshot(nodeToBake, name=nodeToBake.name + "_new")
        snap.material = rt.standard(showInViewport=False, name="GlassMat")
        nodeToProject.material = rt.standard(diffuseMap=rt.Vertex_Color(),
                                             showInViewport=False,
                                             name="WiperMat")
        # --Clear all render elements
        snap.iNodeBakeProperties.removeAllBakeElements()
        # --Preparing the Bake Elements:
        be1 = rt.diffusemap()  # --instance of the bake element class
        be1.outputSzX = be1.outputSzY = 1024  # --set the size of the baked map --specifythe full file path, name and type:
        be1.fileType = outputPath
        be1.fileName = rt.filenameFromPath(be1.fileType)
        be1.filterOn = True  # --enable filtering
        be1.shadowsOn = False  # --disable shadows
        be1.lightingOn = False  # --disable lighting
        be1.enabled = True  # --enable baking
        snap.iNodeBakeProperties.nDilations = padding  # --expand the texturea bit
        snap.iNodeBakeProperties.addBakeElement(be1)  # --add first element
        snap.iNodeBakeProperties.bakeEnabled = True  # --enabling baking
        snap.iNodeBakeProperties.bakeChannel = 2  # --channel to bake
        snap.INodeBakeProjProperties.bakeEnabled = True  # --enabling baking
        snap.INodeBakeProjProperties.bakeChannel = 2  # --channel to bake
        snap.INodeBakeProjProperties.subObjBakeChannel = 2
        snap.INodeBakeProjProperties.enabled = True  #enable projection baking

        # add a projection modifier and set it as the projection source
        projection = rt.Projection()
        rt.addModifier(snap, projection)
        projection.addObjectNode(nodeToProject)
        projection.resetCage()
        snap.INodeBakeProjProperties.projectionMod = projection
        snap.INodeBakeProjProperties.rayMissColor = rt.Point3(0, 0, 0)

        #select the object enter modify mode, offset the cage and bake the texture at the given path

        rt.select(
            snap
        )  # --we are baking the selection, so we select the object --Call the rendererto bake both elements:
        rt.execute("max modify mode")
        projection.pushCage(0.1)
        rt.render(rendertype=rt.Name("bakeSelected"),
                  vfb=False,
                  progressBar=True,
                  outputSize=rt.Point2(1024, 1024))
        print("baked image in {0}".format(be1.fileType))
        rt.delete(snap)
        rt.enableSceneRedraw()
        rt.CompleteRedraw()
Beispiel #24
0
    def old_recreate(self):
        with pymxs.undo(True):

            if len(self.result) > 0:
                self.newNodes = []
                self.dict = {}
                temp = mxs.Array()
                lastNode = None
                index = 0

                rootNode = mxs.point()
                rootNode.size = 2
                rootNode.showlinks = True
                rootNode.Box = True
                rootNode.cross = False
                rootNode.axistripod = False
                rootNode.centermarker = False
                mxs.join(temp, rootNode)

            def create_constraints(node, nNode):

                # Position
                sub = mxs.getSubAnim(nNode, 3)
                secsub = mxs.getSubAnim(sub, 1)
                secsub.controller = mxs.Position_List()
                posCtrl = mxs.Position_Constraint()
                thirdsub = mxs.getSubAnim(secsub, 2)
                thirdsub.controller = posCtrl
                posConstraintInterface = posCtrl.constraints
                posConstraintInterface.appendTarget(node, 100)

                # Rotation
                sub = mxs.getSubAnim(nNode, 3)
                secsub = mxs.getSubAnim(sub, 2)
                secsub.controller = mxs.rotation_list()
                posCtrl = mxs.Orientation_Constraint()
                thirdsub = mxs.getSubAnim(secsub, 2)
                thirdsub.controller = posCtrl
                posConstraintInterface = posCtrl.constraints
                posConstraintInterface.appendTarget(node, 100)

            for i in self.result:
                # Create new nodes and add them to list and dict
                nNode = mxs.point()
                nNode.showlinks = True
                nNode.size = 2
                nNode.transform = i.transform
                nNode.name = i.name
                nNode.wireColor = i.wireColor
                self.dict[i] = nNode
                self.newNodes.append(i)

                # Create parent connections
                if mxs.isValidNode(i.parent):
                    nNode.parent = self.dict[i.parent]

                else:
                    nNode.parent = rootNode

                # Create Constraints
                create_constraints(i, nNode)

                # final part
                mxs.join(temp, nNode)
                lastNode = nNode
                index += 1

            mxs.select(temp)

        mxs.redrawViews()
    print('centering points ch points')
    hull_verts = [hull.points[vert] - center for vert in hull.vertices]

    print('working out svd')
    pcloud = matrix(hull_verts)
    _, _, vh = svd(pcloud)

    print('building matrix')
    xaxis, yaxis, zaxis = vh.tolist()

    xaxis = mxs.point3(*map(float, xaxis))
    yaxis = mxs.point3(*map(float, yaxis))
    zaxis = mxs.point3(*map(float, zaxis))

    transform = mxs.matrix3(mxs.normalize(xaxis),
                            mxs.normalize(yaxis),
                            mxs.normalize(zaxis),
                            mxs.point3(*map(float, center)))

    return transform


if __name__ == '__main__':
    if not list(mxs.selection):
        raise RuntimeError('select something my guy')

    pnt = mxs.point(name='volume align transform')
    pnt.transform = volume_based_transform(mxs.selection[0])
    mxs.select(pnt)
Beispiel #26
0
 def _doubleClickedItem(self):
     selected = self.selectedItems()
     s = selected[len(selected) - 1]
     if(s.childCount() == 0):
         rt.select(self._rootDict[s])
         userprop.openUserPropertyWindow()