Exemple #1
0
    def pickPositions(self):

        refs = []

        for name in self.pick_transform:

            if "#" in name:
                i = 0
                while not self.minmax[name].max > 0 or i < self.minmax[name].max:
                    localName = string.replaceSharpWithPadding(name, i)

                    position = uit.pickPosition("Pick %s position"%localName, False)
                    if not position:
                        break
                    self.tra[localName] = tra.getTransformFromPosition(position)
                    refs.append(self.drawRef(self.tra[localName]))

                    i += 1

                if i < self.minmax[name].min:
                    gear.log("Minimum of object requiered for "+name+" hasn't been reached", gear.sev_warning)
                    xsi.DeleteObj(refs)
                    return False
            else:
                position = uit.pickPosition("Pick %s position"%name, True)
                if not position:
                    xsi.DeleteObj(refs)
                    return False

                self.tra[name] = tra.getTransformFromPosition(position)
                refs.append(self.drawRef(self.tra[name]))

        xsi.DeleteObj(refs)

        return True
Exemple #2
0
def plotSpringToControler(comp_name, prop):

    # Get objects
    model = prop.Model
    refs = []
    ctls = []
    i = 0
    while True:
        ctl = model.FindChild(comp_name + "_fk%s_ctl" % i)
        ref = model.FindChild(comp_name + "_%s_ref" % i)

        if not ctl or not ref:
            break

        ctls.append(ctl)
        refs.append(ref)

        i += 1

    # UI
    pc = ani.PlayControl()
    ui_prop = xsi.ActiveSceneRoot.AddProperty("CustomProperty", False, "Plot")
    pStartFrame = ui_prop.AddParameter3("start_frame", c.siInt4,
                                        pc.localIn.Value, None, None)
    pEndFrame = ui_prop.AddParameter3("end_frame", c.siInt4, pc.localOut.Value,
                                      None, None)

    rtn = xsi.InspectObj(ui_prop, "", "Plot", c.siModal, False)

    start_frame = pStartFrame.Value
    end_frame = pEndFrame.Value

    xsi.DeleteObj(ui_prop)

    if rtn:
        return

    # Plot
    params = [
        ref.Kinematics.Local.Parameters("rot" + s).FullName for ref in refs
        for s in "xyz"
    ]
    action = xsi.PlotAndApplyActions(",".join(params), "plot", start_frame,
                                     end_frame, 1, 20, 3, False, .01, True,
                                     False, False, False)(0)

    # Edit the stored Action
    for item in action.SourceItems:

        item.Target = item.Target.replace(comp_name + "_", comp_name + "_fk")
        item.Target = item.Target.replace("_ref", "_ctl")

    prop.Parameters(comp_name + "_main_blend").Value = 0
    xsi.ApplyAction(action)
    xsi.DeleteObj(action)
Exemple #3
0
def importXtraRig(path, model):
    return

    # Check Input
    if not os.path.exists(path):
        gear.log("Invalid File", gear.sev_error)
        return

    # Import
    xrig_model = xsi.ImportModel(path, xsi.ActiveSceneRoot, False, None,
                                 model.Name + "_xrig")(1)
    xrig_org = xrig_model.FindChild(XRIG_ORG_NAME)
    xrig_prop = xrig_model.Properties(XRIG_PROP_NAME)
    xrig_cns = xrig_prop.Parameters("constraints").Value
    if not xrig_org or xrig_prop:
        gear.log("This is not a valid Extra Rig Model", gear.sev_error)
        xsi.DeleteObj("B:" + xrig_model.Name)
        return

    # Merging rig
    model.AddChild(xrig_org)

    # Retrieve Groups
    for xrig_group in xrig_model.Groups:
        group = model.Groups(xrig_group.Name)
        if not group:
            group = model.AddGroup(None, xrig_group.Name)
        group.AddMember(xrig_group.Members)

    xsi.DeleteObj("B:" + xrig_model.Name)

    ## TODO : IMPORT CONSTRAINT !!!
    ## TODO : IMPORT PARAMETERS AND CONNECTION !!!
    '''
    # Reconnect Controls
    oExtraControls = oExtraRig.Properties("anim_ctrl")
    oAnimCtrl = dynDispatch(oModel.Properties("anim_ctrl"))
    aSkipParameters = ["Debug", "Layout", "Logic", "LayoutLanguage"]
    for oParam in oExtraControls.Parameters:
        if oParam.Name in aSkipParameters:
            continue
        oAnimCtrl.AddProxyParameter(oParam, oParam.Name, oParam.Name)

    # Layout
    sLayout = "\r\noLayout.AddTab('ExtraRig');\r\n" + oExtraControls.Parameters("Layout").Value
    oAnimCtrl.Parameters("Layout").Value += sLayout
    
    # Retrive Constrains
    sXmlPath = sPath.replace(".emdl", ".xml")
    if os.path.exists(sXmlPath):
        xsi.gImportSkin(oExtraRig.Children, sXmlPath, True)
    '''

    return
