def create_json_dictionary(self, rig_component):
        if self.get_control_info(self.get_driver_object()):
            addon_dict = super(Attribute_Translator, self).create_json_dictionary(rig_component)
        else:
            addon_node = self.network['addon'].node
            addon_info = v1_shared.shared_utils.get_class_info(addon_node.component_type.get())
            addon_dict = {'module': get_first_or_default(addon_info), 'type': get_index_or_default(addon_info,1), 'driven_name': self.get_driver_object().stripNamespace(), 
                          'target_type': addon_node.target_type.get(), 'target_data': addon_node.target_data.get()}

        control_joint = self.get_target_object()
        attribute_channel_dict = {}
        for attr in ['tx', 'ty', 'tz']:
            for condition_node in set(pm.listConnections(getattr(control_joint, attr), s=False, d=True, type='condition')):
                attribute_channel_dict.setdefault(attr, {})
                multiply_node = get_first_or_default(pm.listConnections(condition_node, s=False, d=True, type='multiplyDivide'))
                multiplier_value = multiply_node.input2X.get()
        
                is_positive = True if multiplier_value > 0 else False
                multiplier = abs(multiplier_value)

                attribute = get_first_or_default(pm.listConnections(multiply_node, s=False, d=True, p=True, type='joint'))
                attribute_name = get_last_or_default(attribute.name().split('.'))
                attribute_channel_dict[attr][is_positive] = attribute_name
                attribute_channel_dict[attr]['multiplier'] = multiplier

        addon_dict['channel_dict'] = attribute_channel_dict

        return addon_dict
def get_control_vars_strings(rig_control):
    '''
    Returns visibility if false and any locked transform attributes
    '''
    modified_dict = {}
    if not rig_control.visibility.get():
        modified_dict["visibility"] = False
    for attr_str in maya_utils.node_utils.TRANSFORM_ATTRS:
        attr = getattr(rig_control, attr_str)
        if attr.isLocked():
            attr_name = attr.name().rsplit(".", 1)[-1]
            modified_dict[attr_name+".isLocked"] = True

    control_property = metadata.meta_properties.get_property(rig_control, metadata.meta_properties.ControlProperty)
    selection_lock = control_property.get("locked")
    if selection_lock:
        modified_dict["locked.selectionLock"] = True

    orient_constraint = get_first_or_default(rig_control.rotateX.listConnections(s=True, d=False))
    if orient_constraint and type(orient_constraint) != pm.nt.OrientConstraint:
        orient_constraint = get_first_or_default(orient_constraint.listConnections(s=True, d=False, type='orientConstraint'))
    if orient_constraint:
        rotate_info = get_constraint_info(orient_constraint, rig_control)
        if rotate_info:
            modified_dict["orientConstraint.constraint"] = rotate_info

    point_constraint = get_first_or_default(rig_control.translateX.listConnections(s=True, d=False))
    if point_constraint and type(point_constraint) != pm.nt.OrientConstraint:
        point_constraint = get_first_or_default(point_constraint.listConnections(s=True, d=False, type='pointConstraint'))
    if point_constraint:
        point_info = get_constraint_info(point_constraint, rig_control)
        if point_info:
            modified_dict["pointConstraint.constraint"] = point_info

    return modified_dict
Example #3
0
 def toggle_ribbon_visibility(self, c_rig_button, event_args):
     world_grp = get_first_or_default([
         x for x in self.network['component'].group.getChildren()
         if "World_grp" in x.name()
     ])
     if world_grp:
         ribbon_surface = get_first_or_default([
             x for x in world_grp.getChildren(type='transform')
             if x.getShape() and type(x.getShape()) == pm.nt.NurbsSurface
         ])
         ribbon_surface.visibility.set(not ribbon_surface.visibility.get())
Example #4
0
def save_skin_weights_with_dialog(character_grp):
    character_node = get_first_or_default(
        character_grp.affectedBy.listConnections(type='network'))
    content_path = v1_shared.file_path_utils.relative_path_to_content(
        character_node.root_path.get())

    start_dir = content_path if os.path.exists(
        content_path) else os.path.expanduser("~")
    load_path = get_first_or_default(
        pm.fileDialog2(ds=1, fm=0, ff="JSON - .json (*.json)", dir=start_dir))
    if load_path:
        save_skin_weights(character_grp, load_path)