Exemple #4
0
def getObjectDefinitions(path, inputs, ui=False):

    items, xml_objs = getObjectItems(path)

    objects = []
    for obj in inputs:
        if obj.Type in ["pntSubComponent"]:
            objects.append(obj.SubComponent.Parent3DObject)
        else:
            objects.append(obj)

    # -----------------------------------------------------
    # Check if we need the UI
    defs = {}
    if ui:
        if not [False for obj in objects if obj.Name not in items]:
            ui = False
        else:
            prop = xsi.ActiveSceneRoot.AddProperty("CustomProperty", False,
                                                   "ImportEnvelope")
            layout = prop.PPGLayout

            layout.AddGroup("Select Object Reference")

            params = {}
            for obj in objects:
                if obj.Name in items:
                    param = prop.AddParameter3("def_%s" % obj.Name, c.siString,
                                               obj.Name)
                else:
                    param = prop.AddParameter3("def_%s" % obj.Name, c.siString,
                                               "0")

                params[obj.name] = param

                layout.AddEnumControl(param.ScriptName, items, obj.Name,
                                      c.siControlCombo)

            layout.EndGroup()

            rtn = xsi.InspectObj(prop, "", "Import Envelope", c.siModal, False)

            for obj in objects:
                if params[obj.Name].Value != "0":
                    defs[obj.Name] = xml_objs[params[obj.Name].Value]

            xsi.DeleteObj(prop)

            if rtn:
                return False

    if not ui:
        for obj in objects:
            if obj.Name in xml_objs.keys():
                defs[obj.Name] = xml_objs[obj.Name]
            else:
                gear.log("No defintion found for %s" % obj.Name,
                         gear.sev_warning)

    return defs
Exemple #5
0
def createSymmetryMappingTemplate(in_deformers):

    deformers = XSIFactory.CreateObject("XSI.Collection")
    deformers.AddItems(in_deformers)

    temp_mesh = deformers(0).Model.AddGeometry("Sphere", "MeshSurface",
                                               "TempMesh")
    temp_mesh.ApplyEnvelope(deformers, False, False)

    # Create Mapping Template
    mapTemplate = xsi.CreateSymmetryMappingTemplate(temp_mesh, False, 0, False)

    for deformer in deformers:

        # Skip effectors
        if deformer.Type == "eff":
            continue

        sym_deformers = deformer.Model.FindChild(
            uti.convertRLName(deformer.Name))
        if not sym_deformers or sym_deformers.IsEqualTo(deformer):
            continue

        xsi.AddMappingRule(mapTemplate, deformer.Name, sym_deformers.Name,
                           xsi.GetNumMappingRules(mapTemplate))

    xsi.DeleteObj(temp_mesh)

    return mapTemplate
def gear_GuideToolsUI_import_OnClicked():

    if not os.path.exists(PPG.templateList.Value):
        return

    parent = xsi.Selection(0)
    if parent is not None and not parent.IsClassOf(c.siX3DObjectID):
        gear.log("Invalid Parent Selected", gear.sev_error)
        return

    if parent is not None:
        if parent.Type == "#model":
            target_model = parent
        else:
            target_model = parent.Model

        if not target_model.Properties("options"):
            gear.log("Invalid Parent Selected", gear.sev_error)
            return

    # import guide
    rg = RigGuide()
    model = rg.importFromXml(PPG.templateList.Value)

    if parent is not None:
        for child in model.children:
            if child.Name not in ["controlers_org"]:
                parent.AddChild(child)

        for group in model.Groups:
            if target_model.Groups(group.Name):
                target_model.Groups(group.Name).AddMember(group.Members)

        xsi.DeleteObj(model)
Exemple #7
0
def gear_newPose_Execute():
    if xsi.ActiveSceneRoot.Properties("gear_newPoseProp"):
        xsi.DeleteObj(xsi.ActiveSceneRoot.Properties("gear_newPoseProp"))

    prop = xsi.ActiveSceneRoot.AddProperty("gear_newPoseProp", False, "gear_newPoseProp")


    ds.inspect(prop, 350, 150)
Exemple #8
0
def gear_OpenRenamer_Execute():

    if xsi.ActiveSceneRoot.Properties("gear_Renamer"):
        xsi.DeleteObj(xsi.ActiveSceneRoot.Properties("gear_Renamer"))

    prop = xsi.ActiveSceneRoot.AddProperty("gear_Renamer", False, "gear_Renamer")

    dis.inspect(prop, 550, 450)
Exemple #9
0
def exportXtraRig(path, model):
    return

    # Check Input
    if not os.path.exists(path):
        gear.log("Invalid File", gear.sev_error)
        return

    xrig_org = xrig_model.FindChild(XRIG_ORG_NAME)
    if not xrig_org or xrig_prop:
        gear.log("This is not a valid Extra Rig Model", gear.sev_error)
        xsi.DeleteObj("B:" + xrig_model.Name)
        return

    # Create New Extra Rig Model
    xrig_model = model.AddModel(xrig_org, model.Name + "_xrig")

    # Groups
    for child in xrig_model.FindChildren():
        for group in model.Groups:
            if group.IsMember(child):
                xrig_group = xrig_model.Groups(group.Name)
                if not xrig_model.Groups(group.Name):
                    xrig_group = xrig_model.AddGroup(None, group.Name)
                xrig_group.AddMember(child)

    ## TODO : EXPORT CONSTRAINT !!!

    xrig_prop = xrig_model.AddProperty("Custom Property", False,
                                       XRIG_PROP_NAME)
    pCns = xrig_prop.AddParameter3("constraints", c.siString, "")
    '''   
    xmldom.setOptions("X3DObject_children":False,
                      "X3DObject_primitive":False,
                      "X3DObject_kinematics":True,
                      "X3DObject_properties":False)
    '''

    ## TODO : EXPORT PARAMETERS AND CONNECTIONS !!!

    # Export Model
    xsi.ExportModel(xrig_model, path)

    # Restore rig
    model.AddChild(xrig_org)
    xsi.DeleteObj("B:" + xrig_model.FullName)
def gear_MirrorAnimation_Execute():  # controlers

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return
    ## Miquel Shed added:
    else:
        controlers = XSIFactory.CreateActiveXObject("XSI.Collection")
        controlers.AddItems(xsi.Selection)
    ##end of the addition

    # Get First and Last Frame
    frames = fcv.getFirstAndLastKey(controlers)
    if not frames:
        gear.log("No Key on selection, cannot perform mirror animation",
                 gear.sev_error)
        return

    # UI
    ui_prop = xsi.ActiveSceneRoot.AddProperty("CustomProperty", False,
                                              "Mirror Animation")
    pOffset = ui_prop.AddParameter3("offset", c.siInt4, 0, None, None, False,
                                    False)
    pConsiderTime = ui_prop.AddParameter3("considerTime", c.siBool, False,
                                          None, None, False, False)
    pFrameIn = ui_prop.AddParameter3("frameIn", c.siInt4, frames[0], None,
                                     None, False, False)
    pFrameOut = ui_prop.AddParameter3("frameOut", c.siInt4, frames[1], None,
                                      None, False, False)

    layout = ui_prop.PPGLayout
    layout.AddGroup("Options")
    layout.AddItem(pOffset.ScriptName, "Offset")
    layout.AddItem(pConsiderTime.ScriptName, "Consider Time")
    layout.AddRow()
    layout.AddItem(pFrameIn.ScriptName, "Frame In")
    layout.AddItem(pFrameOut.ScriptName, "Frame Out")
    layout.EndRow()
    layout.EndGroup()

    rtn = xsi.InspectObj(ui_prop, "", "Mirror Animation", c.siModal, False)

    frame_offset = pOffset.Value
    considerTime = pConsiderTime.Value
    frame_in = pFrameIn.Value
    frame_out = pFrameOut.Value

    xsi.DeleteObj(ui_prop)

    if rtn:
        return

    # Mirror
    ani.mirror(controlers, True, frame_offset, considerTime, frame_in,
               frame_out)

    return
Exemple #11
0
def gear_prefPoseLib_Execute():

    if xsi.ActiveSceneRoot.Properties("gear_prefPoseLibProp"):
        xsi.DeleteObj(xsi.ActiveSceneRoot.Properties("gear_prefPoseLibProp"))

    prop = xsi.ActiveSceneRoot.AddProperty("gear_prefPoseLibProp", False, "gear_prefPoseLibProp")


    ds.inspect(prop, 550, 200)
Exemple #12
0
def gear_selectionSetsCmd_Execute():
    if xsi.ActiveSceneRoot.Properties("gear_selectionSets"):
        xsi.DeleteObj(xsi.ActiveSceneRoot.Properties("gear_selectionSets"))

    oScene = xsi.ActiveProject.ActiveScene

    prop = xsi.ActiveSceneRoot.AddProperty("gear_selectionSets", False,
                                           "gear_selectionSets")

    dis.inspect(prop, 410, 525)
def gear_OpenWireframe_Execute():

    if xsi.ActiveSceneRoot.Properties("gear_Wireframe"):
        prop = xsi.ActiveSceneRoot.Properties("gear_Wireframe")
        xsi.DeleteObj(prop)

    prop = xsi.ActiveSceneRoot.AddProperty("gear_Wireframe", False,
                                           "gear_Wireframe")

    dis.inspect(prop, 315, 345, 125, 75)
Exemple #14
0
def gear_poseLib_Execute():

    if xsi.ActiveSceneRoot.Properties("gear_poseLibManager"):
        xsi.DeleteObj(xsi.ActiveSceneRoot.Properties("gear_poseLibManager"))

    prop = xsi.ActiveSceneRoot.AddProperty("gear_poseLibManager", False, "gear_poseLibManager")

    if xsi.Preferences.Categories("gear_prefPoseLib"):
        listSize = xsi.GetValue("preferences.gear_prefPoseLib.list_Size")
    else:
        listSize = 500

    ds.inspect(prop, 300, 365 + listSize)
Exemple #15
0
def gear_CreateRollSplineKine_Execute():

    if xsi.Selection.Count < 2:
        gear.log("Select at least two objects", gear.sev_error)
        return

    controlers = [
        pri.addNull(obj, obj.Name + "_rot", obj.Kinematics.Global.Transform)
        for obj in xsi.Selection
    ]
    for ctl in controlers:
        pri.setNullDisplay(ctl, 2)

    # -----------------------------------------------------
    # UI
    prop = xsi.ActiveSceneRoot.AddProperty("CustomProperty", False,
                                           "SplineKineOptions")
    pDivision = prop.AddParameter3("division", c.siInt4, 10, 1, None, False,
                                   False)

    rtn = xsi.InspectObj(prop, "", "Spline Kine Options", c.siModal, False)

    div_count = pDivision.Value

    xsi.DeleteObj(prop)

    if rtn:
        return

    # -----------------------------------------------------
    # Create Parent property to connect the multiple operators parameters
    prop = controlers[0].Properties("gear_splinekine_options")
    if not prop:
        prop = controlers[0].AddProperty("CustomProperty", False,
                                         "gear_splinekine_options")
        prop.AddParameter3("resample", c.siBool, True, None, None, True, False)
        prop.AddParameter3("subdiv", c.siInt4, 10, 3, 50, True, False)
        prop.AddParameter3("absolute", c.siBool, False, None, None, True,
                           False)

    # -----------------------------------------------------
    for i in range(div_count):

        div = controlers[0].AddNull("div_%s" % i)
        pri.setNullDisplay(div, 4, .5)
        op = aop.sn_rollsplinekine_op(div, controlers, i / (div_count - 1.0))

        for s in ["resample", "subdiv", "absolute"]:
            op.Parameters(s).AddExpression(prop.Parameters(s))

    xsi.InspectObj(prop)
Exemple #16
0
def gear_PruneWeights_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    sel = xsi.Selection(0)

    if sel.Type in ["polymsh", "surfmsh", "crvlist"]:
        mesh = sel
        points = range(mesh.ActivePrimitive.Geometry.Points.Count)