Example #5
0
def create_face_morph_rig(root_joint, mesh_list):
    '''
    Create a blend shape for every given mesh from every 10th frame from a Maya scene

    Args:
        root_joint (PyNode): Maya scene joint for the root of a skeleton
        mesh_list (list<PyNode>): List of Maya scene mesh objects to create blend shapes for

    Returns:
        (list<PyNode>). List of meshes driven by the created blend shapes
    '''
    scene_objects = pm.ls(assemblies=True)
    target_list = []
    for mesh in mesh_list:
        pm.currentTime(0)

        target = get_first_or_default(pm.duplicate(mesh))
        target.rename(mesh.name() + "_morph")
        for attr in target.listAttr():
            attr.unlock()
        target.setParent(None)
        target_list.append(target)

        blend_shape_list = []
        attr_list = []
        start_frame = int(pm.playbackOptions(q=True, ast=True))
        end_frame = int(pm.playbackOptions(q=True, aet=True))
        for frame in xrange(start_frame, end_frame + 10, 10):
            pm.currentTime(frame)
            attr_list = pm.listAttr(root_joint,
                                    ud=True,
                                    k=True,
                                    l=False,
                                    v=True)
            for attr in attr_list:
                attr_obj = getattr(root_joint, attr)
                if get_first_or_default(
                        pm.keyframe(attr_obj, q=True, ev=True, t=frame)) == 1:
                    blend_shape = get_first_or_default(pm.duplicate(mesh))
                    blend_shape.rename(attr)
                    for attr in blend_shape.listAttr():
                        attr.unlock()
                    blend_shape.setParent(None)
                    blend_shape_list.append(blend_shape)

        blend_shape = get_first_or_default(
            pm.blendShape(blend_shape_list, target))
        #pm.delete(blend_shape_list)

    #pm.delete(scene_objects)

    return target_list
Example #6
0
    def bind_chain_process(self, rigging_chain, ik_solved_chain,
                           skeleton_chain, control_chain, additive):
        rigging.skeleton.force_set_attr(rigging_chain[-1].visibility, False)
        rigging.skeleton.force_set_attr(ik_solved_chain[-1].visibility, False)

        # re-zero for binding so we can do mo=True without capturing a random rotation from the animation
        rigging.skeleton.zero_character(self.skel_root, ignore_rigged=False)
        rigging.rig_base.Component_Base.zero_all_rigging(
            self.network['character'])
        rigging.skeleton.zero_skeleton_joints(skeleton_chain)

        # Bind rigging and skeleton together
        ik_solved_chain = rigging.skeleton.sort_chain_by_hierarchy(
            ik_solved_chain)
        skeleton_chain = rigging.skeleton.sort_chain_by_hierarchy(
            skeleton_chain)

        character_settings = v1_core.global_settings.GlobalSettings(
        ).get_category(v1_core.global_settings.CharacterSettings)
        if character_settings.lightweight_rigging:
            rigging.constraints.bind_chains(ik_solved_chain[1:],
                                            skeleton_chain[1:],
                                            self.exclude,
                                            translate=False,
                                            additive=additive)
            rigging.constraints.bind_chains(ik_solved_chain[:1],
                                            skeleton_chain[:1],
                                            self.exclude,
                                            rotate=False,
                                            additive=additive)
            pm.orientConstraint(get_first_or_default(control_chain),
                                get_first_or_default(skeleton_chain),
                                mo=True)
        else:
            rigging.constraints.bind_chains(rigging_chain,
                                            skeleton_chain,
                                            self.exclude,
                                            additive=additive)
            rigging.constraints.bind_chains(ik_solved_chain[1:],
                                            rigging_chain[1:],
                                            self.exclude,
                                            translate=False)
            rigging.constraints.bind_chains(ik_solved_chain[:1],
                                            rigging_chain[:1],
                                            self.exclude,
                                            rotate=False)
            pm.orientConstraint(get_first_or_default(control_chain),
                                get_first_or_default(rigging_chain),
                                mo=True)