#    elif sel.Type == "pntSubComponent":
#        mesh = sel.SubComponent.Parent3DObject
#        points = sel.SubComponent.ElementArray
    else:
        gear.log("Invalid selection", gear.sev_error)
        return

    # Get Envelope from object
    envelope_op = ope.getOperatorFromStack(mesh, "envelopop")
    if not envelope_op:
        gear.log("There is no envelope on selected mesh", gear.sev_error)
        return

    # PPG for Options
    prop = xsi.ActiveSceneRoot.AddProperty("CustomProperty", False,
                                           "gear_PruneWeights")
    pThreshold = prop.AddParameter3("Threshold", c.siDouble, .1, 0, None,
                                    False, False)
    pRemove = prop.AddParameter3("RemoveDeformers", c.siBool, True, None, None,
                                 False, False)

    layout = prop.PPGLayout
    layout.AddGroup("Prune")
    layout.AddItem(pThreshold.ScriptName, "Weights Threshold")
    layout.AddItem(pRemove.ScriptName, "Remove Unused Deformers")
    layout.EndGroup()

    rtn = xsi.InspectObj(prop, "", "Prune Weights", c.siModal, False)

    threshold = pThreshold.Value
    remove = pRemove.Value

    xsi.DeleteObj(prop)

    if rtn:
        return

    # Process
    env.pruneWeights(envelope_op, points, threshold, remove, True)
Exemple #17
0
def gear_poseLibManager_removePose_OnClicked():
    oSel = xsi.Selection(0)
    if oSel and oSel.Type == "customparamset":
        oParam = oSel.Parameters("poseEditList")
        if oParam:
            currPose = oSel.Parameters("poseEditList").Value.split(";")
            setName = oSel.Name
            xsi.DeleteObj(oSel)
            gear_poseLibManager_createPoseSet_OnClicked(currPose , setName, True)

        else:
            lm("The custom paramenter set selected is not a Pose Set", 4)
    else:
        lm("Select a custom paramenter set", 4)
Exemple #18
0
def setWireColor(in_mousebutton=0, color=0):

    colors = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0],
              [0.25098039215686274, 0.25098039215686274, 0.25098039215686274],
              [0.5019607843137255, 0.5019607843137255, 0.5019607843137255],
              [0.6078431372549019, 0.0, 0.1568627450980392],
              [0.0, 0.011764705882352941, 0.37254901960784315],
              [0.0, 0.0, 0.9921568627450981],
              [0.00392156862745098, 0.27450980392156865, 0.10196078431372549],
              [0.15294117647058825, 0.0, 0.2627450980392157],
              [0.7843137254901961, 0.0, 0.7803921568627451],
              [0.5372549019607843, 0.2784313725490196, 0.19215686274509802],
              [0.24313725490196078, 0.13333333333333333, 0.12156862745098039],
              [0.6039215686274509, 0.14509803921568626, 0.00392156862745098],
              [0.9921568627450981, 0.0, 0.0], [0.0, 1.0, 0.00392156862745098],
              [0.0, 0.2588235294117647, 0.6], [1.0, 1.0, 1.0],
              [1.0, 1.0, 0.00392156862745098],
              [0.38823529411764707, 0.8627450980392157, 1.0],
              [0.2588235294117647, 1.0, 0.6352941176470588],
              [1.0, 0.6862745098039216, 0.6901960784313725],
              [0.8901960784313725, 0.6745098039215687, 0.4745098039215686],
              [1.0, 1.0, 0.38431372549019605], [0.0, 0.6, 0.32156862745098036],
              [0.6274509803921569, 0.4117647058823529, 0.1843137254901961],
              [0.6235294117647059, 0.6313725490196078, 0.18823529411764706],
              [0.40784313725490196, 0.6274509803921569, 0.1843137254901961],
              [0.1843137254901961, 0.6313725490196078, 0.36470588235294116],
              [0.1843137254901961, 0.6235294117647059, 0.6274509803921569],
              [0.1843137254901961, 0.4, 0.6313725490196078],
              [0.43529411764705883, 0.1843137254901961, 0.6313725490196078],
              [0.6274509803921569, 0.1843137254901961, 0.40784313725490196]]

    if in_mousebutton:
        xsi.gear_setWireColorRange(in_mousebutton, colors[color])
    else:
        for obj in xsi.Selection:
            if obj.Properties("display") != None:
                if color:
                    xsi.SIMakeLocal(obj.Properties("display"),
                                    "siDefaultPropagation")
                else:
                    xsi.DeleteObj(obj.Properties("display"))

                obj.Properties('display').Parameters(12).PutValue2(
                    None, colors[color][0])
                obj.Properties('display').Parameters(13).PutValue2(
                    None, colors[color][1])
                obj.Properties('display').Parameters(14).PutValue2(
                    None, colors[color][2])
Exemple #19
0
def gear_selectionSets_deleteSet_OnClicked():
    from win32com.client import constants as c

    oList = PPG.pSetsList.Value.split(";")[0]
    for x in PPG.pSetsList.Value.split(";")[1:]:
        oList = oList + "," + x
    if len(oList) <= 1:
        xsi.LogMessage("Select a Set before Delete it", 4)
    else:
        oReturn = XSIUIToolkit.MsgBox(
            "Are you sure? Want to delete selected sets?", c.siMsgYesNo)
        if oReturn:
            xsi.DeleteObj(oList)
            gear_selectionSets_OnInit()
        else:
            lm("You cancel the delete operation.")