Example #7
0
def duplicate_animation(attr, anim_blend_rotate):
    '''
    Duplicate the animation connected to an attribute. If no animation layers are used retrun a duplicate of the animCurve
    object connected to the attribute.  If animation layers are used duplicate the anim blend node and all animation curves
    connected to it, and return the anim blend node.
    If anim_blend_rotate is passed in pass it straight through and don't duplicate anything.  This should only be passed in if 
    this code was already run on one rotate channel and all duplication is already done, so we just want to re-use the node
    from the previous run
    '''
    blend_type_list = [
        pm.nt.AnimBlendNodeAdditiveDL, pm.nt.AnimBlendNodeAdditiveRotation,
        pm.nt.AnimBlendNodeAdditiveScale
    ]

    anim_input_list = attr.listConnections(s=True, d=False)
    anim_blend_list = [
        x for x in anim_input_list if type(x) in blend_type_list
    ]

    anim_curve = get_first_or_default(
        attr.listConnections(type='animCurve', s=True, d=False))
    # If there's an animCurve connectino duplicate and return it
    return_output = pm.duplicate(anim_curve)[0] if anim_curve else None
    # If anim_blend_rotate was passed it return it through
    return_output = anim_blend_rotate if anim_blend_rotate else return_output

    # If the attr is controlled by an anim blend(layer) and we haven't already duplicated it's layer network
    # duplicate the anim blend node and all animCurve nodes connected to it
    if anim_blend_list and not anim_blend_rotate:
        return_output = pm.duplicate(get_first_or_default(anim_blend_list),
                                     ic=True)[0]
        anim_curve_list = return_output.listConnections(type='animCurve',
                                                        s=True,
                                                        d=False,
                                                        c=True)

        for anim_curve_tuple in anim_curve_list:
            connection_attr, anim_curve = anim_curve_tuple
            duplicate_curve = pm.duplicate(anim_curve)[0]
            duplicate_curve.output >> connection_attr
            if pm.objExists(anim_curve):
                pm.delete(anim_curve)

        pm.delete(anim_blend_list)

    if anim_curve and pm.objExists(anim_curve):
        pm.delete(anim_curve)

    return return_output
    def connect_ik_leg(self, c_rig_button, event_args):
        '''
        If the leg above the reverse foot is rigged in IK, this will connect the IK handle to the attachment control.
        If the leg is not rigged in IK this will do nothing.
        '''
        attachment_joint = self.network['attachment'].get_first_connection()
        control_list = self.network['controls'].get_connections()
        attachment_control = get_first_or_default(
            [x for x in control_list if "attach" in x.name()])

        leg_component_network = rigging.skeleton.get_rig_network(
            attachment_joint)
        if leg_component_network and "ik" in leg_component_network.get(
                'component_type'):
            leg_ik_component = rigging.rig_base.Component_Base.create_from_network_node(
                leg_component_network.node)
            overdriver_list = leg_ik_component.is_in_addon()
            if overdriver_list:
                for od in overdriver_list:
                    od.remove()

            ik_handle = leg_ik_component.get_control('ik_handle')
            leg_ik_component.switch_space(ik_handle,
                                          rigging.overdriver.Overdriver,
                                          [attachment_control])
    def rig_from_json(cls, component, addon_component_dict, created_rigging):
        '''

        '''
        if addon_component_dict.get('ctrl_key'):
            control_list = component.get_control_dict()[addon_component_dict['ctrl_key']]
            ordered_control_list = rigging.skeleton.sort_chain_by_hierarchy(control_list)
            control = ordered_control_list[int(addon_component_dict['ordered_index'])]
        else:
            control_name = addon_component_dict['driven_name']
            control = pm.PyNode(component.namespace + control_name) if pm.objExists(component.namespace + control_name) else None

        v1_core.v1_logging.get_logger().debug("Addon_Component rig_from_json - {0} - {1} - {2}".format(cls, control, component))

        target_string_list = addon_component_dict['target_type'].split(',')
        target_type = get_first_or_default(target_string_list)

        if control and target_type:
            if target_type == 'ctrl':  # rig control object
                target_data = rigging.rig_base.ControlInfo.parse_string(addon_component_dict['target_data'])
                target_component = created_rigging[target_data.side][target_data.region]
                
                target_control_list = target_component.get_control_dict()[target_data.control_type]
                target_ordered_control_list = rigging.skeleton.sort_chain_by_hierarchy(target_control_list)
                target_control = target_ordered_control_list[target_data.ordered_index]
            elif target_type == 'node':  # scene object
                target_control_name = component.namespace + addon_component_dict['target_data']
                target_control = pm.PyNode(target_control_name)
            
            addon_component = cls()
            addon_component.rig(component.network['component'].node, control, [target_control], addon_component_dict['channel_dict'])
        
            return addon_component
        return None
Example #10
0
    def get_target_object(self):
        control = self.network['controls'].get_first_connection()
        addon_target_set = set(pm.listConnections(control, s=False, d=True))
        joint_set = [x for x in addon_target_set if type(x) == pm.nt.Joint]
        addon_target = get_first_or_default([x for x in joint_set if x != control])

        return addon_target
Example #11
0
def remove_sub_frames(obj_list):
    '''
    Sets a key on every whole frame over the keyed range of all objects, then removes all subframe keys.

    Args:
        obj_list (list<PyNode>): List of all objects to remove sub frames on
    '''
    #pm.select(None)
    #for model_panel in pm.getPanel(type='modelPanel'):
    #    pm.isolateSelect(model_panel, state=True)
    #pm.refresh(su=True)

    try:
        key_frame_list = list(set(pm.keyframe(obj_list, q=True)))
        key_frame_list.sort()
        first_keyframe = get_first_or_default(key_frame_list)
        last_keyframe = get_last_or_default(key_frame_list)

        time_range = (int(first_keyframe), int(last_keyframe))
        current_time = pm.currentTime()
        for frame in xrange(time_range[0], time_range[1] + 1):
            pm.currentTime(frame)
            pm.setKeyframe(obj_list)
    except:
        pass
    finally:
        pm.refresh(su=False)
        for model_panel in pm.getPanel(type='modelPanel'):
            pm.isolateSelect(model_panel, state=False)

    pm.currentTime(current_time)
    pm.select(obj_list, r=True)

    for frame in [x for x in key_frame_list if x % 1 > 0]:
        pm.cutKey(obj_list, t=frame)
Example #12
0
    def __init__(self, character_node_name):
        self.process = System.Diagnostics.Process.GetCurrentProcess()
        self.ui = Freeform.Rigging.RegionEditor.RegionEditor(self.process)
        self.vm = self.ui.DataContext

        self.character_node = pm.PyNode(character_node_name)

        # Find All Regions from character
        character_network = metadata.network_core.MetaNode.create_from_node(self.character_node)
        jnt = character_network.get_downstream(metadata.network_core.JointsCore).get_first_connection('joint')
        skeleton_dict = rigging.skeleton.get_skeleton_dict(jnt)

        for side, region_dict in skeleton_dict.iteritems():
            for region, joint_dict in region_dict.iteritems():
                markup_properties = metadata.meta_properties.get_properties([pm.PyNode(joint_dict['root'].name())], metadata.meta_properties.RigMarkupProperty)
                markup = get_first_or_default([x for x in markup_properties if x.data['side'] == side and x.data['region'] == region])
                self.vm.AddRegion(side, region, markup.data.get('group'), joint_dict['root'].name(), joint_dict['end'].name(), 
                                  markup.data.get('com_object'), markup.data.get('com_region'), markup.data.get('com_weight'))

        self.vm.CharacterName = self.character_node.name()

        # Load Event Handlers
        self.vm.CloseWindowEventHandler += self.close

        self.vm.PickEventHandler += self.pick_from_scene
        self.vm.RemoveRegionEventHandler += self.remove_region
        self.vm.AddRegionEventHandler += self.add_region
        self.vm.RegionDataChangedEventHandler += self.data_changed
        self.vm.RootChangedEventHandler += self.root_changed
        self.vm.EndChangedEventHandler += self.end_changed
        self.vm.SelectionChangedEventHandler += self.ui_selection_changed
        self.vm.CheckSelectionEventHandler += self.check_for_rigging
        self.vm.MirrorFilteredRegionsHandler += self.mirror_filtered_regions