Exemple #20
0
def gear_MatchGeometry_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    target = xsi.Selection(0)
    if target.Type not in ["pntSubComponent", "polymsh", "surfmsh", "crvlist"]:
        gear.log("Invalid Selection, select a geometry or a point selection",
                 gear.sev_error)
        return

    # Get reference
    source = uit.pickSession(c.siGenericObjectFilter, "Pick Source Geometry")
    if not source:
        return

    # Get cluster
    if target.Type == "pntSubComponent":
        obj = target.SubComponent.Parent3DObject
        cls = obj.ActivePrimitive.Geometry.AddCluster(
            c.siVertexCluster, "gear_MatchGeometryOp_cls",
            target.SubComponent.ElementArray)
    else:
        obj = target
        cls = obj.ActivePrimitive.Geometry.AddCluster(
            c.siVertexCluster, "gear_MatchGeometryOp_cls")

    if source.Type != obj.Type:
        gear.log("Invalid Selection", gear.sev_error)
        xsi.DeleteObj(cls)
        return

    # Apply Operator
    op = XSIFactory.CreateObject("gear_MatchGeometryOp")

    op.AddIOPort(obj.ActivePrimitive)
    op.AddInputPort(source.ActivePrimitive)
    op.AddInputPort(cls)
    op.AddInputPort(obj.Kinematics.Global)
    op.AddInputPort(source.Kinematics.Global)

    op.Connect()

    xsi.InspectObj(op)

    return op
Exemple #21
0
def gear_GuideToolsUI_extractCtrl_OnClicked():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    # Get guide target
    guide_model = uit.pickSession(c.siModelFilter, "Pick Guide Model", False)
    if not guide_model:
      return

    if not guide_model.Properties("options"):
      gear.log("Invalid model", gear.sev_error)
      return

    guidectrl_org = guide_model.FindChild("controlers_org")
    guidectrl_grp = guide_model.Groups("controlers_grp")

    # Recreate Controlers -----------------------------
    for rig_ctl in xsi.Selection:

        if guide_model.FindChild(rig_ctl.Name):
            xsi.DeleteObj(guide_model.FindChild(rig_ctl.Name))

        guide_ctl = xsi.Duplicate(rig_ctl, 1,
                                          c.siCurrentHistory,
                                          c.siNoParent,
                                          c.siNoGrouping,
                                          c.siNoProperties,
                                          c.siNoAnimation,
                                          c.siNoConstraints,
                                          c.siNoSelection,
                                          c.siGlobalXForm)(0)

        #Get color from rig
        rR = rig_ctl.Properties('display').Parameters(12).GetValue2(None)
        rG = rig_ctl.Properties('display').Parameters(13).GetValue2(None)
        rB = rig_ctl.Properties('display').Parameters(14).GetValue2(None)
        uti.setColor(guide_ctl, [rR, rG,rB])
        guidectrl_org.AddChild(guide_ctl)
        guidectrl_grp.AddMember(guide_ctl)

        guide_ctl.Name = rig_ctl.Name
Exemple #22
0
def gear_prefPoseLibProp_setPreferences_OnClicked():

    if xsi.Preferences.Categories("gear_prefPoseLib"):
        xsi.SetValue("preferences.gear_prefPoseLib.global_Repo", PPG.global_Repo.Value, "")
        xsi.SetValue("preferences.gear_prefPoseLib.list_Size", PPG.list_Size.Value, "")
        xsi.SetValue("preferences.gear_prefPoseLib.control_groups_list", PPG.control_groups_list.Value, "")

    else:

        prop = xsi.ActiveSceneRoot.AddProperty("CustomProperty", False, "gear_prefPoseLib")
        prop.AddParameter3("global_Repo", c.siString, 0, 0, None, False, False)
        prop.AddParameter3("list_Size", c.siInt4, 500, 1, None, False, False)
        prop.AddParameter3("control_groups_list", c.siString, 0, 0, None, False, False)

        prop.global_Repo.Value = PPG.global_Repo.Value
        prop.list_Size.Value = PPG.list_Size.Value
        prop.control_groups_list.Value = PPG.control_groups_list.Value

        xsi.InstallCustomPreferences (prop, "gear_prefPoseLib")


    PPG.Close()
    if xsi.ActiveSceneRoot.Properties("gear_prefPoseLibProp"):
        xsi.DeleteObj(xsi.ActiveSceneRoot.Properties("gear_prefPoseLibProp"))
Exemple #23
0
def gear_RemoveUnusedEnvCls_Execute():

    # This method is named based and doesn't provide a perfect result but should work in most of the case.

    # Return All the Pnt Cluster from the active scene
    point_clusters = xsi.FindObjects(None,
                                     "{E4DD8E40-1E1C-11D0-AA2E-00A0243E34C4}")

    # Search for unused EnvelopWeightCls
    delete_objs = XSIFactory.CreateObject("XSI.Collection")
    for cls in point_clusters:

        if cls.Name.startswith("EnvelopWeightCls"):
            delete = True
            for prop in cls.Properties:
                if prop.Type == "envweights":
                    delete = False

            if delete:
                delete_objs.Add(cls)

    # Delete
    if delete_objs.Count:
        xsi.DeleteObj(delete_objs)
Exemple #24
0
def gear_SplitShapeKey_Execute():

    if not xsi.Selection.Count:
        gear.log("Select shape keys", gear.sev_error)
        return

    shapes = [shape for shape in xsi.Selection if shape.Type in ["clskey"]]
    if not shapes:
        return

    cls = shapes[0].Parent
    mesh = cls.Parent3DObject
    geo = mesh.ActivePrimitive.Geometry
    clusters = geo.Clusters

    # UI
    prop = xsi.ActiveSceneRoot.AddProperty("Custom_parameter_list", False,
                                           "gear_SplitShapeKey")

    pLPrefix = prop.AddParameter3("LPrefix", c.siString, "L_", None, None,
                                  False, False)
    pRPrefix = prop.AddParameter3("RPrefix", c.siString, "R_", None, None,
                                  False, False)
    pRCluster = prop.AddParameter3("RCluster", c.siInt4, -1, -1,
                                   clusters.Count - 1, False, False)
    pLCluster = prop.AddParameter3("LCluster", c.siInt4, -1, -1,
                                   clusters.Count - 1, False, False)
    pCCluster = prop.AddParameter3("CCluster", c.siInt4, -1, -1,
                                   clusters.Count - 1, False, False)

    clusters_items = ["Auto Detect Points", -1]
    for i, cls in enumerate(clusters):
        clusters_items.append(cls.Name)
        clusters_items.append(i)

    # Layout
    layout = prop.PPGLayout
    layout.Clear()

    layout.AddTab("General")
    layout.AddGroup("Prefix")
    layout.AddRow()
    layout.AddItem(pRPrefix.ScriptName, "Right")
    layout.AddItem(pLPrefix.ScriptName, "Left")
    layout.EndRow()
    layout.EndGroup()

    layout.AddGroup("Clusters")
    layout.AddEnumControl(pRCluster.ScriptName, clusters_items, "Right Points",
                          c.siControlCombo)
    layout.AddEnumControl(pLCluster.ScriptName, clusters_items, "Left Points",
                          c.siControlCombo)
    layout.AddEnumControl(pCCluster.ScriptName, clusters_items,
                          "Center Points", c.siControlCombo)
    layout.EndGroup()

    # Inspect
    rtn = xsi.InspectObj(prop, "", "Split Shape Key", c.siModal, False)

    # Return Values
    if pRCluster.Value == -1:
        r_points = sha.getPoints(geo, "R")
    else:
        r_points = clusters(pRCluster.value - 1).Elements.Array

    if pLCluster.Value == -1:
        l_points = sha.getPoints(geo, "L")
    else:
        l_points = clusters(pLCluster.value - 1).Elements.Array

    if pCCluster.Value == -1:
        c_points = sha.getPoints(geo, "C")
    else:
        c_points = clusters(pCCluster.value - 1).Elements.Array

    r_prefix = pRPrefix.Value
    l_prefix = pLPrefix.Value

    xsi.DeleteObj(prop)

    if rtn:
        return

    # Process
    for shape in shapes:
        sha.createHalfShape(shape, c_points, l_prefix, r_points)
        sha.createHalfShape(shape, c_points, r_prefix, l_points)
Exemple #25
0
def mirror(controlers=xsi.Selection,
           animation=False,
           frame_offset=0,
           considerTime=False,
           frame_in=0,
           frame_out=0):

    if not animation:
        source_type = 1
        considerTime = False
        frame_offset = 0
    else:
        source_type = 6

    params = getKeyableParameters(controlers)

    # Avoid having the parameter and its proxy in the collection
    # Curiosly, XSI can store the fcurves of the parameter and its proxy separatly
    # We get weird result when applying the action
    key_params = XSIFactory.CreateObject("XSI.Collection")
    key_params.Unique = True
    for param in params:
        if param.Type == "ProxyParameter":
            key_params.Add(param.MasterParameter)
        else:
            key_params.Add(param)

    if not key_params.Count:
        gear.log("No Keyable Parameter on Selection", gear.sev_error)
        return

    # Get all keys if considerTime is False
    if not considerTime and animation:
        frame_in, frame_out = fcu.getFirstAndLastKey(controlers)

    # Get Connexion Map --------------------
    model = controlers(0).Model
    cnx_prop = model.Properties(MIRROR_PROP_NAME)
    if not cnx_prop:
        gear.log("There is no Mirror Cnx Template on this model",
                 gear.sev_error)
        return

    cnx_grid = cnx_prop.Parameters("CnxGridHidden").Value
    connections = par.getDictFromGridData(cnx_grid)

    # Actions ------------------------------
    # Store the Action
    if model.Sources("Temp_MirrorAction"):
        xsi.DeleteObj(model.Sources("Temp_MirrorAction"))

    action = xsi.StoreAction(model, key_params, source_type,
                             "Temp_MirrorAction", False, frame_in, frame_out,
                             considerTime, False, False, False)

    # Edit the stored Action
    for item in action.SourceItems:

        # skip sourceItems if not listed in the CnxMap
        if item.Target not in connections:
            continue

        # Change the target to mirror action
        target = connections[item.Target]
        item.Target = target[0]

        # Inverse the value of fcurve if necessary
        # The string version is to keep compatibility with previous version of XSI
        # When the gridata was only returning string
        if target[1] in [True, "True"]:
            invertSource(item.Source)

    xsi.ApplyAction(action, model, True, frame_in + frame_offset,
                    frame_out + frame_offset, False)
    xsi.DeleteObj(action)

    return