Example #13
0
def get_constraint_driver(constraint):
    '''
    Get the driver object from a constraint node

    Args:
        constraint (PyNode): The constraint scene node to query

    Returns:
        PyNode. The first object that is driving the constraint
    '''
    weight_attr_list = constraint.getWeightAliasList()
    index = 0
    highest_value = 0
    for i, weight_attr in enumerate(weight_attr_list):
        if weight_attr.get() > highest_value:
            highest_value = weight_attr.get()
            index = i

    constraint_type_list = [
        pm.nt.ParentConstraint, pm.nt.PointConstraint, pm.nt.OrientConstraint
    ]
    destination_connection_list = get_first_or_default(
        list(set(constraint.listConnections(s=False, d=True,
                                            type='transform'))))
    source_transform_list = [
        x for x in list(
            set(constraint.listConnections(s=True, d=False, type='transform')))
        if x != destination_connection_list
        and type(x) not in constraint_type_list
    ]

    source_transform = source_transform_list[index]

    return source_transform
    def load_data(self, data, obj, *args):
        '''
        Load Property MetaNode data from json

        Args:
            data (dictionary): json file dictionary to load from
            obj (PyNode): Maya scene object to load attributes onto
            args (args): Optional args
        '''
        data_dict = data.get(self.category)
        data_dict = data_dict if data_dict else {}
        for property_data in data_dict.itervalues():
            property_class = getattr(sys.modules[property_data['module']], property_data['type'])
            current_properties = metadata.meta_properties.get_properties_dict(obj)
            data = property_data['data']

            # If the property already exists with correct data update and move on
            if property_class in current_properties.keys():
                do_continue = False
                for prop in current_properties[property_class]:
                    if prop.compare(data):
                        prop.data = data
                        do_continue = True
                        break
                if do_continue:
                    continue

            if property_class == metadata.meta_properties.ExportProperty and property_class in current_properties.keys():
                get_first_or_default(current_properties[property_class]).data = data
            else:
                new_property = metadata.meta_properties.add_property(obj, property_class)
                new_property.data = data
Example #15
0
    def rig(self, component_node, control, object_space, attribute_list, use_global_queue = False, **kwargs):
        # Disable queue for this type
        use_global_queue = False

        if not super(Channel_Overdriver, self).rig(component_node, control, object_space, use_global_queue = use_global_queue, **kwargs):
            return False

        object_space = get_last_or_default(object_space)
        pm.parentConstraint(object_space, self.network['addon'].group, mo=True)

        addon_control = self.network['controls'].get_first_connection()
        pm.delete(addon_control.getShape())

        for attr in attribute_list:
            attr_name = attr.name().replace(attr.namespace(), '').replace(".", "_")
            addon_control.addAttr(attr_name, at=attr.type(), k=True, h=False, w=True)
            addon_control_attr = getattr(addon_control, attr_name)
            
            object_space.addAttr(attr_name, at=attr.type(), k=True, h=False, w=True)
            control_attr = getattr(object_space, attr_name)

            # If there's incoming animation re-connected it to our new attr
            anim_connection = get_first_or_default(pm.listConnections(attr, s=True, d=False, p=True))
            if anim_connection:
                anim_connection >> control_attr

            control_attr >> addon_control_attr
            addon_control_attr >> attr

            attr.lock()
Example #16
0
def character_setup_from_ue4(jnt):
    '''
    Setup an animation ready character from a UE4 exported animation.  UE4 exports need to be cleaned up before
    they're ready for the rigging system, joint orient is pushed onto rotation channels and no rotate orders
    are properly set

    Args:
        jnt (PyNode): Maya scene joint that's part of a skeleton imported from UE4
    '''
    character_network = freeform_utils.character_utils.characterize_skeleton(
        jnt, "ue_4_transfer")
    updater = versioning.character_version.CharacterUpdater(character_network)
    updater.update()

    content_path = v1_shared.file_path_utils.relative_path_to_content(
        character_network.node.root_path.get())

    file_list = []
    for (dirpath, dirnames, filenames) in os.walk(content_path):
        file_list.extend(filenames)
        break

    settings_file_name = get_first_or_default(
        [x for x in file_list if 'settings' in x])
    if settings_file_name:
        settings_file = os.path.join(content_path, settings_file_name)
        rigging.file_ops.load_settings_from_json(
            character_network.group, settings_file,
            rigging.settings_binding.Binding_Sets.ZERO_ORIENT_ALL)

    else:
        rigging.file_ops.load_settings_from_json_with_dialog(
            character_network.group,
            rigging.settings_binding.Binding_Sets.ZERO_ORIENT_ALL)