Exemple #26
0
def gear_newPoseProp_saveNewPose_OnClicked():


    #Check if the name is valid
    oName = PPG.parPoseName.Value
    if not  oName.isalnum():
        lm("The name is not valid, use alphanumeric characters only ", 2)
    else:
        #Check is something is selected
        oSel = xsi.Selection
        if oSel.Count:
            #Construt the path
            userName = os.environ.get( "USERNAME" )
            #Global Path
            if PPG.parRepo.Value == "Global":
                if xsi.Preferences.Categories("gear_prefPoseLib"):
                    globalPath = Application.GetValue("preferences.gear_prefPoseLib.global_Repo")
                else:
                    globalPath = "Ops! you forget to set the preferences"
                    userPath = False

                if  os.path.isdir(globalPath):
                    userPath = os.path.join(globalPath, userName)
                    if not os.path.isdir(userPath):
                        os.makedirs(userPath)

                else:
                    lm("Global Path preferences are not set correctly. Looks like the folder: " + globalPath +" Doesn't exist.", 4 )

            #Current DB user path
            else:
                currentProject = xsi.ActiveProject2.Path
                currentPosePath = os.path.join(currentProject, "PoseLib")
                if not os.path.isdir(currentPosePath):
                    os.makedirs(currentPosePath)
                    lm("New folder for poses in the current datebase (DB) was created: " + currentPosePath )

                userPath = os.path.join(currentPosePath, userName)
                if not os.path.isdir(userPath):
                    os.makedirs(userPath)

            if userPath:
                oModel = oSel(0).Model
                modName = oModel.Name.split("_")[0]
                #Check if the pose exist and ask for overwrite
                oReturn = 6 # is the return value fo "yes" in the msgBox. We use it as default.
                if os.path.isdir(os.path.join(userPath, modName + "_" + oName)):
                   oReturn = XSIUIToolkit.MsgBox( "The pose exist!!. Do you want to overwrite it?", c.siMsgYesNo )
                else:
                    #Create folders if doesn't exist
                    os.makedirs(os.path.join(userPath, modName + "_" + oName))
                if oReturn == 6:
                    #Create xml pose
                    oModel = oSel(0).Model
                    root = xml.Element(oModel.Name)

                    # Function indentation ===============================
                    def indent(elem, level=0):
                        i = "\n" + level*" "
                        if len(elem):
                            if not elem.text or not elem.text.strip():
                                elem.text = i + " "
                            if not elem.tail or not elem.tail.strip():
                                elem.tail = i
                            for elem in elem:
                                indent(elem, level+1)
                            if not elem.tail or not elem.tail.strip():
                                elem.tail = i
                        else:
                            if level and (not elem.tail or not elem.tail.strip()):
                                elem.tail = i
                    # ===========================================


                    for oItem in oSel:
                        collection = XSIFactory.CreateActiveXObject( "XSI.Collection" )

                        collection.AddItems( oItem )

                        oKeyable = collection.FindObjectsByMarkingAndCapabilities( None, c.siKeyable )

                        child = xml.Element(oItem.Name)
                        root.append(child)

                        for oParam in oKeyable:
                            childParam = xml.Element(".".join(oParam.FullName.split(".")[2:]))
                            childParam.attrib["Value"] = str(oParam.Value)
                            #childParam.attrib["scriptName"] = str(oParam.ScriptName)
                            child.append(childParam)

                    indent(root)
                    posePath = os.path.join(userPath, modName +  "_" + oName, oName + ".xml")
                    file = open(posePath, "w")

                    xml.ElementTree(root).write(file)

                    file.close()

                    #Capture the image
                    currFrame = xsi.ActiveProject.Properties("Play Control").Parameters("Current").Value

                    oViewportCapture = xsi.Dictionary.GetObject("ViewportCapture")


                    xsi.SetValue("Views.view*.*Camera.camvis.gridaxisvis", False, "")
                    xsi.SetValue("Views.view*.*Camera.camvis.constructionlevel", False, "")
                    xsi.SetValue("*Camera.camvis.gridaxisvis", False, "")
                    xsi.SetValue("*Camera.camvis.constructionlevel", False, "")

                    oViewportCapture.NestedObjects[0].PutValue2(None, os.path.join(userPath, modName + "_" + oName, oName + ".jpg"))  # path FileName
                    oViewportCapture.NestedObjects[1].PutValue2(None, "(fn)(ext)")  # frame Padding
                    oViewportCapture.NestedObjects[2].PutValue2(None, "75")  # Width
                    oViewportCapture.NestedObjects[3].PutValue2(None, "75")  # Height
                    oViewportCapture.NestedObjects[4].PutValue2(None, "1")  # Scale Factor
                    oViewportCapture.NestedObjects[5].PutValue2(None, "True")  # user pixel ratio
                    oViewportCapture.NestedObjects[6].PutValue2(None, "1.0")  # pixel ratio
                    oViewportCapture.NestedObjects[10].PutValue2(None, currFrame) # Start Frame
                    oViewportCapture.NestedObjects[11].PutValue2(None, currFrame) # End Frame
                    oViewportCapture.NestedObjects[12].PutValue2(None, "False")  # Launch Flipbook

                    xsi.CaptureViewport( -1, False )

                    xsi.SetValue("Views.view*.*Camera.camvis.gridaxisvis", True, "")
                    xsi.SetValue("Views.view*.*Camera.camvis.constructionlevel", True, "")
                    xsi.SetValue("*Camera.camvis.gridaxisvis", True, "")
                    xsi.SetValue("*Camera.camvis.constructionlevel", True, "")

                    #Create the miniSynoptic
                    imageName = oName +".jpg"
                    oDate =  strftime("%a, %d %b %Y %H:%M:%S")
                    synCretor(posePath, imageName,  oName, userName, oDate, oModel.Name)
                else:
                    lm("Creation cancelled", 2)
            else:
                lm("Set preferences before save poses in the global repo", 2)
        else:
            lm("Nothing selected, Pose can not be stored", 2)

    PPG.Close()
    if xsi.ActiveSceneRoot.Properties("gear_newPoseProp"):
        xsi.DeleteObj(xsi.ActiveSceneRoot.Properties("gear_newPoseProp"))
Exemple #27
0
def gear_MoveShapeKey_Execute():

    if not xsi.Selection.Count:
        gear.log("Select shape keys", gear.sev_error)
        return

    shapes = [shape for shape in xsi.Selection if shape.Type in ["clskey"]]
    if not shapes:
        return

    cls = shapes[0].Parent
    geo = cls.Parent
    clusters = geo.Clusters

    # UI
    prop = xsi.ActiveSceneRoot.AddProperty("Custom_parameter_list", False,
                                           "gear_MoveShapeKey")
    pDuplicate = prop.AddParameter3("duplicate", c.siBool, True, None, None,
                                    False, False)
    pClusters = prop.AddParameter3("clusters", c.siInt4, -1, 0,
                                   clusters.Count - 1, False, False)

    clustersItems = ["New Cluster", -1]
    for i, cls in enumerate(clusters):
        clustersItems.append(cls.Name)
        clustersItems.append(i)

    layout = prop.PPGLayout
    layout.Clear()
    layout.AddTab("General")
    layout.AddGroup("Move Shape Key Option")
    item = layout.AddItem(pDuplicate.ScriptName, "Duplicate")
    item = layout.AddEnumControl(pClusters.ScriptName, clustersItems,
                                 "Move to", c.siControlCombo)
    layout.EndGroup()

    # Inspect
    rtn = xsi.InspectObj(prop, "", "Move Shape Key", c.siModal, False)

    # Return values
    duplicate = pDuplicate.Value
    cluster_index = pClusters.Value

    xsi.DeleteObj(prop)

    if rtn:
        return

    # Create or get target cluster
    if cluster_index == -1:
        target_cluster = geo.AddCluster(c.siVertexCluster, cls.Name + "_Copy",
                                        cls.Elements.Array)
    else:
        target_cluster = clusters(cluster_index)

    # Duplicate Shape key
    for shape in shapes:
        sha.duplicateShapeKey(shape, target_cluster)

    # Delete original
    if not duplicate:
        xsi.DeleteObj(shapes)
Exemple #28
0
    def finalize(self):

        # Properties --------------------------------------
        self.plog.log("Filling layout and logic")
        self.ui.fillLayoutAndLogic()

        # Groups ------------------------------------------
        self.plog.log("Creating groups")
        # Retrieve group content from components
        for name in self.componentsIndex:
            component = self.components[name]
            for name, objects in component.groups.items():
                self.addToGroup(objects, name)

        # Creating all groups
        for name, objects in self.groups.items():
            collection = XSIFactory.CreateObject("XSI.Collection")
            collection.AddItems(objects)
            self.groups[name] = self.model.AddGroup(collection, name + "_grp")

        # Hidden
        if self.options["setHidden"]:
            self.groups["hidden"].Parameters("viewvis").Value = 0
            self.groups["hidden"].Parameters("rendvis").Value = 0

        # Unselectable
        if self.options["setUnselectable"]:
            self.groups["unselectable"].Parameters("selectability").Value = 0

        # Deformers
        if self.options["setDeformers"]:
            self.groups["deformers"].Parameters("viewvis").Value = 0
            self.groups["deformers"].Parameters("rendvis").Value = 0

        # Geometries
        if self.options["setGeometries"]:
            self.groups["geometries"].Parameters("selectability").Value = 0
            prop = self.groups["geometries"].AddProperty("GeomApprox")
            par.addExpression(prop.Parameters("gapproxmosl"), self.pOGLLevel)

        # Skin --------------------------------------------
        if self.options["addGeometry"]:
            self.plog.log("Applying skin")

            # Import geometry
            if self.options["geo_path"] and os.path.exists(
                    self.options["geo_path"]):
                geo_model = xsi.ImportModel(self.options["geo_path"],
                                            xsi.ActiveSceneRoot, False,
                                            None)(1)

                geo_objects = geo_model.FindChildren()

                self.model.AddChild(geo_model.children)
                for group in geo_model.Groups:
                    target_group = pri.createOrReturnGroup(
                        self.model, group.Name)
                    target_group.AddMember(group.Members)
                xsi.DeleteObj(geo_model)

                # Apply skin
                if self.options["skin_path"] and os.path.exists(
                        self.options["skin_path"]):
                    xml_objs = io.getObjectDefinitions(
                        self.options["skin_path"], geo_objects, False)

                    for obj in geo_objects:

                        if obj.Name not in xml_objs.keys():
                            continue

                        io.importSkin(xml_objs[obj.Name], obj)

        # Symmetry Mapping Template -----------------------
        if self.options["mode"] == 1:

            env.createSymmetryMappingTemplate(self.groups["deformers"].Members)

            for geo in self.groups["geometries"].Members:
                if geo.Type == "polymsh":
                    xsi.CreateSymmetryMap("SymmetryMap", geo, "Symmetry Map")

        # Mirror Animation Template -----------------------
        if self.options["mode"] == 0:
            cnx_prop = ani.createMirrorCnxTemplate(self.model)
            for count, compName in enumerate(self.componentsIndex):
                component = self.components[compName]
                inversed_params = component.inv_params.GetAsText().split(",")
                for ctl in component.controlers:
                    ani.addMirroringRule(ctl, cnx_prop, inversed_params, True)

        # Reset Pose --------------------------------------
        self.plog.log("Creating rest pose")
        controlers = XSIFactory.CreateObject("XSI.Collection")
        for group in self.model.Groups:
            if group.Name.startswith("controlers"):
                controlers.AddItems(group.Members)

        keyableParams = controlers.FindObjectsByMarkingAndCapabilities(
            None, c.siKeyable)
        xsi.StoreAction(self.model, keyableParams, 1, "reset", False)

        # Isolate and popup -------------------------------
        if self.options["isolateResult"]:
            xsi.SelectObj(self.model, "BRANCH")
            xsi.IsolateSelected(False, -1)
            xsi.DeselectAll()

        if self.options["popUpControls"]:
            xsi.InspectObj(self.ui.anim_prop)