Example #17
0
    def build_template(self, vm, event_args):
        obj_list = pm.ls(sl=True)
        character_network = self.active_character

        if not character_network:
            character_node_list = metadata.network_core.MetaNode.get_all_network_nodes(
                metadata.network_core.CharacterCore)
            if len(character_node_list) == 1:
                character_node = get_first_or_default(character_node_list)
                character_network = metadata.network_core.MetaNode.create_from_node(
                    character_node)

        # If another tool hasn't set the active character, and there's more than 1 character in the scene, we'll use
        # user selection to determine which character to build rigging on.
        if not character_network:
            if obj_list:
                selected_obj = obj_list[0]
                character_network = metadata.network_core.MetaNode.get_first_network_entry(
                    selected_obj, metadata.network_core.CharacterCore)
                if not character_network:
                    pm.confirmDialog(
                        title="Not Part of a Character",
                        message=
                        "Select part of a character to build the template",
                        button=['OK'],
                        defaultButton='OK',
                        cancelButton='OK',
                        dismissString='OK')
            else:
                pm.confirmDialog(
                    title="Nothing Selected",
                    message="Select part of a character to build the template",
                    button=['OK'],
                    defaultButton='OK',
                    cancelButton='OK',
                    dismissString='OK')

        if character_network:
            joints_network = character_network.get_downstream(
                metadata.network_core.JointsCore)
            skeleton_dict = rigging.skeleton.get_skeleton_dict(
                joints_network.get_first_connection())

            side_list = [x for x in event_args.SideList]
            region_list = [x for x in event_args.RegionList]

            template_group = event_args.TemplateGroup
            template_settings_file = self.default_settings.get(template_group)
            namespace = character_network.node.namespace()
            if template_settings_file:
                rigging.skeleton.build_regions_from_skeleton_dict(
                    template_settings_file, skeleton_dict, namespace,
                    side_list, region_list)

            created_rigging = rigging.file_ops.load_from_json(
                character_network, event_args.FilePath, side_list, region_list)

            scene_tools.scene_manager.SceneManager().run_by_string(
                'UpdateRiggerInPlace')
            pm.select(obj_list)
Example #18
0
def update_ordered_index():
    '''
    Update the MetaNode graph to ensure all objects are the latest version
    '''
    try:
        update_list = [
            x for x in pm.ls(type='network')
            if 'ControlProperty' in x.meta_type.get()
            and not x.hasAttr('ordered_index')
        ]
        main_progress_bar = pm.mel.eval('$tmp = $gMainProgressBar')
        pm.progressBar(main_progress_bar,
                       edit=True,
                       beginProgress=True,
                       isInterruptable=True,
                       status='Updating Network...',
                       maxValue=len(update_list))

        for property_node in update_list:
            pm.addAttr(property_node, ln='ordered_index', at='short')

        for property_node in update_list:
            pm.progressBar(main_progress_bar, edit=True, step=1)
            control = get_first_or_default(
                property_node.message.listConnections())
            component_network = metadata.network_core.MetaNode.get_first_network_entry(
                control, metadata.network_core.ComponentCore)
            if component_network:
                component = rigging.rig_base.Component_Base.create_from_network_node(
                    component_network.node)
                component.set_control_orders()
    except Exception, e:
        raise e
Example #19
0
def voxel_cube(voxel_vector, voxel_size):
    if type(voxel_vector) == type([]):
        voxel_vector = v1_math.vector.Vector(voxel_vector)
    cube = get_first_or_default(pm.polyCube())
    pos = v1_math.vector.Vector(*voxel_vector.values)
    pos = pos * voxel_size
    pos = pos + (voxel_size / 2.0)
    cube.translate.set(pos)
    cube.scale.set([voxel_size, voxel_size, voxel_size])
 def root(self):
     '''
     Transform node that is the scene group object for this node
     '''
     return_root = get_first_or_default(
         pm.listConnections(self.node.root_joint, type=pm.nt.Joint))
     return_root = return_root if return_root else self.get_root(
         self.get_first_connection())
     return return_root
Example #21
0
    def apply_selected_to_color(self, vm, event_args):
        obj = get_first_or_default(pm.ls(selection=True))

        if type(obj) == pm.nt.Blinn:
            scene_material = obj
        else:
            scene_material = get_first_or_default(
                freeform_utils.materials.get_material_list(
                    obj)) if obj else None

        if scene_material:
            color = scene_material.color.get()
            event_args.Color.ColorR = round(color[0] * 255.0)
            event_args.Color.ColorG = round(color[1] * 255.0)
            event_args.Color.ColorB = round(color[2] * 255.0)

            event_args.Color.Alpha = round(
                (1 - scene_material.transparency.get()[0]) * 255.0)
            event_args.Color.Translucence = scene_material.translucence.get()
    def pick_control(self, c_asset, event_args):
        '''
        pick_control(self, c_asset, event_args)
        Have the selected object drive the animation attributes and set them on itself
        '''
        root = get_first_or_default(pm.selected())
        self.target = root

        if (c_asset != None):
            c_asset.TargetName = str(self.target)
Example #23
0
    def remove(self, do_bake = True):
        control = self.network['controls'].get_first_connection()

        custom_attr_list = [getattr(control, x) for x in pm.listAttr(control, ud=True, k=True)]
        for attr in custom_attr_list:
            input_attr = get_first_or_default(pm.listConnections(attr, s=True, d=False, p=True))
            output_attr = get_first_or_default(pm.listConnections(attr, s=False, d=True, p=True))
    
            anim_connection = get_first_or_default(pm.listConnections(input_attr, s=True, d=False, p=True))
    
            output_attr.unlock()
            input_attr // attr
            attr // output_attr
            if anim_connection:
                anim_connection >> output_attr
                anim_connection // input_attr

            input_attr.delete()

        self.network['addon'].delete_all()
    def fix_heel(self, fix_range):
        autokey_state = pm.autoKeyframe(q=True, state=True)
        pm.autoKeyframe(state=False)

        character_network = self.network['character']
        rigging.rig_base.Component_Base.zero_all_overdrivers(character_network)
        rigging.rig_base.Component_Base.zero_all_rigging(character_network)

        heel_loc = pm.spaceLocator(name="rf_fix_heel_loc")
        toe_rot_loc = pm.spaceLocator(name="rf_fix_toe_rot_loc")
        toe_ik_pos_loc = pm.spaceLocator(name="rf_fix_toe_ik_pos_loc")

        control_list = self.network['controls'].get_connections()
        to_order_list = [x for x in control_list if 'toe_ik' not in x.name()]
        ordered_controls = rigging.skeleton.sort_chain_by_hierarchy(
            to_order_list)
        ik_control = get_first_or_default(
            [x for x in control_list if x not in ordered_controls])

        del_constraint = []
        pm.delete(pm.parentConstraint(ordered_controls[-1], heel_loc,
                                      mo=False))
        del_constraint.append(
            pm.parentConstraint(ordered_controls[0], heel_loc, mo=True))
        del_constraint.append(
            pm.parentConstraint(ordered_controls[1], toe_rot_loc, mo=False))
        del_constraint.append(
            pm.parentConstraint(ik_control, toe_ik_pos_loc, mo=False))

        maya_utils.baking.bake_objects([heel_loc, toe_rot_loc, toe_ik_pos_loc],
                                       True, True, False)
        pm.delete(del_constraint)
        pm.currentTime(pm.currentTime(
        ))  # Maya may not update the scene properly after this bake

        del_constraint = []
        del_constraint.append(
            pm.parentConstraint(heel_loc, ordered_controls[-1], mo=False))
        del_constraint.append(
            pm.orientConstraint(toe_rot_loc, ordered_controls[1], mo=False))
        del_constraint.append(
            pm.pointConstraint(toe_ik_pos_loc, ik_control, mo=False))

        bake_list = [ordered_controls[-1], ordered_controls[1], ik_control]
        maya_utils.baking.bake_objects(bake_list,
                                       True,
                                       True,
                                       False,
                                       bake_range=fix_range,
                                       preserveOutsideKeys=True)

        pm.delete(del_constraint + [heel_loc, toe_rot_loc, toe_ik_pos_loc])

        pm.autoKeyframe(state=autokey_state)
    def get_first_connection(self, node_type=None, get_attribute=None):
        '''
        Get the first connection from the network node's message attribute, excluding 'nodeGraphEditorInfo' type nodes

        Args:
            node_type (type): If given, only get connections to this type of node

        Returns:
            (list<PyNode>). List of all objects connected
        '''
        return get_first_or_default(
            self.get_connections(node_type, get_attribute))
Example #26
0
def freeze_xform_rig(character_network):
    '''
    Duplicates the skeleton, freezes all transforms, charactarizes the new skeleton and saves a temporary character json file
    with all of the zeroed joint values in it.
    '''
    joint_core_network = character_network.get_downstream(
        metadata.network_core.JointsCore)
    character_joint_list = joint_core_network.get_connections()
    root = rigging.skeleton.get_root_joint(
        get_first_or_default(character_joint_list))

    new_skeleton = pm.duplicate(character_joint_list, po=True)
    new_root = rigging.skeleton.get_root_joint(
        get_first_or_default(new_skeleton))
    new_root.setParent(None)
    new_root.rename(root.stripNamespace())

    for jnt in new_skeleton:
        maya_utils.node_utils.unlock_transforms(jnt)
        jnt.translate.set(jnt.bind_translate.get())
        jnt.rotate.set(jnt.bind_rotate.get())

    # remove duplicated constraint nodes
    pm.delete(pm.listRelatives(new_root, ad=True, type='constraint'))
    pm.makeIdentity(new_skeleton, apply=True)

    new_character_network = freeform_utils.character_utils.characterize_skeleton(
        new_root, name="ZeroTemp", update_ui=False, freeze_skeleton=False)

    settings_path = os.path.join(os.path.expanduser("~"), "V1",
                                 "_rig_temp_settings.json")
    rigging.file_ops.save_settings_to_json(new_root, settings_path)

    rigging.rig_base.Component_Base.delete_character(
        new_character_network.node)
    rigging.file_ops.load_settings_from_json(character_network.group,
                                             settings_path)

    scene_tools.scene_manager.SceneManager().run_by_string(
        'UpdateRiggerInPlace')
    def load_data(self, data, obj, *args):
        '''
        Load the parent transform of a Maya scene joint from a json file

        Args:
            data (dictionary): json file dictionary to load from
            obj (PyNode): Maya scene object to load attributes onto
            args (args): Optional args
        '''
        parent_name = get_first_or_default(args) + data['parent']
        if pm.objExists(parent_name):
            parent = pm.PyNode(parent_name)
            obj.setParent(parent)
Example #28
0
def load_from_json_with_dialog(character_network):
    '''
    Loads a rig configuration json file onto a character.  Reads all rig components from file and applies them
    to the character by region.  Prompts user to choose the file save path

    Args:
        character_network (PyNode): The Maya scene character network node for the character to save
    '''
    config_manager = v1_core.global_settings.ConfigManager()
    start_dir = config_manager.get_character_directory()
    load_path = pm.fileDialog2(ds = 1, fm = 1, ff = "JSON - .json (*.json)", dir = start_dir, cap = "Load Rigging File")
    if load_path:
        load_from_json(character_network, get_first_or_default(load_path))
Example #29
0
def save_to_json_with_dialog(character_network):
    '''
    Saves a rig configuration file out to json.  Finds all rig components on a character and saves their applied
    state out to file.  Prompts user to choose the file save path

    Args:
        character_network (PyNode): The Maya scene character network node for the character to save
    '''
    config_manager = v1_core.global_settings.ConfigManager()
    start_dir = config_manager.get_character_directory()
    load_path = pm.fileDialog2(ds = 1, fm = 0, ff = "JSON - .json (*.json)", dir = start_dir, cap = "Save Rigging File")
    if load_path:
        save_to_json(character_network, get_first_or_default(load_path))
Example #30
0
def get_root_node(obj, type_name):
    '''
    Recursive. Traverse up the hierarchy until finding the first object that doesn't have a parent

    Args:
        obj (PyNode): The Maya scene joint node that's part of a skeleton

    Returns:
        PyNode. The top level joint of a skeleton
    '''
    parent = get_first_or_default(
        pm.listRelatives(obj, parent=True, type=type_name))
    return get_root_node(parent, type_name) if parent else obj