code
stringlengths
1
1.72M
language
stringclasses
1 value
# This file is part of Androguard. # # Copyright (c) 2012 Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class MakeProperties(type): def __init__(cls, name, bases, dct): def _wrap_set(names, name): def fun(self, value): for field in names: self.__dict__[field] = (name == field) and value return fun def _wrap_get(name): def fun(self): return self.__dict__[name] return fun super(MakeProperties, cls).__init__(name, bases, dct) attrs = [] prefixes = ('_get_', '_set_') for key in dct.keys(): for prefix in prefixes: if key.startswith(prefix): attrs.append(key[4:]) delattr(cls, key) for attr in attrs: setattr(cls, attr[1:], property(_wrap_get(attr), _wrap_set(attrs, attr))) cls._attrs = attrs def __call__(cls, *args, **kwds): obj = super(MakeProperties, cls).__call__(*args, **kwds) for attr in cls._attrs: obj.__dict__[attr] = False return obj class LoopType(object): __metaclass__ = MakeProperties _set_is_pretest = _set_is_posttest = _set_is_endless = None _get_is_pretest = _get_is_posttest = _get_is_endless = None def copy(self): res = LoopType() for key, value in self.__dict__.iteritems(): setattr(res, key, value) return res class NodeType(object): __metaclass__ = MakeProperties _set_is_cond = _set_is_switch = _set_is_stmt = None _get_is_cond = _get_is_switch = _get_is_stmt = None _set_is_return = _set_is_throw = None _get_is_return = _get_is_throw = None def copy(self): res = NodeType() for key, value in self.__dict__.iteritems(): setattr(res, key, value) return res class Node(object): def __init__(self, name): self.name = name self.num = 0 self.follow = {'if': None, 'loop': None, 'switch': None} self.looptype = LoopType() self.type = NodeType() self.in_catch = False self.interval = None self.startloop = False self.latch = None self.loop_nodes = [] def copy_from(self, node): self.num = node.num self.looptype = node.looptype.copy() self.interval = node.interval self.startloop = node.startloop self.type = node.type.copy() self.follow = node.follow.copy() self.latch = node.latch self.loop_nodes = node.loop_nodes self.in_catch = node.in_catch def update_attribute_with(self, n_map): self.latch = n_map.get(self.latch, self.latch) for follow_type, value in self.follow.iteritems(): self.follow[follow_type] = n_map.get(value, value) self.loop_nodes = list(set(n_map.get(n, n) for n in self.loop_nodes)) def get_head(self): return self def get_end(self): return self def __repr__(self): return '%s' % self class Interval(object): def __init__(self, head): self.name = 'Interval-%s' % head.name self.content = set([head]) self.end = None self.head = head self.in_catch = head.in_catch head.interval = self def __contains__(self, item): # If the interval contains nodes, check if the item is one of them if item in self.content: return True # If the interval contains intervals, we need to check them return any(item in node for node in self.content if isinstance(node, Interval)) def add_node(self, node): if node in self.content: return False self.content.add(node) node.interval = self return True def compute_end(self, graph): for node in self.content: for suc in graph.sucs(node): if suc not in self.content: self.end = node def get_end(self): return self.end.get_end() def get_head(self): return self.head.get_head() def __len__(self): return len(self.content) def __repr__(self): return '%s(%s)' % (self.name, self.content)
Python
# This file is part of Androguard. # # Copyright (c) 2012 Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from collections import defaultdict from androguard.decompiler.dad.basic_blocks import (build_node_from_block, StatementBlock, CondBlock) from androguard.decompiler.dad.instruction import Variable from androguard.decompiler.dad.util import common_dom logger = logging.getLogger('dad.graph') class Graph(): def __init__(self): self.entry = None self.exit = None self.nodes = list() self.rpo = [] self.edges = defaultdict(list) self.catch_edges = defaultdict(list) self.reverse_edges = defaultdict(list) self.reverse_catch_edges = defaultdict(list) self.loc_to_ins = None self.loc_to_node = None def sucs(self, node): return self.edges.get(node, []) def all_sucs(self, node): return self.edges.get(node, []) + self.catch_edges.get(node, []) def preds(self, node): return [n for n in self.reverse_edges.get(node, []) if not n.in_catch] def all_preds(self, node): return (self.reverse_edges.get(node, []) + self.reverse_catch_edges.get(node, [])) def add_node(self, node): self.nodes.append(node) def add_edge(self, e1, e2): lsucs = self.edges[e1] if e2 not in lsucs: lsucs.append(e2) lpreds = self.reverse_edges[e2] if e1 not in lpreds: lpreds.append(e1) def add_catch_edge(self, e1, e2): lsucs = self.catch_edges[e1] if e2 not in lsucs: lsucs.append(e2) lpreds = self.reverse_catch_edges[e2] if e1 not in lpreds: lpreds.append(e1) def remove_node(self, node): preds = self.reverse_edges.pop(node, []) for pred in preds: self.edges[pred].remove(node) succs = self.edges.pop(node, []) for suc in succs: self.reverse_edges[suc].remove(node) exc_preds = self.reverse_catch_edges.pop(node, []) for pred in exc_preds: self.catch_edges[pred].remove(node) exc_succs = self.catch_edges.pop(node, []) for suc in exc_succs: self.reverse_catch_edges[suc].remove(node) self.nodes.remove(node) if node in self.rpo: self.rpo.remove(node) del node def number_ins(self): self.loc_to_ins = {} self.loc_to_node = {} num = 0 for node in self.rpo: start_node = num num = node.number_ins(num) end_node = num - 1 self.loc_to_ins.update(node.get_loc_with_ins()) self.loc_to_node[(start_node, end_node)] = node def get_ins_from_loc(self, loc): return self.loc_to_ins.get(loc) def get_node_from_loc(self, loc): for (start, end), node in self.loc_to_node.iteritems(): if start <= loc <= end: return node def remove_ins(self, loc): ins = self.get_ins_from_loc(loc) self.get_node_from_loc(loc).remove_ins(loc, ins) self.loc_to_ins.pop(loc) def split_if_nodes(self): ''' Split IfNodes in two nodes, the first node is the header node, the second one is only composed of the jump condition. ''' node_map = {} to_update = set() for node in self.nodes[:]: if node.type.is_cond: if len(node.get_ins()) > 1: pre_ins = node.get_ins()[:-1] last_ins = node.get_ins()[-1] pre_node = StatementBlock('%s-pre' % node.name, pre_ins) cond_node = CondBlock('%s-cond' % node.name, [last_ins]) node_map[node] = pre_node pre_node.copy_from(node) cond_node.copy_from(node) for var in node.var_to_declare: pre_node.add_variable_declaration(var) pre_node.type.is_stmt = True cond_node.true = node.true cond_node.false = node.false for pred in self.all_preds(node): pred_node = node_map.get(pred, pred) # Verify that the link is not an exception link if node not in self.sucs(pred): self.add_catch_edge(pred_node, pre_node) continue if pred is node: pred_node = cond_node if pred.type.is_cond: # and not (pred is node): if pred.true is node: pred_node.true = pre_node if pred.false is node: pred_node.false = pre_node self.add_edge(pred_node, pre_node) for suc in self.sucs(node): self.add_edge(cond_node, node_map.get(suc, suc)) # We link all the exceptions to the pre node instead of the # condition node, which should not trigger any of them. for suc in self.catch_edges.get(node, []): self.add_catch_edge(pre_node, node_map.get(suc, suc)) if node is self.entry: self.entry = pre_node self.add_node(pre_node) self.add_node(cond_node) self.add_edge(pre_node, cond_node) pre_node.update_attribute_with(node_map) cond_node.update_attribute_with(node_map) self.remove_node(node) else: to_update.add(node) for node in to_update: node.update_attribute_with(node_map) def simplify(self): ''' Simplify the CFG by merging/deleting statement nodes when possible: If statement B follows statement A and if B has no other predecessor besides A, then we can merge A and B into a new statement node. We also remove nodes which do nothing except redirecting the control flow (nodes which only contains a goto). ''' redo = True while redo: redo = False node_map = {} to_update = set() for node in self.nodes[:]: if node.type.is_stmt and node in self.nodes: sucs = self.all_sucs(node) if len(sucs) == 0 or len(sucs) > 1: continue suc = sucs[0] if len(node.get_ins()) == 0: if any(pred.type.is_switch for pred in self.all_preds(node)): continue suc = self.edges.get(node)[0] if node is suc: continue node_map[node] = suc add_edge = self.add_edge if node.in_catch: add_edge = self.add_catch_edge for pred in self.all_preds(node): pred.update_attribute_with(node_map) if node not in self.sucs(pred): self.add_catch_edge(pred, suc) continue self.add_edge(pred, suc) redo = True if node is self.entry: self.entry = suc self.remove_node(node) elif (suc.type.is_stmt and len(self.all_preds(suc)) == 1 and not (suc in self.catch_edges) and not ((node is suc) or (suc is self.entry))): ins_to_merge = suc.get_ins() node.add_ins(ins_to_merge) for var in suc.var_to_declare: node.add_variable_declaration(var) new_suc = self.sucs(suc)[0] if new_suc: self.add_edge(node, new_suc) for exception_suc in self.catch_edges.get(suc, []): self.add_catch_edge(node, exception_suc) redo = True self.remove_node(suc) else: to_update.add(node) for node in to_update: node.update_attribute_with(node_map) def _traverse(self, node, visit, res): if node in visit: return visit.add(node) for suc in self.all_sucs(node): self._traverse(suc, visit, res) res.insert(0, node) def compute_rpo(self): ''' Number the nodes in reverse post order. An RPO traversal visit as many predecessors of a node as possible before visiting the node itself. ''' visit = set() res = [] self._traverse(self.entry, visit, res) for i, n in enumerate(res, 1): n.num = i self.rpo.append(n) def reset_rpo(self): self.rpo = [] self.compute_rpo() def post_order(self, start=None, visited=None, res=None): ''' Return the nodes of the graph in post-order i.e we visit all the children of a node before visiting the node itself. ''' if visited is None: res = [] visited = set() start = self.entry visited.add(start) for suc in self.all_sucs(start): if not suc in visited: self.post_order(suc, visited, res) res.append(start) return res def draw(self, name, dname, draw_branches=True): from pydot import Dot, Edge g = Dot() g.set_node_defaults(color='lightgray', style='filled', shape='box', fontname='Courier', fontsize='10') for node in sorted(self.nodes, key=lambda x: x.num): if draw_branches and node.type.is_cond: g.add_edge(Edge(str(node), str(node.true), color='green')) g.add_edge(Edge(str(node), str(node.false), color='red')) else: for suc in self.sucs(node): g.add_edge(Edge(str(node), str(suc), color='blue')) for except_node in self.catch_edges.get(node, []): g.add_edge(Edge(str(node), str(except_node), color='black', style='dashed')) g.write_png('%s/%s.png' % (dname, name)) def immediate_dominators(self): ''' Create a mapping of the nodes of a graph with their corresponding immediate dominator ''' idom = dict((n, None) for n in self.nodes) for node in self.rpo: if node.in_catch: predecessor = self.all_preds else: predecessor = self.preds for pred in predecessor(node): if pred.num < node.num: idom[node] = common_dom(idom, idom[node], pred) return idom def __len__(self): return len(self.nodes) def __repr__(self): return str(self.nodes) def __iter__(self): for node in self.nodes: yield node def bfs(start): to_visit = [start] visited = set([start]) while to_visit: node = to_visit.pop(0) yield node if node.exception_analysis: for _, _, exception in node.exception_analysis.exceptions: if exception not in visited: to_visit.append(exception) visited.add(exception) for _, _, child in node.childs: if child not in visited: to_visit.append(child) visited.add(child) class GenInvokeRetName(object): def __init__(self): self.num = 0 self.ret = None def new(self): self.num += 1 self.ret = Variable('tmp%d' % self.num) return self.ret def set_to(self, ret): self.ret = ret def last(self): return self.ret def make_node(graph, block, block_to_node, vmap, gen_ret): node = block_to_node.get(block) if node is None: node = build_node_from_block(block, vmap, gen_ret) block_to_node[block] = node if block.exception_analysis: for _type, _, exception_target in block.exception_analysis.exceptions: exception_node = block_to_node.get(exception_target) if exception_node is None: exception_node = build_node_from_block(exception_target, vmap, gen_ret, _type) exception_node.in_catch = True block_to_node[exception_target] = exception_node graph.add_catch_edge(node, exception_node) for _, _, child_block in block.childs: child_node = block_to_node.get(child_block) if child_node is None: child_node = build_node_from_block(child_block, vmap, gen_ret) block_to_node[child_block] = child_node graph.add_edge(node, child_node) if node.type.is_switch: node.add_case(child_node) if node.type.is_cond: if_target = ((block.end / 2) - (block.last_length / 2) + node.off_last_ins) child_addr = child_block.start / 2 if if_target == child_addr: node.true = child_node else: node.false = child_node # Check that both branch of the if point to something # It may happen that both branch point to the same node, in this case # the false branch will be None. So we set it to the right node. # TODO: In this situation, we should transform the condition node into # a statement node if node.type.is_cond and node.false is None: node.false = node.true return node def construct(start_block, vmap, exceptions): bfs_blocks = bfs(start_block) graph = Graph() gen_ret = GenInvokeRetName() # Construction of a mapping of basic blocks into Nodes block_to_node = {} exceptions_start_block = [] for exception in exceptions: for _, _, block in exception.exceptions: exceptions_start_block.append(block) for block in bfs_blocks: node = make_node(graph, block, block_to_node, vmap, gen_ret) graph.add_node(node) graph.entry = block_to_node[start_block] del block_to_node, bfs_blocks graph.compute_rpo() graph.number_ins() for node in graph.rpo: preds = [pred for pred in graph.all_preds(node) if pred.num < node.num] if preds and all(pred.in_catch for pred in preds): node.in_catch = True # Create a list of Node which are 'return' node # There should be one and only one node of this type # If this is not the case, try to continue anyway by setting the exit node # to the one which has the greatest RPO number (not necessarily the case) lexit_nodes = [node for node in graph if node.type.is_return] if len(lexit_nodes) > 1: # Not sure that this case is possible... logger.error('Multiple exit nodes found !') graph.exit = graph.rpo[-1] elif len(lexit_nodes) < 1: # A method can have no return if it has throw statement(s) or if its # body is a while(1) whitout break/return. logger.debug('No exit node found !') else: graph.exit = lexit_nodes[0] return graph
Python
# This file is part of Androguard. # # Copyright (C) 2013, Anthony Desnos <desnos at t0t0.fr> # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from subprocess import Popen, PIPE, STDOUT import tempfile import os from androguard.core.androconf import rrmdir from androguard.decompiler.dad import decompile PYGMENTS = True try: from pygments.filter import Filter from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import TerminalFormatter from pygments.token import Token except ImportError: PYGMENTS = False class Filter: pass class Dex2Jar: def __init__(self, vm, path_dex2jar="./decompiler/dex2jar/", bin_dex2jar="dex2jar.sh", tmp_dir="/tmp/"): pathtmp = tmp_dir if not os.path.exists(pathtmp): os.makedirs(pathtmp) fd, fdname = tempfile.mkstemp(dir=pathtmp) fd = os.fdopen(fd, "w+b") fd.write(vm.get_buff()) fd.flush() fd.close() compile = Popen([path_dex2jar + bin_dex2jar, fdname], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink(fdname) self.jarfile = fdname + "_dex2jar.jar" def get_jar(self): return self.jarfile class DecompilerDex2Jad: def __init__(self, vm, path_dex2jar="./decompiler/dex2jar/", bin_dex2jar="dex2jar.sh", path_jad="./decompiler/jad/", bin_jad="jad", tmp_dir="/tmp/"): self.classes = {} self.classes_failed = [] pathtmp = tmp_dir if not os.path.exists(pathtmp): os.makedirs(pathtmp) fd, fdname = tempfile.mkstemp(dir=pathtmp) fd = os.fdopen(fd, "w+b") fd.write(vm.get_buff()) fd.flush() fd.close() compile = Popen([path_dex2jar + bin_dex2jar, fdname], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink(fdname) pathclasses = fdname + "dex2jar/" compile = Popen(["unzip", fdname + "_dex2jar.jar", "-d", pathclasses], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink(fdname + "_dex2jar.jar") for root, dirs, files in os.walk(pathclasses, followlinks=True): if files != []: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f compile = Popen([path_jad + bin_jad, "-o", "-d", root, real_filename], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() for i in vm.get_classes(): fname = pathclasses + "/" + i.get_name()[1:-1] + ".jad" if os.path.isfile(fname) == True: fd = open(fname, "r") self.classes[i.get_name()] = fd.read() fd.close() else: self.classes_failed.append(i.get_name()) rrmdir(pathclasses) def get_source_method(self, method): class_name = method.get_class_name() method_name = method.get_name() if class_name not in self.classes: return "" if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) lexer.add_filter(MethodFilter(method_name=method_name)) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result return self.classes[class_name] def display_source(self, method): print self.get_source_method(method) def get_source_class(self, _class): return self.classes[_class.get_name()] def get_all(self, class_name): if class_name not in self.classes: return "" if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result return self.classes[class_name] def display_all(self, _class): print self.get_all(_class.get_name()) class DecompilerDex2WineJad: def __init__(self, vm, path_dex2jar="./decompiler/dex2jar/", bin_dex2jar="dex2jar.sh", path_jad="./decompiler/jad/", bin_jad="jad", tmp_dir="/tmp/"): self.classes = {} self.classes_failed = [] pathtmp = tmp_dir if not os.path.exists(pathtmp): os.makedirs(pathtmp) fd, fdname = tempfile.mkstemp(dir=pathtmp) fd = os.fdopen(fd, "w+b") fd.write(vm.get_buff()) fd.flush() fd.close() compile = Popen([path_dex2jar + bin_dex2jar, fdname], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink(fdname) pathclasses = fdname + "dex2jar/" compile = Popen(["unzip", fdname + "_dex2jar.jar", "-d", pathclasses], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink(fdname + "_dex2jar.jar") for root, dirs, files in os.walk(pathclasses, followlinks=True): if files != []: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f compile = Popen(["wine", path_jad + bin_jad, "-o", "-d", root, real_filename], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() for i in vm.get_classes(): fname = pathclasses + "/" + i.get_name()[1:-1] + ".jad" if os.path.isfile(fname) == True: fd = open(fname, "r") self.classes[i.get_name()] = fd.read() fd.close() else: self.classes_failed.append(i.get_name()) rrmdir(pathclasses) def get_source_method(self, method): class_name = method.get_class_name() method_name = method.get_name() if class_name not in self.classes: return "" if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) lexer.add_filter(MethodFilter(method_name=method_name)) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result return self.classes[class_name] def display_source(self, method): print self.get_source_method(method) def get_source_class(self, _class): return self.classes[_class.get_name()] def get_all(self, class_name): if class_name not in self.classes: return "" if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result return self.classes[class_name] def display_all(self, _class): print self.get_all(_class.get_name()) class DecompilerDed: def __init__(self, vm, path="./decompiler/ded/", bin_ded="ded.sh", tmp_dir="/tmp/"): self.classes = {} self.classes_failed = [] pathtmp = tmp_dir if not os.path.exists(pathtmp) : os.makedirs( pathtmp ) fd, fdname = tempfile.mkstemp( dir=pathtmp ) fd = os.fdopen(fd, "w+b") fd.write( vm.get_buff() ) fd.flush() fd.close() dirname = tempfile.mkdtemp(prefix=fdname + "-src") compile = Popen([ path + bin_ded, "-c", "-o", "-d", dirname, fdname ], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink( fdname ) findsrc = None for root, dirs, files in os.walk( dirname + "/optimized-decompiled/" ) : if dirs != [] : for f in dirs : if f == "src" : findsrc = root if findsrc[-1] != "/" : findsrc += "/" findsrc += f break if findsrc != None : break for i in vm.get_classes() : fname = findsrc + "/" + i.get_name()[1:-1] + ".java" #print fname if os.path.isfile(fname) == True : fd = open(fname, "r") self.classes[ i.get_name() ] = fd.read() fd.close() else : self.classes_failed.append( i.get_name() ) rrmdir( dirname ) def get_source_method(self, method): class_name = method.get_class_name() method_name = method.get_name() if class_name not in self.classes: return "" lexer = get_lexer_by_name("java", stripall=True) lexer.add_filter(MethodFilter(method_name=method_name)) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result def display_source(self, method): print self.get_source_method(method) def get_all(self, class_name): if class_name not in self.classes: return "" lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result def get_source_class(self, _class): return self.classes[_class.get_name()] def display_all(self, _class): print self.get_all(_class.get_name()) class DecompilerDex2Fernflower: def __init__(self, vm, path_dex2jar="./decompiler/dex2jar/", bin_dex2jar="dex2jar.sh", path_fernflower="./decompiler/fernflower/", bin_fernflower="fernflower.jar", options_fernflower={"dgs": '1', "asc": '1'}, tmp_dir="/tmp/"): self.classes = {} self.classes_failed = [] pathtmp = tmp_dir if not os.path.exists(pathtmp): os.makedirs(pathtmp) fd, fdname = tempfile.mkstemp(dir=pathtmp) fd = os.fdopen(fd, "w+b") fd.write(vm.get_buff()) fd.flush() fd.close() compile = Popen([path_dex2jar + bin_dex2jar, fdname], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink(fdname) pathclasses = fdname + "dex2jar/" compile = Popen(["unzip", fdname + "_dex2jar.jar", "-d", pathclasses], stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() os.unlink(fdname + "_dex2jar.jar") for root, dirs, files in os.walk(pathclasses, followlinks=True): if files != []: for f in files: real_filename = root if real_filename[-1] != "/": real_filename += "/" real_filename += f l = ["java", "-jar", path_fernflower + bin_fernflower] for option in options_fernflower: l.append("-%s:%s" % (option, options_fernflower[option])) l.append(real_filename) l.append(root) compile = Popen(l, stdout=PIPE, stderr=STDOUT) stdout, stderr = compile.communicate() for i in vm.get_classes(): fname = pathclasses + "/" + i.get_name()[1:-1] + ".java" if os.path.isfile(fname) == True: fd = open(fname, "r") self.classes[i.get_name()] = fd.read() fd.close() else: self.classes_failed.append(i.get_name()) rrmdir(pathclasses) def get_source_method(self, method): class_name = method.get_class_name() method_name = method.get_name() if class_name not in self.classes: return "" if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) lexer.add_filter(MethodFilter(method_name=method_name)) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result return self.classes[class_name] def display_source(self, method): print self.get_source_method(method) def get_source_class(self, _class): return self.classes[_class.get_name()] def get_all(self, class_name): if class_name not in self.classes: return "" if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(self.classes[class_name], lexer, formatter) return result return self.classes[class_name] def display_all(self, _class): print self.get_all(_class.get_name()) class MethodFilter(Filter): def __init__(self, **options): Filter.__init__(self, **options) self.method_name = options["method_name"] #self.descriptor = options["descriptor"] self.present = False self.get_desc = True #False def filter(self, lexer, stream) : a = [] l = [] rep = [] for ttype, value in stream: if self.method_name == value and (ttype is Token.Name.Function or ttype is Token.Name) : #print ttype, value item_decl = -1 for i in range(len(a)-1, 0, -1) : if a[i][0] is Token.Keyword.Declaration : if a[i][1] != "class" : item_decl = i break if item_decl != -1 : self.present = True l.extend( a[item_decl:] ) if self.present and ttype is Token.Keyword.Declaration : item_end = -1 for i in range(len(l)-1, 0, -1) : if l[i][0] is Token.Operator and l[i][1] == "}" : item_end = i break if item_end != -1 : rep.extend( l[:item_end+1] ) l = [] self.present = False if self.present : l.append( (ttype, value) ) a.append( (ttype, value) ) if self.present : nb = 0 item_end = -1 for i in range(len(l)-1, 0, -1) : if l[i][0] is Token.Operator and l[i][1] == "}" : nb += 1 if nb == 2 : item_end = i break rep.extend( l[:item_end+1] ) return rep class DecompilerDAD: def __init__(self, vm, vmx): self.vm = vm self.vmx = vmx def get_source_method(self, m): mx = self.vmx.get_method(m) z = decompile.DvMethod(mx) z.process() result = z.get_source() return result def display_source(self, m): result = self.get_source_method(m) if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(result, lexer, formatter) print result def get_source_class(self, _class): c = decompile.DvClass(_class, self.vmx) c.process() result = c.get_source() return result def display_all(self, _class): result = self.get_source_class(_class) if PYGMENTS: lexer = get_lexer_by_name("java", stripall=True) formatter = TerminalFormatter() result = highlight(result, lexer, formatter) print result def get_all(self, class_name): pass
Python
''' Module which prompts the user for translations and saves them. TODO: implement @author: Rodrigo Damazio ''' class Translator(object): ''' classdocs ''' def __init__(self, language): ''' Constructor ''' self._language = language def Translate(self, string_names): print string_names
Python
''' Module which brings history information about files from Mercurial. @author: Rodrigo Damazio ''' import re import subprocess REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*') def _GetOutputLines(args): ''' Runs an external process and returns its output as a list of lines. @param args: the arguments to run ''' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines = True, shell = False) output = process.communicate()[0] return output.splitlines() def FillMercurialRevisions(filename, parsed_file): ''' Fills the revs attribute of all strings in the given parsed file with a list of revisions that touched the lines corresponding to that string. @param filename: the name of the file to get history for @param parsed_file: the parsed file to modify ''' # Take output of hg annotate to get revision of each line output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename]) # Create a map of line -> revision (key is list index, line 0 doesn't exist) line_revs = ['dummy'] for line in output_lines: rev_match = REVISION_REGEX.match(line) if not rev_match: raise 'Unexpected line of output from hg: %s' % line rev_hash = rev_match.group('hash') line_revs.append(rev_hash) for str in parsed_file.itervalues(): # Get the lines that correspond to each string start_line = str['startLine'] end_line = str['endLine'] # Get the revisions that touched those lines revs = [] for line_number in range(start_line, end_line + 1): revs.append(line_revs[line_number]) # Merge with any revisions that were already there # (for explict revision specification) if 'revs' in str: revs += str['revs'] # Assign the revisions to the string str['revs'] = frozenset(revs) def DoesRevisionSuperceed(filename, rev1, rev2): ''' Tells whether a revision superceeds another. This essentially means that the older revision is an ancestor of the newer one. This also returns True if the two revisions are the same. @param rev1: the revision that may be superceeding the other @param rev2: the revision that may be superceeded @return: True if rev1 superceeds rev2 or they're the same ''' if rev1 == rev2: return True # TODO: Add filename args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename] output_lines = _GetOutputLines(args) return rev2 in output_lines def NewestRevision(filename, rev1, rev2): ''' Returns which of two revisions is closest to the head of the repository. If none of them is the ancestor of the other, then we return either one. @param rev1: the first revision @param rev2: the second revision ''' if DoesRevisionSuperceed(filename, rev1, rev2): return rev1 return rev2
Python
''' Module which parses a string XML file. @author: Rodrigo Damazio ''' from xml.parsers.expat import ParserCreate import re #import xml.etree.ElementTree as ET class StringsParser(object): ''' Parser for string XML files. This object is not thread-safe and should be used for parsing a single file at a time, only. ''' def Parse(self, file): ''' Parses the given file and returns a dictionary mapping keys to an object with attributes for that key, such as the value, start/end line and explicit revisions. In addition to the standard XML format of the strings file, this parser supports an annotation inside comments, in one of these formats: <!-- KEEP_PARENT name="bla" --> <!-- KEEP_PARENT name="bla" rev="123456789012" --> Such an annotation indicates that we're explicitly inheriting form the master file (and the optional revision says that this decision is compatible with the master file up to that revision). @param file: the name of the file to parse ''' self._Reset() # Unfortunately expat is the only parser that will give us line numbers self._xml_parser = ParserCreate() self._xml_parser.StartElementHandler = self._StartElementHandler self._xml_parser.EndElementHandler = self._EndElementHandler self._xml_parser.CharacterDataHandler = self._CharacterDataHandler self._xml_parser.CommentHandler = self._CommentHandler file_obj = open(file) self._xml_parser.ParseFile(file_obj) file_obj.close() return self._all_strings def _Reset(self): self._currentString = None self._currentStringName = None self._currentStringValue = None self._all_strings = {} def _StartElementHandler(self, name, attrs): if name != 'string': return if 'name' not in attrs: return assert not self._currentString assert not self._currentStringName self._currentString = { 'startLine' : self._xml_parser.CurrentLineNumber, } if 'rev' in attrs: self._currentString['revs'] = [attrs['rev']] self._currentStringName = attrs['name'] self._currentStringValue = '' def _EndElementHandler(self, name): if name != 'string': return assert self._currentString assert self._currentStringName self._currentString['value'] = self._currentStringValue self._currentString['endLine'] = self._xml_parser.CurrentLineNumber self._all_strings[self._currentStringName] = self._currentString self._currentString = None self._currentStringName = None self._currentStringValue = None def _CharacterDataHandler(self, data): if not self._currentString: return self._currentStringValue += data _KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+' r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?' r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*', re.MULTILINE | re.DOTALL) def _CommentHandler(self, data): keep_parent_match = self._KEEP_PARENT_REGEX.match(data) if not keep_parent_match: return name = keep_parent_match.group('name') self._all_strings[name] = { 'keepParent' : True, 'startLine' : self._xml_parser.CurrentLineNumber, 'endLine' : self._xml_parser.CurrentLineNumber } rev = keep_parent_match.group('rev') if rev: self._all_strings[name]['revs'] = [rev]
Python
#!/usr/bin/python ''' Entry point for My Tracks i18n tool. @author: Rodrigo Damazio ''' import mytracks.files import mytracks.translate import mytracks.validate import sys def Usage(): print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0] print 'Commands are:' print ' cleanup' print ' translate' print ' validate' sys.exit(1) def Translate(languages): ''' Asks the user to interactively translate any missing or oudated strings from the files for the given languages. @param languages: the languages to translate ''' validator = mytracks.validate.Validator(languages) validator.Validate() missing = validator.missing_in_lang() outdated = validator.outdated_in_lang() for lang in languages: untranslated = missing[lang] + outdated[lang] if len(untranslated) == 0: continue translator = mytracks.translate.Translator(lang) translator.Translate(untranslated) def Validate(languages): ''' Computes and displays errors in the string files for the given languages. @param languages: the languages to compute for ''' validator = mytracks.validate.Validator(languages) validator.Validate() error_count = 0 if (validator.valid()): print 'All files OK' else: for lang, missing in validator.missing_in_master().iteritems(): print 'Missing in master, present in %s: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, missing in validator.missing_in_lang().iteritems(): print 'Missing in %s, present in master: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, outdated in validator.outdated_in_lang().iteritems(): print 'Outdated in %s: %s:' % (lang, str(outdated)) error_count = error_count + len(outdated) return error_count if __name__ == '__main__': argv = sys.argv argc = len(argv) if argc < 2: Usage() languages = mytracks.files.GetAllLanguageFiles() if argc == 3: langs = set(argv[2:]) if not langs.issubset(languages): raise 'Language(s) not found' # Filter just to the languages specified languages = dict((lang, lang_file) for lang, lang_file in languages.iteritems() if lang in langs or lang == 'en' ) cmd = argv[1] if cmd == 'translate': Translate(languages) elif cmd == 'validate': error_count = Validate(languages) else: Usage() error_count = 0 print '%d errors found.' % error_count
Python
''' Module which compares languague files to the master file and detects issues. @author: Rodrigo Damazio ''' import os from mytracks.parser import StringsParser import mytracks.history class Validator(object): def __init__(self, languages): ''' Builds a strings file validator. Params: @param languages: a dictionary mapping each language to its corresponding directory ''' self._langs = {} self._master = None self._language_paths = languages parser = StringsParser() for lang, lang_dir in languages.iteritems(): filename = os.path.join(lang_dir, 'strings.xml') parsed_file = parser.Parse(filename) mytracks.history.FillMercurialRevisions(filename, parsed_file) if lang == 'en': self._master = parsed_file else: self._langs[lang] = parsed_file self._Reset() def Validate(self): ''' Computes whether all the data in the files for the given languages is valid. ''' self._Reset() self._ValidateMissingKeys() self._ValidateOutdatedKeys() def valid(self): return (len(self._missing_in_master) == 0 and len(self._missing_in_lang) == 0 and len(self._outdated_in_lang) == 0) def missing_in_master(self): return self._missing_in_master def missing_in_lang(self): return self._missing_in_lang def outdated_in_lang(self): return self._outdated_in_lang def _Reset(self): # These are maps from language to string name list self._missing_in_master = {} self._missing_in_lang = {} self._outdated_in_lang = {} def _ValidateMissingKeys(self): ''' Computes whether there are missing keys on either side. ''' master_keys = frozenset(self._master.iterkeys()) for lang, file in self._langs.iteritems(): keys = frozenset(file.iterkeys()) missing_in_master = keys - master_keys missing_in_lang = master_keys - keys if len(missing_in_master) > 0: self._missing_in_master[lang] = missing_in_master if len(missing_in_lang) > 0: self._missing_in_lang[lang] = missing_in_lang def _ValidateOutdatedKeys(self): ''' Computers whether any of the language keys are outdated with relation to the master keys. ''' for lang, file in self._langs.iteritems(): outdated = [] for key, str in file.iteritems(): # Get all revisions that touched master and language files for this # string. master_str = self._master[key] master_revs = master_str['revs'] lang_revs = str['revs'] if not master_revs or not lang_revs: print 'WARNING: No revision for %s in %s' % (key, lang) continue master_file = os.path.join(self._language_paths['en'], 'strings.xml') lang_file = os.path.join(self._language_paths[lang], 'strings.xml') # Assume that the repository has a single head (TODO: check that), # and as such there is always one revision which superceeds all others. master_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2), master_revs) lang_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2), lang_revs) # If the master version is newer than the lang version if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev): outdated.append(key) if len(outdated) > 0: self._outdated_in_lang[lang] = outdated
Python
''' Module for dealing with resource files (but not their contents). @author: Rodrigo Damazio ''' import os.path from glob import glob import re MYTRACKS_RES_DIR = 'MyTracks/res' ANDROID_MASTER_VALUES = 'values' ANDROID_VALUES_MASK = 'values-*' def GetMyTracksDir(): ''' Returns the directory in which the MyTracks directory is located. ''' path = os.getcwd() while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)): if path == '/': raise 'Not in My Tracks project' # Go up one level path = os.path.split(path)[0] return path def GetAllLanguageFiles(): ''' Returns a mapping from all found languages to their respective directories. ''' mytracks_path = GetMyTracksDir() res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK) language_dirs = glob(res_dir) master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES) if len(language_dirs) == 0: raise 'No languages found!' if not os.path.isdir(master_dir): raise 'Couldn\'t find master file' language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs] language_tuples.append(('en', master_dir)) return dict(language_tuples)
Python
#!/usr/bin/env python # Copyright (c) 2004,2005 Damien Miller <djm@mindrot.org> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # $Id$ import sys from distutils.core import setup, Extension DEFS = [ ( 'PROGVER', '"0.9.1"' ), ] if __name__ == '__main__': if sys.hexversion < 0x02030000: print >> sys.stderr, "error: " + \ "flowd requires python >= 2.3" sys.exit(1) flowd = Extension('flowd', sources = ['flowd_python.c'], define_macros = DEFS, libraries = ['flowd'], library_dirs = ['.', '../..']) setup( name = "flowd", version = "0.9.1", author = "Damien Miller", author_email = "djm@mindrot.org", url = "http://www.mindrot.org/flowd.html", description = "Interface to flowd flow storage format", long_description = """\ This is an API to parse the binary flow logs written by the flowd network flow collector. """, license = "BSD", ext_modules = [flowd] )
Python
#!/usr/bin/env python # Copyright (c) 2004,2005 Damien Miller <djm@mindrot.org> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # $Id$ # This is a small program to populate a RRD database with summaries of # NetFlow data recorded by flowd. It is a pretty basic example; only # creating per-protocol (TCP, UDP, ICMP, etc.) summaries but it can be # easily modified to suit any summarisation system by changing the # FlowTrack class below # Please note that this requires the py-rrdtool module # How often (seconds) we update the RRD UPDATE_RATE = 300 import socket import time import select import flowd import os import sys import getopt import rrdtool def usage(): print >> sys.stderr, "flow_rrd.pl (flowd.py version %s)" % \ flowd.__version__ print >> sys.stderr, "Usage: flow_rrd.pl [options] [flowd-log] " + \ "[rrd-database]"; print >> sys.stderr, "Options:"; print >> sys.stderr, " -h Display this help"; print >> sys.stderr, " -s Read from a flowd log socket " + \ "instead of a log file" sys.exit(1); def create_rrd(filename, when = None): args = [ filename ] if when is not None: args.append("-b%s" % when) args += [ "-s300", "DS:icmp_flows:ABSOLUTE:600:0:U", "DS:tcp_flows:ABSOLUTE:600:0:U", "DS:udp_flows:ABSOLUTE:600:0:U", "DS:gre_flows:ABSOLUTE:600:0:U", "DS:esp_flows:ABSOLUTE:600:0:U", "DS:other_flows:ABSOLUTE:600:0:U", "DS:icmp_bytes:ABSOLUTE:600:0:U", "DS:tcp_bytes:ABSOLUTE:600:0:U", "DS:udp_bytes:ABSOLUTE:600:0:U", "DS:gre_bytes:ABSOLUTE:600:0:U", "DS:esp_bytes:ABSOLUTE:600:0:U", "DS:other_bytes:ABSOLUTE:600:0:U", "DS:icmp_packets:ABSOLUTE:600:0:U", "DS:tcp_packets:ABSOLUTE:600:0:U", "DS:udp_packets:ABSOLUTE:600:0:U", "DS:gre_packets:ABSOLUTE:600:0:U", "DS:esp_packets:ABSOLUTE:600:0:U", "DS:other_packets:ABSOLUTE:600:0:U", "RRA:AVERAGE:0.75:1:4800", "RRA:AVERAGE:0.5:6:2400", "RRA:AVERAGE:0.5:24:1200", "RRA:AVERAGE:0.5:288:1500", ] print >> sys.stderr, "Creating %s" % filename rrdtool.create(*args) class FlowTrack: _PROTOS = { 1 : "icmp", 6 : "tcp", 17 : "udp", 47 : "gre", 50 : "esp", -1 : "other" } _FIELDS = [ "flows", "bytes", "packets" ] def __init__(self): for field in self._FIELDS: self.__dict__[field] = dict([(x, 0) for x in self._PROTOS.keys()]) def update(self, flow): proto = -1 bytes = 0 packets = 0 if flow.has_field(flowd.FIELD_PROTO_FLAGS_TOS): proto = flow.protocol if not self.flows.has_key(proto): proto = -1 if flow.has_field(flowd.FIELD_OCTETS): bytes = flow.octets if flow.has_field(flowd.FIELD_PACKETS): packets = flow.packets self.flows[proto] += 1 self.bytes[proto] += bytes self.packets[proto] += packets def store_in_rrd(self, filename, when = None): print when if when is None: when = "N" all = [(x, y) for x in self._FIELDS for y in self.flows.keys()] template = "" data = "%s" % when for field, proto in all: ds = "%s_%s" % (self._PROTOS[proto], field) template += ":" + ds data += ":%u" % self.__dict__[field][proto] # Fix up start of template template = "-t" + template[1:] rrdtool.update(filename, template, data) def quantise(when): return (when // UPDATE_RATE) * UPDATE_RATE def process_from_socket(sockpath, rrdpath): if not os.access(rrdpath, os.R_OK|os.W_OK): create_rrd(rrdpath) s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) s.bind(sockpath) start_time = quantise(time.time()) flows = FlowTrack() try: while 1: elapsed = time.time() - start_time if elapsed > 0: select.select([s], [], [], UPDATE_RATE - elapsed) elapsed = time.time() - start_time if elapsed > UPDATE_RATE: flows.store_in_rrd(rrdpath) flows = FlowTrack() start_time = time.time() continue flowrec = s.recv(2048) flow = flowd.Flow(blob = flowrec) flows.update(flow) except: os.unlink(sockpath) raise def process_from_file(logpath, rrdpath): flowlog = flowd.FlowLog(logpath) start_time = None flows = FlowTrack() for flow in flowlog: if not flow.has_field(flowd.FIELD_RECV_TIME): continue if start_time is None or \ (flow.recv_sec - start_time) > UPDATE_RATE: if start_time is not None: flows.store_in_rrd(rrdpath, start_time) elif not os.access(rrdpath, os.R_OK|os.W_OK): create_rrd(rrdpath, quantise(flow.recv_sec) - 300) flows = FlowTrack() start_time = quantise(flow.recv_sec) flows.update(flow) def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hs') except getopt.GetoptError: print >> sys.stderr, "Invalid commandline arguments" usage() do_sock = False for o, a in opts: if o in ('-h', '--help'): usage() sys.exit(0) if o in ('-s', '--socket'): do_sock = True if len(args) == 0: print >> sys.stderr, "No log path specified" usage() if len(args) == 1: print >> sys.stderr, "No RRD database specified" usage() if len(args) > 2: print >> sys.stderr, "Too many commandline arguments" usage() if do_sock: process_from_socket(args[0], args[1]) else: process_from_file(args[0], args[1]) if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright (c) 2004,2005 Damien Miller <djm@mindrot.org> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # $Id$ # This is a tiny example client for the flowd.conf "logsock" realtime # flow relay socket import socket import flowd import os import sys import getopt def usage(): print >> sys.stderr, "sockclient.pl (flowd.py version %s)" % \ flowd.__version__ print >> sys.stderr, "Usage: reader.pl [options] [flowd-socket]"; print >> sys.stderr, "Options:"; print >> sys.stderr, " -h Display this help"; print >> sys.stderr, " -v Print all flow information"; print >> sys.stderr, " -u Print dates in UTC timezone"; sys.exit(1); def main(): verbose = 0 utc = 0 try: opts, args = getopt.getopt(sys.argv[1:], 'huv') except getopt.GetoptError: print >> sys.stderr, "Invalid commandline arguments" usage() for o, a in opts: if o in ('-h', '--help'): usage() sys.exit(0) if o in ('-v', '--verbose'): verbose = 1 continue if o in ('-u', '--utc'): utc = 1 continue if len(args) == 0: print >> sys.stderr, "No log socket specified" usage() if len(args) > 1: print >> sys.stderr, "Too many log sockets specified" usage() if verbose: mask = flowd.DISPLAY_ALL else: mask = flowd.DISPLAY_BRIEF s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) s.bind(args[0]) try: while 1: flowrec = s.recv(1024) flow = flowd.Flow(blob = flowrec) print flow.format(mask = mask, utc = utc) except: os.unlink(args[0]) raise if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright (c) 2004 Damien Miller <djm@mindrot.org> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # $Id$ # Example Python statistics application # This isn't polished at all, it just writes a top-N report to stdout # XXX TODO # - redo charts support # - Limit memory consumption in per-address statistics # - Reports in UTC time or other timezones # - Autoscale axes in charts better (particularly time) # - Use a moving average for charting the interpolated bitmaps (rather than # absurdly large bins) # - More reports # - pretty PDF output # - Split summarisation from presentation # - Save/load summary state (so you can play with presentation settings # without grovelling through the flow data every time) # - Clean up time units conversion mess in history classes # - num unique src unique dst per unit time import flowd import sys import string import math import getopt import time import datetime import pickle import gzip try: import curses no_curses = False except ImportError: no_curses = True class exponential_histogram: '''Class implementing a histogram with exponential bins''' def __init__(self, base = 2): '''Constructor for class exponential_histogram. Parameter "base" specifies the base bin size. Bins are of the form base**n. For example, a base of 10 will yield bins 1, 10, 100, 1000, ...''' self.n = 0 self.d = {} self.base = int(base) if self.base < 2: raise ValueError, "Invalid base" def update(self, data): '''Update an exponential histogram with 'data' (which must be numeric)''' if data != 0: data = int(math.log(data, self.base)) if not self.d.has_key(data): self.d[data] = 0 self.d[data] += 1 def tolist(self): '''Convert an exponential_histogram to a sorted list of (bin_value, frequency) tuples''' items = self.d.items() items.sort(lambda x, y: cmp(x[0], y[0])) ret = [] last = None for value, count in items: if last is not None and last + 1 < value: # Fill in the blanks for x in range(last + 1, value): ret.append((self.base ** x, 0)) ret.append((self.base ** value, count)) last = value return ret def report(self): ret = "" for val, count in self.tolist(): ret += "%u:%u\n" % (val, count) return ret class _base_history: '''Base class for time-series histories - Implements a history to record an event rate''' def __init__(self, resolution = 7200, start_time = None): '''Create a new history object. 'resolution' parameter determines the time length of a single bin in the array''' self.resolution = resolution * 1000 self.samples = {} def _bin2dt(self, when, skew): secs = (self.resolution * when / 1000.0) + skew return datetime.datetime.fromtimestamp(secs) def tolist(self, skew = 0): '''Convert a history to a sorted list of (time, amount) tuples''' items = self.samples.items() items.sort(lambda x, y: cmp(x[0], y[0])) ret = [] last = None for value, count in items: if last is not None and last + 1 < value: # Fill in the blanks #print "filling", last, value for x in range(last + 1, value): ret.append((self._bin2dt(x, skew), 0)) ret.append((self._bin2dt(value, skew), count)) last = value return ret class interpolated_history(_base_history): '''Implements a history to estimate data throughput based on the information in the flow: start_time, finish_time and quantity.''' def _add(self, amount, when): if not self.samples.has_key(when): self.samples[when] = 0 self.samples[when] += amount * 1000.0 / self.resolution def update(self, amount, start, finish): '''Update a interpolated_history with a flow's data. Throughtput is estimated over the lifetime (defined by 'start' and 'finish') based on total 'amount' of flow.''' if finish < start: raise ValueError, "start lies after finish" mstart = int(start / self.resolution) mfinish = int(finish / self.resolution) # Easy case if mstart == mfinish: #print "easy", mstart, amount self._add(amount, mstart) return rate = float(amount) / float(finish - start) for when in range(mstart, mfinish): # Special-case for start and finish: estimate # contribution based on proportion of time in bin if when == mstart: contribution = (self.resolution - \ (start % self.resolution)) * rate elif when == mfinish - 1: contribution = (finish % self.resolution) * rate else: contribution = rate * self.resolution self._add(contribution, when) def crop(self, first = None, last = None): '''Delete records outside of specified time range''' delete_keys = [] for key in self.samples.keys(): xkey = int(key * self.resolution) if first is not None and xkey < first: delete_keys.append(key) elif last is not None and xkey > last: delete_keys.append(key) for key in delete_keys: del self.samples[key] class simple_history(_base_history): '''Implements a history to record event rate based on the information time and quantity.''' def update(self, amount, when): '''Update a simple_history with a flow's data. Event rate is is recorded based on event rate ('amount') and time of incidence ('when')''' mwhen = int(when / self.resolution) if not self.samples.has_key(mwhen): self.samples[mwhen] = 0 self.samples[mwhen] += amount * 1000.0 / self.resolution class flow_stat_count: def __init__(self): self.flows = 0 self.octets = 0 self.packets = 0 def update(self, flow): self.flows += 1 if flow.has_field(flowd.FIELD_OCTETS): self.octets += flow.octets if flow.has_field(flowd.FIELD_PACKETS): self.packets += flow.packets class flow_statistic: '''maintain flows, packets and octet counts statistics on a particular aspect of a flow (e.g. per-protocol, per-port)''' def __init__(self): '''Constructor for class flow_statistic''' self.num_unique = 0 self.counts = {} def update(self, what, flow): '''Update a flow_statistic with a flow's data.''' try: count = self.counts[what] except: self.num_unique += 1 count = flow_stat_count() self.counts[what] = count count.update(flow) def toplist(self, which = "octets", by_key = False, top_n = 10): d = [[x[0], x[1].__dict__[which]] for x in self.counts.items()] if by_key: d.sort(lambda x, y: cmp(x[0], y[0])) else: d.sort(lambda x, y: -cmp(x[1], y[1])) if top_n is None: return d return d[0:top_n] def report(self): ret = "" ret += "Total: %d\n" % len(self.counts.keys()) ret += "Octets\n" for k, v in self.toplist("octets"): ret += " %s: %s\n" % (k, v) ret += "Packets\n" for k, v in self.toplist("packets"): ret += " %s: %s\n" % (k, v) ret += "Flows\n" for k, v in self.toplist("flows"): ret += " %s: %s\n" % (k, v) return ret class flow_statistics: def __init__(self): self.first = None self.last = None self.average_clockskew = None self.average_clockskew_samples = 0 self.src_port = flow_statistic() self.dst_port = flow_statistic() self.src_addr = flow_statistic() self.dst_addr = flow_statistic() self.fromto = flow_statistic() self.protocol = flow_statistic() self.flows = 0; self.octets = None; self.packets = None; self.octets_hist = None self.packets_hist = None self.duration_hist = None self.packets_history = None self.octets_history = None self.flows_history = None # These need more work, or aren't much use for many people # self.octets_hist = exponential_histogram(base = 10) # self.packets_hist = exponential_histogram(base = 10) # self.duration_hist = exponential_histogram(base = 10) # self.packets_history = interpolated_history() # self.octets_history = interpolated_history() # self.flows_history = simple_history() def update(self, flow): self.flows += 1 if flow.has_field(flowd.FIELD_RECV_TIME): if self.flows_history is not None: self.flows_history.update(1, \ flow.recv_sec * 1000) if self.first is None or \ flow.recv_sec < self.first: self.first = flow.recv_sec if self.last is None or \ flow.recv_sec > self.last: self.last = flow.recv_sec if flow.has_field(flowd.FIELD_FLOW_TIMES): delta = flow.recv_sec - \ flow.flow_finish / 1000.0 if self.average_clockskew is None: self.average_clockskew = delta self.average_clockskew_samples += 1 new_offset = delta - self.average_clockskew self.average_clockskew += new_offset / \ self.average_clockskew_samples if flow.has_field(flowd.FIELD_OCTETS): if self.octets is None: self.octets = 0 self.octets += flow.octets if self.octets_hist is not None: self.octets_hist.update(flow.octets) if flow.has_field(flowd.FIELD_PACKETS): if self.packets is None: self.packets = 0 self.packets += flow.packets if self.packets_hist is not None: self.packets_hist.update(flow.packets) if flow.has_field(flowd.FIELD_FLOW_TIMES) and \ flow.has_field(flowd.FIELD_FLOW_TIMES): duration = flow.flow_finish - \ flow.flow_start duration = int(duration / 1000) # milliseconds if self.duration_hist is not None: self.duration_hist.update(duration) if flow.has_field(flowd.FIELD_OCTETS) and \ self.octets_history is not None: self.octets_history.update(\ flow.octets, \ flow.flow_start, \ flow.flow_finish) if flow.has_field(flowd.FIELD_PACKETS) and \ self.packets_history is not None: self.packets_history.update(\ flow.packets, \ flow.flow_start, \ flow.flow_finish) if flow.has_field(flowd.FIELD_SRC_ADDR): self.src_addr.update(flow.src_addr, flow) if flow.has_field(flowd.FIELD_DST_ADDR): self.dst_addr.update(flow.dst_addr, flow) if flow.has_field(flowd.FIELD_SRC_ADDR) and \ flow.has_field(flowd.FIELD_DST_ADDR): fromto = flow.src_addr + " -> " + \ flow.dst_addr self.fromto.update(fromto, flow) if flow.has_field(flowd.FIELD_SRCDST_PORT): self.src_port.update(flow.src_port, flow) if flow.has_field(flowd.FIELD_SRCDST_PORT): self.dst_port.update(flow.dst_port, flow) if flow.has_field(flowd.FIELD_PROTO_FLAGS_TOS): self.protocol.update(flow.protocol, flow) def crop(self): if self.first is None and self.last is None: return if self.average_clockskew is None: return first = self.first last = self.last if first is not None: first -= self.average_clockskew first *= 1000.0 if last is not None: last -= self.average_clockskew last *= 1000.0 if self.packets_history is not None: self.packets_history.crop(first, last) if self.octets_history is not None: self.octets_history.crop(first, last) def report(self): ret = "" ret += "total_flows: %u\n" % self.flows if self.octets is not None: ret += "total_octets: %u\n" % self.octets if self.packets is not None: ret += "total_packets: %u\n" % self.packets ret += "\n" if self.duration_hist is not None: ret += "duration_histogram:\n" ret += self.duration_hist.report() ret += "\n" if self.octets_hist is not None: ret += "octets_histogram:\n" ret += self.octets_hist.report() ret += "\n" if self.packets_hist is not None: ret += "packets_histogram:\n" ret += self.packets_hist.report() ret += "\n" ret += "src_ports:\n" ret += self.src_port.report() ret += "\n\n" ret += "dst_ports:\n" ret += self.dst_port.report() ret += "\n\n" ret += "protocols:\n" ret += self.protocol.report() ret += "\n\n" ret += "source address:\n" ret += self.src_addr.report() ret += "\n\n" ret += "destination address:\n" ret += self.dst_addr.report() ret += "\n\n" ret += "source / destination tuples:\n" ret += self.fromto.report() return ret def iso_units(x): units = ( "", "K", "M", "G", "T", "E", None) last = "" for u in units: if u is None: break last = u if x < 1000: break; x = int(x / 1000) return "%u%s" % (x, last) def usage(): print >> sys.stderr, "stats.py (flowd.py version %s)" % \ flowd.__version__ print >> sys.stderr, "Usage: stats.py [options] [flowd-store]"; print >> sys.stderr, "Options:"; print >> sys.stderr, " -h Display this help"; sys.exit(1); def main(): stats = flow_statistics() try: opts, args = getopt.getopt(sys.argv[1:], 'p:hu') except getopt.GetoptError: print >> sys.stderr, "Invalid commandline arguments" usage() pickle_file = None for o, a in opts: if o in ('-h', '--help'): usage() sys.exit(0) if o in ('-p', '--pickle'): pickle_file = a # Get clear-to-line-end sequence for progress display ceol = None if sys.stderr.isatty() and not no_curses: curses.setupterm() ceol = curses.tigetstr("el") if ceol is not None: ceol = curses.tparm(ceol, 0, 0) if ceol is None: ceol = "" if len(args) == 0: print >> sys.stderr, "No logfiles specified" usage() i = 0; for ffile in args: j = 0 if ffile == "-": flog = flowd.FlowLog_fromfile(sys.stdin) else: flog = flowd.FlowLog(ffile, "rb") for flow in flog: stats.update(flow) if ceol != "" and i >= 0 and j % 1000 == 0: print >> sys.stderr, "\r%s: %d flows" % \ (ffile, j), if i != j: print >> sys.stderr, " total %d" % i, print >> sys.stderr, ceol, sys.stderr.flush() i += 1 j += 1 print >> sys.stderr, "\r%s: %d flows (total %d)%s\n" % \ (ffile, j, i, ceol) sys.stderr.flush() stats.crop() print stats.report() if pickle_file is not None: out = open(pickle_file, "wb") pickle.dump(stats, out) out.close() print >> sys.stderr, "Statistics pickled to \"%s\"" % \ pickle_file if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright (c) 2004,2005 Damien Miller <djm@mindrot.org> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # $Id$ # This intended to be an example of the flowd package API more than a usable # application import flowd import sys import getopt def usage(): print >> sys.stderr, "reader.pl (flowd.py version %s)" % \ flowd.__version__ print >> sys.stderr, "Usage: reader.pl [options] [flowd-store]"; print >> sys.stderr, "Options:"; print >> sys.stderr, " -h Display this help"; print >> sys.stderr, " -v Print all flow information"; print >> sys.stderr, " -u Print dates in UTC timezone"; sys.exit(1); def main(): verbose = 0 utc = 0 try: opts, args = getopt.getopt(sys.argv[1:], 'huv') except getopt.GetoptError: print >> sys.stderr, "Invalid commandline arguments" usage() for o, a in opts: if o in ('-h', '--help'): usage() sys.exit(0) if o in ('-v', '--verbose'): verbose = 1 continue if o in ('-u', '--utc'): utc = 1 continue if len(args) == 0: print >> sys.stderr, "No logfiles specified" usage() if verbose: mask = flowd.DISPLAY_ALL else: mask = flowd.DISPLAY_BRIEF for ffile in args: flog = flowd.FlowLog(ffile) try: print "LOGFILE " + ffile except IOError: break; for flow in flog: print flow.format(mask = mask, utc = utc) if __name__ == '__main__': main()
Python
from distutils.core import setup, Extension module = Extension('fparser', sources = ['fparser.c', 'collector.c', 'dumper.c', 'logging.c', 'packer.c', 'parser.c', 'sniff.c'], libraries = ['pcap', 'pthread'], extra_compile_args = ['-Wextra', '-Werror', '-Wmissing-prototypes', '-std=gnu99', '-Wshadow', '-Wpointer-arith', '-Wcast-qual', '-Wstrict-prototypes', '-O2', '-g3', '-Wno-missing-field-initializers']) setup (name = 'FlowParser', version = '0.1.10', description = 'A flow parsing/dumping utility', ext_modules = [module], url = 'flowparser.googlecode.com', author = 'Nikola Gvozdiev', author_email = 'nikgvozdiev at gmail.com', license='MIT license', long_description=open('README').read())
Python
import fparser import time fp = fparser.FParser('en0') while True: time.sleep(10) for flow in fp.flow_iter(): if flow.get_info().Bps > 1000: print flow.get_id()
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import webapp2 import jinja2 from controllers import lessons, utils urls = [ ('/', lessons.CourseHandler), ('/register', utils.RegisterHandler), ('/course', lessons.CourseHandler), ('/unit', lessons.UnitHandler), ('/activity', lessons.ActivityHandler), ('/assessment', lessons.AssessmentHandler), ('/answer', lessons.AnswerHandler), ('/forum', utils.ForumHandler) ] app = webapp2.WSGIApplication(urls, debug=True)
Python
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @author: psimakov@google.com (Pavel Simakov) """Enforces schema and verifies course files for referential integrity. Use this script to verify referential integrity of your course definition files before you import them into the production instance of Google AppEngine. Here is how to use the script: - prepare your course files - edit the data/unit.csv file - edit the data/lesson.csv file - edit the assets/js/activity-*.*.js files - edit the assets/js/assessment-*.js files - run the script from a command line by navigating to the root directory of the app and then typing "python tools/verify.py" - review the report printed to the console for errors and warnings Good luck! """ import csv import os import re import sys BOOLEAN = object() STRING = object() FLOAT = object() INTEGER = object() CORRECT = object() REGEX = object() SCHEMA = { "assessment": { "assessmentName": STRING, "preamble": STRING, "checkAnswers": BOOLEAN, "questionsList": [{ "questionHTML": STRING, "lesson": STRING, "choices": [STRING, CORRECT], "correctAnswerNumeric": FLOAT, "correctAnswerString": STRING, "correctAnswerRegex": REGEX}] }, "activity": [ STRING, { "questionType": "multiple choice", "choices": [[STRING, BOOLEAN, STRING]] }, { "questionType": "multiple choice group", "questionsList": [{ "questionHTML": STRING, "choices": [STRING], "correctIndex": INTEGER}], "allCorrectOutput": STRING, "someIncorrectOutput": STRING }, { "questionType": "freetext", "correctAnswerRegex": REGEX, "correctAnswerOutput": STRING, "incorrectAnswerOutput": STRING, "showAnswerOutput": STRING, "showAnswerPrompt": STRING, "outputHeight": STRING }]} UNITS_HEADER = ( "id,type,unit_id,title,release_date,now_available") LESSONS_HEADER = ( "unit_id,unit_title,lesson_id,lesson_title,lesson_activity," "lesson_activity_name,lesson_notes,lesson_video_id,lesson_objectives") NO_VERIFY_TAG_NAME_OPEN = "<gcb-no-verify>" NO_VERIFY_TAG_NAME_CLOSE = "</gcb-no-verify>" OUTPUT_FINE_LOG = False OUTPUT_DEBUG_LOG = False class SchemaException(Exception): """A class to represent a schema error.""" def FormatPrimitiveValueName(self, name): if name == REGEX: return "REGEX(...)" if name == CORRECT: return "CORRECT(...)" if name == BOOLEAN: return "BOOLEAN" return name def FormatPrimitiveTypeName(self, name): if name == BOOLEAN: return "BOOLEAN" if name == REGEX: return "REGEX(...)" if name == CORRECT: return "CORRECT(...)" if name == STRING or isinstance(name, str): return "STRING" if name == FLOAT: return "FLOAT" if name == INTEGER: return "INTEGER" if isinstance(name, dict): return "{...}" if isinstance(name, list): return "[...]" return "Unknown type name '%s'" % name.__class__.__name__ def FormatTypeNames(self, names): if isinstance(names, list): captions = [] for name in names: captions.append(self.FormatPrimitiveTypeName(name)) return captions else: return self.FormatPrimitiveTypeName(names) def FormatTypeName(self, types): if isinstance(types, dict): return self.FormatTypeNames(types.keys()) if isinstance(types, list): return self.FormatTypeNames(types) return self.FormatTypeNames([types]) def __init__(self, message, value=None, types=None, path=None): prefix = "" if path: prefix = "Error at %s\n" % path if types: if value: message = prefix + message % ( self.FormatPrimitiveValueName(value), self.FormatTypeNames(types)) else: message = prefix + message % self.FormatTypeNames(types) else: if value: message = prefix + message % self.FormatPrimitiveValueName(value) else: message = prefix + message super(SchemaException, self).__init__(message) class Context(object): """"A class that manages a stack of traversal contexts.""" def __init__(self): self.parent = None self.path = ["/"] def New(self, names): """"Derives a new context from the current one.""" context = Context() context.parent = self context.path = list(self.path) if names: if isinstance(names, list): for name in names: if name: context.path.append("/" + "%s" % name) else: context.path.append("/" + "%s" % names) return context def FormatPath(self): """"Formats the canonical name of this context.""" return "".join(self.path) class SchemaHelper(object): """A class that knows how to apply the schema.""" def __init__(self): self.type_stats = {} def VisitElement(self, atype, value, context, is_terminal=True): """"This method is called once for each schema element being traversed.""" if self.type_stats.has_key(atype): count = self.type_stats[atype] else: count = 0 self.type_stats[atype] = count + 1 if is_terminal: self.parse_log.append(" TERMINAL: %s %s = %s" % ( atype, context.FormatPath(), value)) else: self.parse_log.append(" NON-TERMINAL: %s %s" % ( atype, context.FormatPath())) def ExtractAllTermsToDepth(self, key, values, type_map): """Walks schema recursively and creates a list of all known terms.""" """Walks schema type map recursively to depth and creates a list of all possible {key: value} pairs. The latter is the list of all non-terminal and terminal terms allowed in the schema. The list of terms from this method can be bound to an execution context for evaluating whether a given instance's map complies with the schema.""" if key: type_map.update({key: key}) if values == REGEX: type_map.update({"regex": lambda x: REGEX}) return if values == CORRECT: type_map.update({"correct": lambda x: CORRECT}) return if values == BOOLEAN: type_map.update({"true": BOOLEAN, "false": BOOLEAN}) return if values == STRING or values == INTEGER: return if isinstance(values, dict): for new_key, new_value in values.items(): self.ExtractAllTermsToDepth(new_key, new_value, type_map) return if isinstance(values, list): for new_value in values: self.ExtractAllTermsToDepth(None, new_value, type_map) return def FindSelectors(self, type_map): """Finds all type selectors.""" """Finds all elements in the type map where both a key and a value are strings. These elements are used to find one specific type map among several alternative type maps.""" selector = {} for akey, avalue in type_map.items(): if isinstance(akey, str) and isinstance(avalue, str): selector.update({akey: avalue}) return selector def FindCompatibleDict(self, value_map, type_map, context): """Find the type map most compatible with the value map.""" """"A value map is considered compatible with a type map when former contains the same key names and the value types as the type map.""" # special case when we have just one type; check name and type are the same if len(type_map) == 1: for value_key in value_map.keys(): for key in type_map[0].keys(): if value_key == key: return key, type_map[0] raise SchemaException( "Expected: '%s'\nfound: %s", type_map[0].keys()[0], value_map) # case when we have several types to choose from for adict in type_map: dict_selector = self.FindSelectors(adict) for akey, avalue in dict_selector.items(): if value_map[akey] == avalue: return akey, adict return None, None def CheckSingleValueMatchesType(self, value, atype, context): """Checks if a single value matches a specific (primitive) type.""" if atype == BOOLEAN: if (value == "True") or (value == "False") or (value == "true") or ( value == "false") or (isinstance(value, bool)) or value == BOOLEAN: self.VisitElement("BOOLEAN", value, context) return True else: raise SchemaException("Expected: 'true' or 'false'\nfound: %s", value) if isinstance(atype, str): if isinstance(value, str): self.VisitElement("str", value, context) return True else: raise SchemaException("Expected: 'string'\nfound: %s", value) if atype == STRING: if isinstance(value, str): self.VisitElement("STRING", value, context) return True else: raise SchemaException("Expected: 'string'\nfound: %s", value) if atype == REGEX and value == REGEX: self.VisitElement("REGEX", value, context) return True if atype == CORRECT and value == CORRECT: self.VisitElement("CORRECT", value, context) return True if atype == FLOAT: if IsNumber(value): self.VisitElement("NUMBER", value, context) return True else: raise SchemaException("Expected: 'number'\nfound: %s", value) if atype == INTEGER: if IsInteger(value): self.VisitElement("INTEGER", value, context) return True else: raise SchemaException( "Expected: 'integer'\nfound: %s", value, path=context.FormatPath()) raise SchemaException( "Unexpected value '%s'\n" "for type %s", value, atype, path=context.FormatPath()) def CheckValueListMatchesType(self, value, atype, context): """Checks if all items in value list match a specific type.""" for value_item in value: found = False for atype_item in atype: if isinstance(atype_item, list): for atype_item_item in atype_item: if self.DoesValueMatchType(value_item, atype_item_item, context): found = True break else: if self.DoesValueMatchType(value_item, atype_item, context): found = True break if not found: raise SchemaException("Expected: '%s'\nfound: %s", atype, value) return True def CheckValueMatchesType(self, value, atype, context): """Checks if single value or a list of values match a specific type.""" if isinstance(atype, list) and isinstance(value, list): return self.CheckValueListMatchesType(value, atype, context) else: return self.CheckSingleValueMatchesType(value, atype, context) def DoesValueMatchType(self, value, atype, context): """Same as other method, but does not throw an exception.""" try: return self.CheckValueMatchesType(value, atype, context) except SchemaException: return False def DoesValueMatchesOneOfTypes(self, value, types, context): """Checks if a value matches to one of the types in the list.""" type_names = None if isinstance(types, list): type_names = types if type_names: for i in range(0, len(type_names)): if self.DoesValueMatchType(value, type_names[i], context): return True return False def DoesValueMatchMapOfType(self, value, types, context): """Checks if value matches any variation of {...} type.""" # find all possible map types maps = [] for atype in types: if isinstance(atype, dict): maps.append(atype) if len(maps) == 0 and isinstance(types, dict): maps.append(types) # check if the structure of value matches one of the maps if isinstance(value, dict): aname, adict = self.FindCompatibleDict(value, maps, context) if adict: self.VisitElement("dict", value, context.New(aname), False) for akey, avalue in value.items(): if not adict.has_key(akey): raise SchemaException( "Unknown term '%s'", akey, path=context.FormatPath()) self.CheckValueOfValidType( avalue, adict[akey], context.New([aname, akey])) return True raise SchemaException( "The value:\n %s\n" "is incompatible with expected type(s):\n %s", value, types, path=context.FormatPath()) return False def FormatNameWithIndex(self, alist, aindex): """custom function to format a context name with an array element index.""" if len(alist) == 1: return "" else: return "[%s]" % aindex def DoesValueMatchListOfTypesInOrder(self, value, types, context, target): """Iterates the value and the types in given order and checks for match.""" all_values_are_lists = True for avalue in value: if not isinstance(avalue, list): all_values_are_lists = False if all_values_are_lists: for i in range(0, len(value)): self.CheckValueOfValidType(value[i], types, context.New( self.FormatNameWithIndex(value, i)), True) else: if len(target) != len(value): raise SchemaException( "Expected: '%s' values\n" + "found: %s." % value, len(target), path=context.FormatPath()) for i in range(0, len(value)): self.CheckValueOfValidType(value[i], target[i], context.New( self.FormatNameWithIndex(value, i))) return True def DoesValueMatchListOfTypesAnyOrder(self, value, types, context, lists): """Iterates the value and types and checks if they match in any order.""" target = lists if len(target) == 0: if not isinstance(types, list): raise SchemaException( "Unsupported type %s", None, types, path=context.FormatPath()) target = types for i in range(0, len(value)): found = False for atarget in target: try: self.CheckValueOfValidType(value[i], atarget, context.New( self.FormatNameWithIndex(value, i))) found = True break except: continue if not found: raise SchemaException( "The value:\n %s\n" "is incompatible with expected type(s):\n %s", value, types, path=context.FormatPath()) return True def DoesValueMatchListOfType(self, value, types, context, in_order): """Checks if a value matches a variation of [...] type.""" """Extra argument controls whether matching must be done in a specific or in any order. A specific order is demanded by [[...]]] construct, i.e. [[STRING, INTEGER, BOOLEAN]], while sub elements inside {...} and [...] can be matched in any order.""" # prepare a list of list types lists = [] for atype in types: if isinstance(atype, list): lists.append(atype) if len(lists) > 1: raise SchemaException( "Unable to validate types with multiple alternative " "lists %s", None, types, path=context.FormatPath()) if isinstance(value, list): if len(lists) > 1: raise SchemaException( "Allowed at most one list\nfound: %s.", None, types, path=context.FormatPath()) # determine if list is in order or not as hinted by double array [[..]]; # [STRING, NUMBER] is in any order, but [[STRING, NUMBER]] demands order ordered = len(lists) == 1 and isinstance(types, list) if in_order or ordered: return self.DoesValueMatchListOfTypesInOrder( value, types, context, lists[0]) else: return self.DoesValueMatchListOfTypesAnyOrder( value, types, context, lists) return False def CheckValueOfValidType(self, value, types, context, in_order=None): """Check if a value matches any of the given types.""" if not (isinstance(types, list) or isinstance(types, dict)): self.CheckValueMatchesType(value, types, context) return if self.DoesValueMatchListOfType(value, types, context, in_order): return if self.DoesValueMatchMapOfType(value, types, context): return if self.DoesValueMatchesOneOfTypes(value, types, context): return raise SchemaException("Unknown type %s", value, path=context.FormatPath()) def CheckInstancesMatchSchema(self, values, types, name): """Recursively decomposes 'values' to see if they match schema (types).""" self.parse_log = [] context = Context().New(name) self.parse_log.append(" ROOT %s" % context.FormatPath()) # handle {..} containers if isinstance(types, dict): if not isinstance(values, dict): raise SchemaException("Error at '/': expected {...}, found %s" % ( values.__class_.__name__)) self.CheckValueOfValidType(values, types, context.New([])) return # handle [...] containers if isinstance(types, list): if not isinstance(values, list): raise SchemaException("Error at '/': expected [...], found %s" % ( values.__class_.__name__)) for i in range(0, len(values)): self.CheckValueOfValidType( values[i], types, context.New("[%s]" % i)) return raise SchemaException( "Expected an array or a dictionary.", None, path=context.FormatPath()) class Unit(object): """A class to represent a Unit.""" id = 0 type = "" unit_id = "" title = "" release_date = "" now_available = False class Lesson(object): """A class to represent a Lesson.""" unit_id = 0 unit_title = "" lesson_id = 0 lesson_title = "" lesson_activity = "" lesson_activity_name = "" lesson_notes = "" lesson_video_id = "" lesson_objectives = "" def ToIdString(self): return "%s.%s.%s" % (self.unit_id, self.lesson_id, self.lesson_title) class Assessment(object): """A class to represent a Assessment.""" def __init__(self): self.scope = {} SchemaHelper().ExtractAllTermsToDepth( "assessment", SCHEMA["assessment"], self.scope) class Activity(object): """A class to represent a Activity.""" def __init__(self): self.scope = {} SchemaHelper().ExtractAllTermsToDepth( "activity", SCHEMA["activity"], self.scope) def Echo(x): print x def IsInteger(s): try: return int(s) == float(s) except ValueError: return False def IsBoolean(s): try: return s == "True" or s == "False" except ValueError: return False def IsNumber(s): try: float(s) return True except ValueError: return False def IsOneOf(value, values): for current in values: if value == current: return True return False def TextToLineNumberedText(text): """Adds line numbers to the provided text.""" lines = text.split("\n") results = [] i = 1 for line in lines: results.append(str(i) + ": " + line) i += 1 return "\n ".join(results) def SetObjectAttributes(target_object, names, values): """Sets object attributes from provided values.""" if len(names) != len(values): raise SchemaException( "The number of elements must match: %s and %s" % (names, values)) for i in range(0, len(names)): if IsInteger(values[i]): setattr(target_object, names[i], int(values[i])) continue if IsBoolean(values[i]): setattr(target_object, names[i], bool(values[i])) continue setattr(target_object, names[i], values[i]) def ReadObjectsFromCsvFile(fname, header, new_object): return ReadObjectsFromCsv(csv.reader(open(fname)), header, new_object) def ReadObjectsFromCsv(value_rows, header, new_object): values = [] for row in value_rows: if len(row) == 0: continue values.append(row) names = header.split(",") if names != values[0]: raise SchemaException( "Error reading CSV header.\n " "Header row had %s element(s): %s\n " "Expected header row with %s element(s): %s" % ( len(values[0]), values[0], len(names), names)) items = [] for i in range (1, len(values)): if len(names) != len(values[i]): raise SchemaException( "Error reading CSV data row.\n " "Row #%s had %s element(s): %s\n " "Expected %s element(s): %s" % ( i, len(values[i]), values[i], len(names), names)) item = new_object() SetObjectAttributes(item, names, values[i]) items.append(item) return items def EscapeJavascriptRegex(text): return re.sub(r"([:][ ]*)([/])(.*)([/][ismx]*)", r': regex("\2\3\4")', text) def RemoveJavaScriptSingleLineComment(text): text = re.sub(re.compile("^(.*?)[ ]+//(.*)$", re.MULTILINE), r"\1", text) text = re.sub(re.compile("^//(.*)$", re.MULTILINE), r"", text) return text def RemoveJavaScriptMultiLineComment(text): return re.sub(re.compile("/\*(.*)\*/", re.MULTILINE + re.DOTALL), r"", text) def RemoveContentMarkedNoVerify(content): """Removes content that should not be verified.""" """If you have any free-form JavaScript in the activity file, you need to place it between //<gcb-no-verify> ... //</gcb-no-verify> tags so that the verifier can selectively ignore it.""" pattern = re.compile("(%s)(.*)(%s)" % ( NO_VERIFY_TAG_NAME_OPEN, NO_VERIFY_TAG_NAME_CLOSE), re.DOTALL) return re.sub(pattern, "", content) def ConvertJavaScriptToPython(content, root_name): """Removes JavaScript specific syntactic constructs.""" """Reads the content and removes JavaScript comments, var's, and escapes regular expressions.""" content = RemoveContentMarkedNoVerify(content) content = RemoveJavaScriptMultiLineComment(content) content = RemoveJavaScriptSingleLineComment(content) content = content.replace("var %s = " % root_name, "%s = " % root_name) content = EscapeJavascriptRegex(content) return content def ConvertJavaScriptFileToPython(fname, root_name): return ConvertJavaScriptToPython( "".join(open(fname, "r").readlines()), root_name) def EvaluatePythonExpressionFromText(content, root_name, scope): """Compiles and evaluates a Python script in a restricted environment.""" """First compiles and then evaluates a Python script text in a restricted environment using provided bindings. Returns the resulting bindings if evaluation completed.""" # create a new execution scope that has only the schema terms defined; # remove all other languages constructs including __builtins__ restricted_scope = {} restricted_scope.update(scope) restricted_scope.update({"__builtins__": {}}) code = compile(content, "<string>", "exec") exec code in restricted_scope if not restricted_scope[root_name]: raise Exception("Unable to find '%s'" % root_name) return restricted_scope def EvaluateJavaScriptExpressionFromFile(fname, root_name, scope, error): content = ConvertJavaScriptFileToPython(fname, root_name) try: return EvaluatePythonExpressionFromText(content, root_name, scope) except: error("Unable to parse %s in file %s\n %s" % ( root_name, fname, TextToLineNumberedText(content))) for message in sys.exc_info(): error(str(message)) class Verifier(object): """A class that verifies all course content.""" """A class that knows how to verify Units, Lessons, Assessment and Activities, and understands their relationships.""" def __init__(self): self.schema_helper = SchemaHelper() self.errors = 0 self.warnings = 0 def VerifyUnitFields(self, units): for unit in units: if not IsOneOf(unit.now_available, [True, False]): self.error("Bad now_available '%s' for unit id %s; expected 'True' or 'False'" % ( unit.now_available, unit.id)) if not IsOneOf(unit.type, ["U", "A", "O"]): self.error("Bad type '%s' for unit id %s; expected 'U', 'A', or 'O'" % ( unit.type, unit.id)) if unit.type == "A": if not IsOneOf(unit.unit_id, ("Pre", "Mid", "Fin")): self.error( "Bad unit_id '%s'; expected 'Pre', 'Mid' or 'Fin' for unit id %s" % (unit.unit_id, unit.id)) if unit.type == "U": if not IsInteger(unit.unit_id): self.error("Expected integer unit_id, found %s in unit id %s" % ( unit.unit_id, unit.id)) def VerifyLessonFields(self, lessons): for lesson in lessons: if not IsOneOf(lesson.lesson_activity, ["yes", ""]): self.error("Bad lesson_activity '%s' for lesson_id %s" % (lesson.lesson_activity, lesson.lesson_id)) def VerifyUnitLessonRelationships(self, units, lessons): """Checks how units relate to lessons and otherwise.""" """Checks that each lesson points to a valid unit and all lessons are used by one of the units.""" used_lessons = [] units.sort(key=lambda x: x.id) #for unit in units: for i in range(0, len(units)): unit = units[i] # check that unit ids are 1-based and sequential if unit.id != i + 1: self.error("Unit out of order: %s" % (unit.id)) # get the list of lessons for each unit self.fine("Unit %s: %s" % (unit.id, unit.title)) unit_lessons = [] for lesson in lessons: if lesson.unit_id == unit.unit_id: unit_lessons.append(lesson) used_lessons.append(lesson) # inspect all lessons for the current unit unit_lessons.sort(key=lambda x: x.lesson_id) for j in range(0, len(unit_lessons)): lesson = unit_lessons[j] # check that lesson_ids are 1-based and sequential if lesson.lesson_id != j + 1: self.warn( "Lesson lesson_id is out of order: expected %s, found %s (%s)" % (j + 1, lesson.lesson_id, lesson.ToIdString())) self.fine(" Lesson %s: %s" % (lesson.lesson_id, lesson.lesson_title)) # find lessons not used by any of the units unused_lessons = list(lessons) for lesson in used_lessons: unused_lessons.remove(lesson) for lesson in unused_lessons: self.warn("Unused lesson_id %s (%s)" % ( lesson.lesson_id, lesson.ToIdString())) # check all lessons point to known units for lesson in lessons: has = False for unit in units: if lesson.unit_id == unit.unit_id: has = True break if not has: self.error("Lesson has unknown unit_id %s (%s)" % (lesson.unit_id, lesson.ToIdString())) def VerifyActivities(self, lessons): """Loads and verifies all activities.""" self.info("Loading activities:") count = 0 for lesson in lessons: if lesson.lesson_activity == "yes": count += 1 fname = os.path.join( os.path.dirname(__file__), "../assets/js/activity-" + str(lesson.unit_id) + "." + str(lesson.lesson_id) + ".js") if not os.path.exists(fname): self.error(" Missing activity: %s" % fname) else: activity = EvaluateJavaScriptExpressionFromFile( fname, "activity", Activity().scope, self.error) self.VerifyActivityInstance(activity, fname) self.info("Read %s activities" % count) def VerifyAssessment(self, units): """Loads and verifies all assessments.""" self.info("Loading assessment:") count = 0 for unit in units: if unit.type == "A": count += 1 fname = os.path.join( os.path.dirname(__file__), "../assets/js/assessment-" + str(unit.unit_id) + ".js") if not os.path.exists(fname): self.error(" Missing assessment: %s" % fname) else: assessment = EvaluateJavaScriptExpressionFromFile( fname, "assessment", Assessment().scope, self.error) self.VerifyAssessmentInstance(assessment, fname) self.info("Read %s assessments" % count) def FormatParseLog(self): return "Parse log:\n%s" % "\n".join(self.schema_helper.parse_log) def VerifyAssessmentInstance(self, scope, fname): """Verifies compliance of assessment with schema.""" if scope: try: self.schema_helper.CheckInstancesMatchSchema( scope["assessment"], SCHEMA["assessment"], "assessment") self.info(" Verified assessment %s" % fname) if OUTPUT_DEBUG_LOG: self.info(self.FormatParseLog()) except SchemaException as e: self.error(" Error in assessment %s\n%s" % ( fname, self.FormatParseLog())) raise e else: self.error(" Unable to evaluate 'assessment =' in %s" % fname) def VerifyActivityInstance(self, scope, fname): """Verifies compliance of activity with schema.""" if scope: try: self.schema_helper.CheckInstancesMatchSchema( scope["activity"], SCHEMA["activity"], "activity") self.info(" Verified activity %s" % fname) if OUTPUT_DEBUG_LOG: self.info(self.FormatParseLog()) except SchemaException as e: self.error(" Error in activity %s\n%s" % ( fname, self.FormatParseLog())) raise e else: self.error(" Unable to evaluate 'activity =' in %s" % fname) def fine(self, x): if OUTPUT_FINE_LOG: self.echo_func("FINE: " + x) def info(self, x): self.echo_func("INFO: " + x) def warn(self, x): self.warnings += 1 self.echo_func("WARNING: " + x) def error(self, x): self.errors += 1 self.echo_func("ERROR: " + x) def LoadAndVerifyModel(self, echo_func): """Loads, parses and verifies all content for a course.""" self.echo_func = echo_func self.info("Started verification in: %s" % __file__) unit_file = os.path.join(os.path.dirname(__file__), "../data/unit.csv") lesson_file = os.path.join(os.path.dirname(__file__), "../data/lesson.csv") self.info("Loading units from: %s" % unit_file) units = ReadObjectsFromCsvFile(unit_file, UNITS_HEADER, lambda: Unit()) self.info("Read %s units" % len(units)) self.info("Loading lessons from: %s" % lesson_file) lessons = ReadObjectsFromCsvFile(lesson_file, LESSONS_HEADER, lambda: Lesson()) self.info("Read %s lessons" % len(lessons)) self.VerifyUnitFields(units) self.VerifyLessonFields(lessons) self.VerifyUnitLessonRelationships(units, lessons) try: self.VerifyActivities(lessons) self.VerifyAssessment(units) except SchemaException as e: self.error(str(e)) self.info("Schema usage statistics: %s" % self.schema_helper.type_stats) self.info("Completed verification: %s warnings, %s errors." % (self.warnings, self.errors)) return self.errors def RunAllRegexUnitTests(): assert EscapeJavascriptRegex( "blah regex: /site:bls.gov?/i, blah") == ( "blah regex: regex(\"/site:bls.gov?/i\"), blah") assert EscapeJavascriptRegex( "blah regex: /site:http:\/\/www.google.com?q=abc/i, blah") == ( "blah regex: regex(\"/site:http:\/\/www.google.com?q=abc/i\"), blah") assert RemoveJavaScriptMultiLineComment( "blah\n/*\ncomment\n*/\nblah") == "blah\n\nblah" assert RemoveJavaScriptMultiLineComment( "blah\nblah /*\ncomment\nblah */\nblah") == ( "blah\nblah \nblah") assert RemoveJavaScriptSingleLineComment( "blah\n// comment\nblah") == "blah\n\nblah" assert RemoveJavaScriptSingleLineComment( "blah\nblah http://www.foo.com\nblah") == ( "blah\nblah http://www.foo.com\nblah") assert RemoveJavaScriptSingleLineComment( "blah\nblah // comment\nblah") == "blah\nblah\nblah" assert RemoveJavaScriptSingleLineComment( "blah\nblah // comment http://www.foo.com\nblah") == "blah\nblah\nblah" assert RemoveContentMarkedNoVerify( "blah1\n// <gcb-no-verify>/blah2\n// </gcb-no-verify>\nblah3") == ( "blah1\n// \nblah3") def RunAllSchemaHelperUnitTests(): def AssertSame(a, b): if a != b: raise Exception("Expected:\n %s\nFound:\n %s" % (a, b)) def AssertPass(instances, types, expected_result=None): try: schema_helper = SchemaHelper() result = schema_helper.CheckInstancesMatchSchema(instances, types, "test") if OUTPUT_DEBUG_LOG: print "\n".join(schema_helper.parse_log) if expected_result: AssertSame(expected_result, result) except SchemaException as e: if OUTPUT_DEBUG_LOG: print str(e) print "\n".join(schema_helper.parse_log) raise def AssertFails(func): try: func() raise Exception("Expected to fail") except SchemaException as e: if OUTPUT_DEBUG_LOG: print str(e) pass def AssertFail(instances, types): AssertFails(lambda: AssertPass(instances, types)) # CSV tests ReadObjectsFromCsv([["id", "type"], [1, "none"]], "id,type", lambda: Unit()) AssertFails(lambda: ReadObjectsFromCsv( [["id", "type"], [1, "none"]], "id,type,title", lambda: Unit())) AssertFails(lambda: ReadObjectsFromCsv( [["id", "type", "title"], [1, "none"]], "id,type,title", lambda: Unit())) # context tests AssertSame( Context().New([]).New(["a"]).New(["b", "c"]).FormatPath(), ("//a/b/c")) # simple map tests AssertPass({"name": "Bob"}, {"name": STRING}, None) AssertFail("foo", "bar") AssertFail({"name": "Bob"}, {"name": INTEGER}) AssertFail({"name": 12345}, {"name": STRING}) AssertFail({"amount": 12345}, {"name": INTEGER}) AssertFail({"regex": CORRECT}, {"regex": REGEX}) AssertPass({"name": "Bob"}, {"name": STRING, "phone": STRING}) AssertPass({"name": "Bob"}, {"phone": STRING, "name": STRING}) AssertPass({"name": "Bob"}, {"phone": STRING, "name": STRING, "age": INTEGER}) # mixed attributes tests AssertPass({"colors": ["red", "blue"]}, {"colors": [STRING]}) AssertPass({"colors": []}, {"colors": [STRING]}) AssertFail({"colors": {"red": "blue"}}, {"colors": [STRING]}) AssertFail({"colors": {"red": "blue"}}, {"colors": [FLOAT]}) AssertFail({"colors": ["red", "blue", 5.5]}, {"colors": [STRING]}) AssertFail({"colors": ["red", "blue", {"foo": "bar"}]}, {"colors": [STRING]}) AssertFail({"colors": ["red", "blue"], "foo": "bar"}, {"colors": [STRING]}) AssertPass({"colors": ["red", 1]}, {"colors": [[STRING, INTEGER]]}) AssertFail({"colors": ["red", "blue"]}, {"colors": [[STRING, INTEGER]]}) AssertFail({"colors": [1, 2, 3]}, {"colors": [[STRING, INTEGER]]}) AssertFail({"colors": ["red", 1, 5.3]}, {"colors": [[STRING, INTEGER]]}) AssertPass({"colors": ["red", "blue"]}, {"colors": [STRING]}) AssertFail({"colors": ["red", "blue"]}, {"colors": [[STRING]]}) AssertFail({"colors": ["red", ["blue"]]}, {"colors": [STRING]}) AssertFail({"colors": ["red", ["blue", "green"]]}, {"colors": [STRING]}) # required attribute tests AssertPass({"colors": ["red", 5]}, {"colors": [[STRING, INTEGER]]}) AssertFail({"colors": ["red", 5]}, {"colors": [[INTEGER, STRING]]}) AssertPass({"colors": ["red", 5]}, {"colors": [STRING, INTEGER]}) AssertPass({"colors": ["red", 5]}, {"colors": [INTEGER, STRING]}) AssertFail({"colors": ["red", 5, "FF0000"]}, {"colors": [[STRING, INTEGER]]}) # an array and a map of primitive type tests AssertPass({"color": {"name": "red", "rgb": "FF0000"}}, {"color": {"name": STRING, "rgb": STRING}}) AssertFail({"color": {"name": "red", "rgb": ["FF0000"]}}, {"color": {"name": STRING, "rgb": STRING}}) AssertFail({"color": {"name": "red", "rgb": "FF0000"}}, {"color": {"name": STRING, "rgb": INTEGER}}) AssertFail({"color": {"name": "red", "rgb": "FF0000"}}, {"color": {"name": STRING, "rgb": {"hex": STRING}}}) AssertPass({"color": {"name": "red", "rgb": "FF0000"}}, {"color": {"name": STRING, "rgb": STRING}}) AssertPass({"colors": [{"name": "red", "rgb": "FF0000"}, {"name": "blue", "rgb": "0000FF"}]}, {"colors": [{"name": STRING, "rgb": STRING}]}) AssertFail({"colors": [{"name": "red", "rgb": "FF0000"}, {"phone": "blue", "rgb": "0000FF"}]}, {"colors": [{"name": STRING, "rgb": STRING}]}) # boolean type tests AssertPass({"name": "Bob", "active": "true"}, {"name": STRING, "active": BOOLEAN}) AssertPass({"name": "Bob", "active": True}, {"name": STRING, "active": BOOLEAN}) AssertPass({"name": "Bob", "active": [5, True, "False"]}, {"name": STRING, "active": [INTEGER, BOOLEAN]}) AssertPass({"name": "Bob", "active": [5, True, "false"]}, {"name": STRING, "active": [STRING, INTEGER, BOOLEAN]}) AssertFail({"name": "Bob", "active": [5, True, "False"]}, {"name": STRING, "active": [[INTEGER, BOOLEAN]]}) # optional attribute tests AssertPass({"points": [{"x": 1, "y": 2, "z": 3}, {"x": 3, "y": 2, "z": 1}, {"x": 2, "y": 3, "z": 1}]}, {"points": [{"x": INTEGER, "y": INTEGER, "z": INTEGER}]}) AssertPass({"points": [{"x": 1, "z": 3}, {"x": 3, "y": 2}, {"y": 3, "z": 1}]}, {"points": [{"x": INTEGER, "y": INTEGER, "z": INTEGER}]}) AssertPass({"account": [{"name": "Bob", "age": 25, "active": True}]}, {"account": [{"age": INTEGER, "name": STRING, "active": BOOLEAN}]}) AssertPass({"account": [{"name": "Bob", "active": True}]}, {"account": [{"age": INTEGER, "name": STRING, "active": BOOLEAN}]}) # nested array tests AssertFail({"name": "Bob", "active": [5, True, "false"]}, {"name": STRING, "active": [[BOOLEAN]]}) AssertFail({"name": "Bob", "active": [True]}, {"name": STRING, "active": [[STRING]]}) AssertPass({"name": "Bob", "active": ["true"]}, {"name": STRING, "active": [[STRING]]}) AssertPass({"name": "flowers", "price": ["USD", 9.99]}, {"name": STRING, "price": [[STRING, FLOAT]]}) AssertPass({"name": "flowers", "price": [["USD", 9.99], ["CAD", 11.79], ["RUB", 250.23]]}, {"name": STRING, "price": [[STRING, FLOAT]]}) # selector tests AssertPass({"likes": [{"state": "CA", "food": "cheese"}, {"state": "NY", "drink": "wine"}]}, {"likes": [{"state": "CA", "food": STRING}, {"state": "NY", "drink": STRING}]}) AssertPass({"likes": [{"state": "CA", "food": "cheese"}, {"state": "CA", "food": "nuts"}]}, {"likes": [{"state": "CA", "food": STRING}, {"state": "NY", "drink": STRING}]}) AssertFail({"likes": {"state": "CA", "drink": "cheese"}}, {"likes": [{"state": "CA", "food": STRING}, {"state": "NY", "drink": STRING}]}) def RunAllUnitTests(): RunAllRegexUnitTests() RunAllSchemaHelperUnitTests() RunAllUnitTests() Verifier().LoadAndVerifyModel(Echo)
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime from google.appengine.ext import db class Student(db.Model): """Student profile.""" enrolled_date = db.DateTimeProperty(auto_now_add=True) precourse_answer = db.TextProperty() midterm_answer = db.TextProperty() final_answer = db.TextProperty() precourse_score = db.IntegerProperty() midterm_score = db.IntegerProperty() final_score = db.IntegerProperty() overall_score = db.IntegerProperty() name = db.StringProperty() class Unit(db.Model): """Unit metadata.""" id = db.IntegerProperty() type = db.StringProperty() unit_id = db.StringProperty() title = db.StringProperty() release_date = db.StringProperty() now_available = db.BooleanProperty() class Lesson(db.Model): """Lesson metadata.""" unit_id = db.IntegerProperty() id = db.IntegerProperty() title = db.StringProperty() objectives = db.TextProperty() video = db.TextProperty() notes = db.TextProperty() activity = db.StringProperty() activity_title = db.StringProperty()
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, logging from models.models import Student, Unit, Lesson import webapp2, jinja2 from google.appengine.api import users, memcache, taskqueue from google.appengine.ext import db template_dir = os.path.join(os.path.dirname(__file__), '../views') jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir)) """ Base handler """ class BaseHandler(webapp2.RequestHandler): templateValue = {} user = users.get_current_user() logging.info(user) def getUser(self): """Validate user exists and in early access list.""" user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) else: return user def render(self, templateFile): template = jinja_environment.get_template(templateFile) self.response.out.write(template.render(self.templateValue)) """ Student Handler """ class StudentHandler(webapp2.RequestHandler): templateValue = {} def getStudent(self): user = users.get_current_user() if user: student = memcache.get(user.email()) if not student: student = Student.get_by_key_name(user.email()) memcache.set(user.email(), student) return student else: self.redirect(users.create_login_url(self.request.uri)) def render(self, templateFile): template = jinja_environment.get_template(templateFile) html = template.render(self.templateValue) self.response.out.write(html) """ Handler for course registration """ class RegisterHandler(BaseHandler): def get(self): user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url('/') navbar = {'registration': True} self.templateValue['navbar'] = navbar # Check for existing registration -> redirect to course page student = Student.get_by_key_name(user.email()) if student is None: self.render('register.html') else: self.redirect('/course') def post(self): user = users.get_current_user() if user: email = user.email() self.templateValue['email'] = email self.templateValue['logoutUrl'] = users.create_logout_url('/') # Restrict the maximum course size to 250000 people # FIXME: you can change this number if you wish. students = Student.all(keys_only=True) if (students.count() > 249999): self.templateValue['course_status'] = 'full' # Create student record name = self.request.get('form01') student = Student(key_name=user.email(), name=name) student.put() # Render registration confirmation page navbar = {'registration': True} self.templateValue['navbar'] = navbar self.render('confirmation.html') """ Handler for forum page """ class ForumHandler(BaseHandler): def get(self): navbar = {'forum':True} self.templateValue['navbar'] = navbar user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url('/') self.render('forum.html')
Python
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging, json from google.appengine.api import users, memcache from utils import StudentHandler from models.models import Student, Unit, Lesson """ Handler for course page """ class CourseHandler(StudentHandler): def get(self): # Check for enrollment status student = self.getStudent() if student: # Get unit data and set template values units = memcache.get('units') if units is None: units = Unit.all().order('id') memcache.add('units', units) self.templateValue['units'] = units # Set template values for nav bar navbar = {'course': True} self.templateValue['navbar'] = navbar # Set template values for user user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url("/") # Render course page self.render('course.html') else: self.redirect('/register') """ Handler for unit page """ class UnitHandler(StudentHandler): def get(self): # Check for enrollment status student = self.getStudent() if student: # Extract incoming args c = self.request.get("unit") if not c: unit_id = 1 else: unit_id = int(c) self.templateValue['unit_id'] = unit_id l = self.request.get("lesson") if not l: lesson_id = 1 else: lesson_id = int(l) self.templateValue['lesson_id'] = lesson_id # Set template values for a unit and its lesson entities units = memcache.get('units') if units is None: units = Unit.all().order('id') memcache.add('units', units) for unit in units: if unit.unit_id == str(unit_id): self.templateValue['units'] = unit lessons = memcache.get('lessons' + str(unit_id)) if lessons is None: lessons = Lesson.all().filter('unit_id =', unit_id).order('id') memcache.add('lessons' + str(unit_id), lessons) self.templateValue['lessons'] = lessons # Set template values for nav bar navbar = {'course':True} self.templateValue['navbar'] = navbar # Set template values for back and next nav buttons if lesson_id == 1: self.templateValue['back_button_url'] = '' if lessons[lesson_id - 1].activity: self.templateValue['next_button_url'] = '/activity?unit=' + str(unit_id) + '&lesson=' + str(lesson_id) else: self.templateValue['next_button_url'] = '/unit?unit=' + str(unit_id) + '&lesson=' + str(lesson_id + 1) elif lesson_id == lessons.count(): if lessons[lesson_id - 2].activity: self.templateValue['back_button_url'] = '/activity?unit=' + str(unit_id) + '&lesson=' + str(lesson_id - 1) else: self.templateValue['back_button_url'] = '/unit?unit=' + str(unit_id) + '&lesson=' + str(lesson_id - 1) if lessons[lesson_id - 1].activity: self.templateValue['next_button_url'] = '/activity?unit=' + str(unit_id) + '&lesson=' + str(lesson_id) else: self.templateValue['next_button_url'] = '' else: if lessons[lesson_id - 2].activity: self.templateValue['back_button_url'] = '/activity?unit=' + str(unit_id) + '&lesson=' + str(lesson_id - 1) else: self.templateValue['back_button_url'] = '/unit?unit=' + str(unit_id) + '&lesson=' + str(lesson_id - 1) if lessons[lesson_id - 1].activity: self.templateValue['next_button_url'] = '/activity?unit=' + str(unit_id) + '&lesson=' + str(lesson_id) else: self.templateValue['next_button_url'] = '/unit?unit=' + str(unit_id) + '&lesson=' + str(lesson_id + 1) # Set template values for user user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url("/") # Render unit page with all lessons in tabs self.render('unit.html') else: self.redirect('/register') """ Handler for activity page. """ class ActivityHandler(StudentHandler): def get(self): # Check for enrollment status student = self.getStudent() if student: # Extract incoming args c = self.request.get("unit") if not c: unit_id = 1 else: unit_id = int(c) self.templateValue['unit_id'] = unit_id l = self.request.get('lesson') if not l: lesson_id = 1 else: lesson_id = int(l) self.templateValue['lesson_id'] = lesson_id # Set template values for a unit and its lesson entities units = memcache.get('units') if units is None: units = Unit.all().order('id') memcache.add('units', units) for unit in units: if unit.unit_id == unit_id: self.templateValue['units'] = unit lessons = memcache.get('lessons' + str(unit_id)) if lessons is None: lessons = Lesson.all().filter('unit_id =', unit_id).order('id') memcache.add('lessons' + str(unit_id), lessons) self.templateValue['lessons'] = lessons # Set template values for nav-x bar navbar = {'course':True} self.templateValue['navbar'] = navbar # Set template values for back and next nav buttons self.templateValue['back_button_url'] = '/unit?unit=' + str(unit_id) + '&lesson=' + str(lesson_id) if lesson_id == lessons.count(): self.templateValue['next_button_url'] = '' else: self.templateValue['next_button_url'] = '/unit?unit=' + str(unit_id) + '&lesson=' + str(lesson_id + 1) # Set template values for user user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url("/") # Render activity page self.render('activity.html') else: self.redirect('/register') """ Handler for assessment page """ class AssessmentHandler(StudentHandler): def get(self): # Check for enrollment status student = self.getStudent() if student: # Extract incoming args n = self.request.get("name") if not n: n = 'Pre' self.templateValue['name'] = n # Set template values for nav-x bar navbar = {'course':True} self.templateValue['navbar'] = navbar # Set template values for user user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url("/") # Render assessment page self.render('assessment.html') else: self.redirect('/register') """ Handler for saving assessment answers """ class AnswerHandler(StudentHandler): def post(self): # Read in answers answer = json.dumps(self.request.POST.items()) assessment_type = self.request.get('assessment_type') num_correct = self.request.get('num_correct') num_questions = self.request.get('num_questions') # Check for enrollment status student = self.getStudent() if student: logging.info(student.key().name() + ':' + answer) # Find student entity and save answers student = Student.get_by_key_name(student.key().name().encode('utf8')) # FIXME: Currently the demonstration course is hardcoded to have # three assessments: 'precourse', 'midcourse', and 'postcourse'. # If you would like to have different types of assessments or # different score weights/thresholds, edit the code below ... if assessment_type == 'precourse': score = self.request.get('score') student.precourse_answer = answer student.precourse_score = int(float(score)) elif assessment_type == 'midcourse': score = self.request.get('score') student.midterm_answer = answer student.midterm_score = int(float(score)) elif assessment_type == 'postcourse': score = self.request.get('score') student.final_answer = answer student.final_score = int(float(score)) if not student.midterm_score: student.midterm_score = 0 student.overall_score = int((0.35 * student.midterm_score) + (0.65 * student.final_score)) self.templateValue['score'] = student.overall_score if student.overall_score >= 70: assessment_type = 'postcourse_pass' else: assessment_type = 'postcourse_fail' student.put() # Update student entity in memcache memcache.set(student.key().name(), student) # Set template values for nav-x bar navbar = {'course':True} self.templateValue['navbar'] = navbar # Set template values for user user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url("/") # Render confirmation page self.templateValue['assessment'] = assessment_type self.render('test_confirmation.html') else: self.redirect('/register')
Python
#! /usr/bin/env python # encoding: utf-8 # waf 1.6.2 VERSION='0.3.3' import sys APPNAME='p2t' top = '.' out = 'build' CPP_SOURCES = ['poly2tri/common/shapes.cc', 'poly2tri/sweep/cdt.cc', 'poly2tri/sweep/advancing_front.cc', 'poly2tri/sweep/sweep_context.cc', 'poly2tri/sweep/sweep.cc', 'testbed/main.cc'] from waflib.Tools.compiler_cxx import cxx_compiler cxx_compiler['win32'] = ['g++'] #Platform specific libs if sys.platform == 'win32': # MS Windows sys_libs = ['glfw', 'opengl32'] elif sys.platform == 'darwin': # Apple OSX sys_libs = ['glfw', 'OpenGL'] else: # GNU/Linux, BSD, etc sys_libs = ['glfw', 'GL'] def options(opt): print(' set_options') opt.load('compiler_cxx') def configure(conf): print(' calling the configuration') conf.load('compiler_cxx') conf.env.CXXFLAGS = ['-O3', '-ffast-math'] conf.env.DEFINES_P2T = ['P2T'] conf.env.LIB_P2T = sys_libs def build(bld): print(' building') bld.program(features = 'cxx cxxprogram', source=CPP_SOURCES, target = 'p2t', uselib = 'P2T')
Python
''' Module which brings history information about files from Mercurial. @author: Rodrigo Damazio ''' import re import subprocess REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*') def _GetOutputLines(args): ''' Runs an external process and returns its output as a list of lines. @param args: the arguments to run ''' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines = True, shell = False) output = process.communicate()[0] return output.splitlines() def FillMercurialRevisions(filename, parsed_file): ''' Fills the revs attribute of all strings in the given parsed file with a list of revisions that touched the lines corresponding to that string. @param filename: the name of the file to get history for @param parsed_file: the parsed file to modify ''' # Take output of hg annotate to get revision of each line output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename]) # Create a map of line -> revision (key is list index, line 0 doesn't exist) line_revs = ['dummy'] for line in output_lines: rev_match = REVISION_REGEX.match(line) if not rev_match: raise 'Unexpected line of output from hg: %s' % line rev_hash = rev_match.group('hash') line_revs.append(rev_hash) for str in parsed_file.itervalues(): # Get the lines that correspond to each string start_line = str['startLine'] end_line = str['endLine'] # Get the revisions that touched those lines revs = [] for line_number in range(start_line, end_line + 1): revs.append(line_revs[line_number]) # Merge with any revisions that were already there # (for explict revision specification) if 'revs' in str: revs += str['revs'] # Assign the revisions to the string str['revs'] = frozenset(revs) def DoesRevisionSuperceed(filename, rev1, rev2): ''' Tells whether a revision superceeds another. This essentially means that the older revision is an ancestor of the newer one. This also returns True if the two revisions are the same. @param rev1: the revision that may be superceeding the other @param rev2: the revision that may be superceeded @return: True if rev1 superceeds rev2 or they're the same ''' if rev1 == rev2: return True # TODO: Add filename args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename] output_lines = _GetOutputLines(args) return rev2 in output_lines def NewestRevision(filename, rev1, rev2): ''' Returns which of two revisions is closest to the head of the repository. If none of them is the ancestor of the other, then we return either one. @param rev1: the first revision @param rev2: the second revision ''' if DoesRevisionSuperceed(filename, rev1, rev2): return rev1 return rev2
Python
#!/usr/bin/python ''' Entry point for My Tracks i18n tool. @author: Rodrigo Damazio ''' import mytracks.files import mytracks.translate import mytracks.validate import sys def Usage(): print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0] print 'Commands are:' print ' cleanup' print ' translate' print ' validate' sys.exit(1) def Translate(languages): ''' Asks the user to interactively translate any missing or oudated strings from the files for the given languages. @param languages: the languages to translate ''' validator = mytracks.validate.Validator(languages) validator.Validate() missing = validator.missing_in_lang() outdated = validator.outdated_in_lang() for lang in languages: untranslated = missing[lang] + outdated[lang] if len(untranslated) == 0: continue translator = mytracks.translate.Translator(lang) translator.Translate(untranslated) def Validate(languages): ''' Computes and displays errors in the string files for the given languages. @param languages: the languages to compute for ''' validator = mytracks.validate.Validator(languages) validator.Validate() error_count = 0 if (validator.valid()): print 'All files OK' else: for lang, missing in validator.missing_in_master().iteritems(): print 'Missing in master, present in %s: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, missing in validator.missing_in_lang().iteritems(): print 'Missing in %s, present in master: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, outdated in validator.outdated_in_lang().iteritems(): print 'Outdated in %s: %s:' % (lang, str(outdated)) error_count = error_count + len(outdated) return error_count if __name__ == '__main__': argv = sys.argv argc = len(argv) if argc < 2: Usage() languages = mytracks.files.GetAllLanguageFiles() if argc == 3: langs = set(argv[2:]) if not langs.issubset(languages): raise 'Language(s) not found' # Filter just to the languages specified languages = dict((lang, lang_file) for lang, lang_file in languages.iteritems() if lang in langs or lang == 'en' ) cmd = argv[1] if cmd == 'translate': Translate(languages) elif cmd == 'validate': error_count = Validate(languages) else: Usage() error_count = 0 print '%d errors found.' % error_count
Python
''' Module which prompts the user for translations and saves them. TODO: implement @author: Rodrigo Damazio ''' class Translator(object): ''' classdocs ''' def __init__(self, language): ''' Constructor ''' self._language = language def Translate(self, string_names): print string_names
Python
''' Module which compares languague files to the master file and detects issues. @author: Rodrigo Damazio ''' import os from mytracks.parser import StringsParser import mytracks.history class Validator(object): def __init__(self, languages): ''' Builds a strings file validator. Params: @param languages: a dictionary mapping each language to its corresponding directory ''' self._langs = {} self._master = None self._language_paths = languages parser = StringsParser() for lang, lang_dir in languages.iteritems(): filename = os.path.join(lang_dir, 'strings.xml') parsed_file = parser.Parse(filename) mytracks.history.FillMercurialRevisions(filename, parsed_file) if lang == 'en': self._master = parsed_file else: self._langs[lang] = parsed_file self._Reset() def Validate(self): ''' Computes whether all the data in the files for the given languages is valid. ''' self._Reset() self._ValidateMissingKeys() self._ValidateOutdatedKeys() def valid(self): return (len(self._missing_in_master) == 0 and len(self._missing_in_lang) == 0 and len(self._outdated_in_lang) == 0) def missing_in_master(self): return self._missing_in_master def missing_in_lang(self): return self._missing_in_lang def outdated_in_lang(self): return self._outdated_in_lang def _Reset(self): # These are maps from language to string name list self._missing_in_master = {} self._missing_in_lang = {} self._outdated_in_lang = {} def _ValidateMissingKeys(self): ''' Computes whether there are missing keys on either side. ''' master_keys = frozenset(self._master.iterkeys()) for lang, file in self._langs.iteritems(): keys = frozenset(file.iterkeys()) missing_in_master = keys - master_keys missing_in_lang = master_keys - keys if len(missing_in_master) > 0: self._missing_in_master[lang] = missing_in_master if len(missing_in_lang) > 0: self._missing_in_lang[lang] = missing_in_lang def _ValidateOutdatedKeys(self): ''' Computers whether any of the language keys are outdated with relation to the master keys. ''' for lang, file in self._langs.iteritems(): outdated = [] for key, str in file.iteritems(): # Get all revisions that touched master and language files for this # string. master_str = self._master[key] master_revs = master_str['revs'] lang_revs = str['revs'] if not master_revs or not lang_revs: print 'WARNING: No revision for %s in %s' % (key, lang) continue master_file = os.path.join(self._language_paths['en'], 'strings.xml') lang_file = os.path.join(self._language_paths[lang], 'strings.xml') # Assume that the repository has a single head (TODO: check that), # and as such there is always one revision which superceeds all others. master_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2), master_revs) lang_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2), lang_revs) # If the master version is newer than the lang version if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev): outdated.append(key) if len(outdated) > 0: self._outdated_in_lang[lang] = outdated
Python
''' Module for dealing with resource files (but not their contents). @author: Rodrigo Damazio ''' import os.path from glob import glob import re MYTRACKS_RES_DIR = 'MyTracks/res' ANDROID_MASTER_VALUES = 'values' ANDROID_VALUES_MASK = 'values-*' def GetMyTracksDir(): ''' Returns the directory in which the MyTracks directory is located. ''' path = os.getcwd() while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)): if path == '/': raise 'Not in My Tracks project' # Go up one level path = os.path.split(path)[0] return path def GetAllLanguageFiles(): ''' Returns a mapping from all found languages to their respective directories. ''' mytracks_path = GetMyTracksDir() res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK) language_dirs = glob(res_dir) master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES) if len(language_dirs) == 0: raise 'No languages found!' if not os.path.isdir(master_dir): raise 'Couldn\'t find master file' language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs] language_tuples.append(('en', master_dir)) return dict(language_tuples)
Python
''' Module which parses a string XML file. @author: Rodrigo Damazio ''' from xml.parsers.expat import ParserCreate import re #import xml.etree.ElementTree as ET class StringsParser(object): ''' Parser for string XML files. This object is not thread-safe and should be used for parsing a single file at a time, only. ''' def Parse(self, file): ''' Parses the given file and returns a dictionary mapping keys to an object with attributes for that key, such as the value, start/end line and explicit revisions. In addition to the standard XML format of the strings file, this parser supports an annotation inside comments, in one of these formats: <!-- KEEP_PARENT name="bla" --> <!-- KEEP_PARENT name="bla" rev="123456789012" --> Such an annotation indicates that we're explicitly inheriting form the master file (and the optional revision says that this decision is compatible with the master file up to that revision). @param file: the name of the file to parse ''' self._Reset() # Unfortunately expat is the only parser that will give us line numbers self._xml_parser = ParserCreate() self._xml_parser.StartElementHandler = self._StartElementHandler self._xml_parser.EndElementHandler = self._EndElementHandler self._xml_parser.CharacterDataHandler = self._CharacterDataHandler self._xml_parser.CommentHandler = self._CommentHandler file_obj = open(file) self._xml_parser.ParseFile(file_obj) file_obj.close() return self._all_strings def _Reset(self): self._currentString = None self._currentStringName = None self._currentStringValue = None self._all_strings = {} def _StartElementHandler(self, name, attrs): if name != 'string': return if 'name' not in attrs: return assert not self._currentString assert not self._currentStringName self._currentString = { 'startLine' : self._xml_parser.CurrentLineNumber, } if 'rev' in attrs: self._currentString['revs'] = [attrs['rev']] self._currentStringName = attrs['name'] self._currentStringValue = '' def _EndElementHandler(self, name): if name != 'string': return assert self._currentString assert self._currentStringName self._currentString['value'] = self._currentStringValue self._currentString['endLine'] = self._xml_parser.CurrentLineNumber self._all_strings[self._currentStringName] = self._currentString self._currentString = None self._currentStringName = None self._currentStringValue = None def _CharacterDataHandler(self, data): if not self._currentString: return self._currentStringValue += data _KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+' r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?' r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*', re.MULTILINE | re.DOTALL) def _CommentHandler(self, data): keep_parent_match = self._KEEP_PARENT_REGEX.match(data) if not keep_parent_match: return name = keep_parent_match.group('name') self._all_strings[name] = { 'keepParent' : True, 'startLine' : self._xml_parser.CurrentLineNumber, 'endLine' : self._xml_parser.CurrentLineNumber } rev = keep_parent_match.group('rev') if rev: self._all_strings[name]['revs'] = [rev]
Python
from maya.cmds import * from names import Parity, Name, camelCaseToNice from vectors import Vector, Colour from control import attrState, NORMAL, HIDE, LOCK_HIDE, NO_KEY from apiExtensions import asMObject, castToMObjects, cmpNodes from mayaDecorators import d_unifyUndo from maya.OpenMaya import MGlobal from referenceUtils import ReferencedNode import names import filesystem import typeFactories import inspect import meshUtils import maya.cmds as cmd import profileDecorators #now do maya imports and maya specific assignments import api import maya.cmds as cmd import rigUtils from rigUtils import ENGINE_FWD, ENGINE_UP, ENGINE_SIDE from rigUtils import MAYA_SIDE, MAYA_FWD, MAYA_UP from rigUtils import Axis, resetSkinCluster mel = api.mel AXES = Axis.BASE_AXES eval = __builtins__[ 'eval' ] #restore the eval function to point to python's eval mayaVar = float( mel.eval( 'getApplicationVersionAsFloat()' ) ) TOOL_NAME = 'skeletonBuilder' CHANNELS = ('x', 'y', 'z') TYPICAL_HEIGHT = 70 #maya units HUD_NAME = 'skeletonBuilderJointCountHUD' #these are the symbols to use as standard rotation axes on bones... BONE_AIM_VECTOR = ENGINE_FWD #this is the axis the joint should bank around, in general the axis the "aims" at the child joint BONE_ROTATE_VECTOR = ENGINE_SIDE #this is the axis of "primary rotation" for the joint. for example, the elbow would rotate primarily in this axis, as would knees and fingers BONE_AIM_AXIS = Axis.FromVector( BONE_AIM_VECTOR ) BONE_ROTATE_AXIS = Axis.FromVector( BONE_ROTATE_VECTOR ) _tmp = BONE_AIM_AXIS.otherAxes() _tmp.remove( BONE_ROTATE_AXIS ) BONE_OTHER_AXIS = _tmp[0] #this is the "other" axis - ie the one thats not either BONE_AIM_AXIS or BONE_ROTATE_AXIS BONE_OTHER_VECTOR = BONE_OTHER_AXIS.asVector() del( _tmp ) getLocalAxisInDirection = rigUtils.getLocalAxisInDirection getPlaneNormalForObjects = rigUtils.getPlaneNormalForObjects #try to load the zooMirror.py plugin try: loadPlugin( 'zooMirror.py', quiet=True ) except: import zooToolbox zooToolbox.loadZooPlugin( 'zooMirror.py' ) def getScaleFromMeshes(): ''' determines a scale based on the visible meshes in the scene. If no visible meshes are found, the TYPICAL_HEIGHT value is returend ''' def isVisible( node ): if not getAttr( '%s.v' % node ): return False for p in iterParents( node ): if not getAttr( '%s.v' % p ): return False return True visibleMeshes = [ m for m in (ls( type='mesh' ) or []) if isVisible( m ) ] if not visibleMeshes: return TYPICAL_HEIGHT return rigUtils.getObjsScale( visibleMeshes ) def getScaleFromSkeleton(): #lets see if there is a Root part already scale = 0 for root in Root.IterAllParts(): t = Vector( getAttr( '%s.t' % root[0] )[0] ) scale = t.y scale *= 1.75 #the root is roughly 4 head heights from the ground and the whole body is about 7 head heights - hence 1.75 (7/4) #lets see if there is a spine part - between the root and the spine, we can get a #pretty good idea of the scale for most anatomy types scaleFromSpine = 0 spineCls = SkeletonPart.GetNamedSubclass( 'Spine' ) if spineCls is not None: numSpines = 0 for spine in spineCls.IterAllParts(): items = spine.items items.append( spine.getParent() ) mnx, mny, mnz, mxx, mxy, mxz = rigUtils.getTranslationExtents( items ) XYZ = mxx-mnx, mxy-mny, mxz-mnz maxLen = max( XYZ ) * 1.5 scaleFromSpine += maxLen numSpines += 1 #if there were spine parts found, average their scales, add them to the root scale and average them again if numSpines: scaleFromSpine /= float( numSpines ) scaleFromSpine *= 2.3 #ths spine is roughly 3 head heights, while the whole body is roughly 7 head heights - hence 2.3 (7/3) scale += scaleFromSpine scale /= 2.0 if not scale: return getScaleFromMeshes() return scale def getItemScale( item ): ''' returns the non-skinned "scale" of a joint (or skeleton part "item") This scale uses a few metrics to determine the scale - first, the bounds of any children are calculated and the max side of the bounding box is found, and if non-zero returned. If the item has no children then the radius of the joint is used (if it exists) otherwise the magnitude of the joint translation is used. If all the above tests fail, 1 is returned. ''' scale = 0 children = listRelatives( item, type='transform' ) if children: scales = [] bb = rigUtils.getTranslationExtents( children ) XYZ = bb[3]-bb[0], bb[4]-bb[1], bb[5]-bb[2] scale = max( XYZ ) if not scale: if objExists( '%s.radius' % item ): scale = getAttr( '%s.radius' % item ) if not scale: pos = Vector( getAttr( '%s.t' % item )[0] ) scale = pos.get_magnitude() return scale or 1 def getNodeParent( obj ): parent = listRelatives( obj, p=True, pa=True ) if parent is None: return None return parent[ 0 ] def iterParents( obj, until=None ): parent = getNodeParent( obj ) while parent is not None: yield parent if until is not None: if parent == until: return parent = getNodeParent( parent ) def sortByHierarchy( objs ): sortedObjs = [] for o in objs: pCount = len( list( iterParents( o ) ) ) sortedObjs.append( (pCount, o) ) sortedObjs.sort() return [ o[ 1 ] for o in sortedObjs ] def getAlignSkipState( item ): attrPath = '%s._skeletonPartSkipAlign' % item if not objExists( attrPath ): return False return getAttr( attrPath ) def setAlignSkipState( item, state ): ''' will flag a joint as user aligned - which means it will get skipped by the alignment functions ''' attrPath = '%s._skeletonPartSkipAlign' % item if state: if not objExists( attrPath ): addAttr( item, ln='_skeletonPartSkipAlign', at='bool' ) setAttr( attrPath, True ) else: deleteAttr( attrPath ) def d_restoreLocksAndNames(f): ''' this decorator is for the alignment functions - it basically takes care of ensuring the children are unparented before alignment happens, re-parented after the fact, channel unlocking and re-locking, freezing transforms etc... NOTE: this function gets called a lot. basically this decorator wraps all alignment functions, and generally each joint in the skeleton has at least one alignment function run on it. Beware! ''' def newF( item, *args, **kwargs ): if getAlignSkipState( item ): return attrs = 't', 'r', 'ra' #unparent and children in place, and store the original name, and lock #states of attributes - we need to unlock attributes as this item will #most likely change its orientation children = castToMObjects( listRelatives( item, typ='transform', pa=True ) or [] ) #cast to mobjects as re-parenting can change and thus invalidate node name strings... childrenPreStates = {} for child in [ item ] + children: lockStates = [] for a in attrs: for c in CHANNELS: attrPath = '%s.%s%s' % (child, a, c) lockStates.append( (attrPath, getAttr( attrPath, lock=True )) ) try: setAttr( attrPath, lock=False ) except: pass originalChildName = str( child ) if not cmpNodes( child, item ): child = cmd.parent( child, world=True )[0] childrenPreStates[ child ] = originalChildName, lockStates #make sure the rotation axis attribute is zeroed out - NOTE: we need to do this after children have been un-parented otherwise it could affect their positions for c in CHANNELS: setAttr( '%s.ra%s' % (item, c), 0 ) f( item, children=children, *args, **kwargs ) makeIdentity( item, a=True, r=True ) #now re-parent children for child, (originalName, lockStates) in childrenPreStates.iteritems(): if child != item: child = cmd.parent( child, item )[0] child = rename( child, originalName.split( '|' )[-1] ) for attrPath, lockState in lockStates: try: setAttr( attrPath, lock=lockState ) except: pass newF.__name__ = f.__name__ newF.__doc__ = f.__doc__ return newF @d_restoreLocksAndNames def autoAlignItem( item, invertAimAndUp=False, upVector=BONE_ROTATE_VECTOR, worldUpVector=MAYA_SIDE, worldUpObject='', upType='vector', children=None, debug=False ): ''' for cases where there is no strong preference about how the item is aligned, this function will determine the best course of action ''' numChildren = len( children ) #if there is more than one child, see if there is only one JOINT child... childJoints = ls( children, type='joint' ) if len( childJoints ) == 1: children = childJoints #if there is only one child, aim the x-axis at said child, and aim the z-axis toward scene-up ### WARNING :: STILL NEED TO DEAL WITH CASE WHERE JOINT IS CLOSE TO AIMING AT SCENE UP invertMult = -1 if invertAimAndUp else 1 if len( children ) == 1: kw = { 'aimVector': BONE_AIM_VECTOR * invertMult, 'upVector': upVector * invertMult, 'worldUpVector': worldUpVector, 'worldUpType': upType } if worldUpObject: kw[ 'worldUpObject' ] = worldUpObject c = aimConstraint( children[ 0 ], item, **kw ) if not debug: delete( c ) else: for a in [ 'jo', 'r' ]: for c in CHANNELS: attrPath = '%s.%s%s' % (item, a, c) if not getAttr( attrPath, settable=True ): continue setAttr( attrPath, 0 ) @d_restoreLocksAndNames def alignAimAtItem( item, aimAtItem, invertAimAndUp=False, upVector=BONE_ROTATE_VECTOR, worldUpVector=MAYA_SIDE, worldUpObject='', upType='vector', children=None, debug=False ): ''' aims the item at a specific transform in the scene. the aim axis is always BONE_AIM_VECTOR, but the up axis can be set to whatever is required ''' invertMult = -1 if invertAimAndUp else 1 kw = { 'aimVector': BONE_AIM_VECTOR * invertMult, 'upVector': upVector * invertMult, 'worldUpVector': worldUpVector, 'worldUpType': upType } if worldUpObject: kw[ 'worldUpObject' ] = worldUpObject c = aimConstraint( aimAtItem, item, **kw ) if debug: raise Exception if not debug: delete( c ) @d_restoreLocksAndNames def alignItemToWorld( item, children=None, skipX=False, skipY=False, skipZ=False ): ''' aligns the item to world space axes, optionally skipping individual axes ''' rotate( -90, -90, 0, item, a=True, ws=True ) if skipX: rotate( 0, 0, 0, item, a=True, os=True, rotateX=True ) if skipY: rotate( 0, 0, 0, item, a=True, os=True, rotateY=True ) if skipZ: rotate( 0, 0, 0, item, a=True, os=True, rotateZ=True ) @d_restoreLocksAndNames def alignItemToLocal( item, children=None, skipX=False, skipY=False, skipZ=False ): ''' aligns the item to local space axes, optionally skipping individual axes ''' for skip, axis in zip( (skipX, skipY, skipZ), CHANNELS ): if skipX: setAttr( '%s.r%s' % (item, axis), 0 ) setAttr( '%s.jo%s' % (item, axis), 0 ) @d_restoreLocksAndNames def alignPreserve( item, children=None ): pass def getCharacterMeshes(): ''' returns all "character meshes" found in the scene. These are basically defined as meshes that aren't parented to a joint - where joints are ''' meshes = ls( type='mesh', r=True ) meshes = set( listRelatives( meshes, p=True, pa=True ) ) #removes duplicates... characterMeshes = set() for mesh in meshes: isUnderJoint = False for parent in iterParents( mesh ): if nodeType( parent ) == 'joint': isUnderJoint = True break if not isUnderJoint: characterMeshes.add( mesh ) return list( characterMeshes ) class SkeletonError(Exception): pass class NotFinalizedError(SkeletonError): pass class SceneNotSavedError(SkeletonError): pass def getSkeletonSet(): ''' returns the "master" set used for storing skeleton parts in the scene - this isn't actually used for anything but organizational purposes - ie the skeleton part sets are members of _this_ set, but at no point does the existence or non-existence of this make any functional difference ''' existing = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == TOOL_NAME ] if existing: return existing[ 0 ] else: skeletonParts = createNode( 'objectSet', n='skeletonParts' ) sets( skeletonParts, e=True, text=TOOL_NAME ) return skeletonParts def createSkeletonPartContainer( name ): ''' ''' theSet = sets( em=True, n=name, text='skeletonPrimitive' ) sets( theSet, e=True, add=getSkeletonSet() ) return theSet def isSkeletonPartContainer( node ): ''' tests whether the given node is a skeleton part container or not ''' if objectType( node, isType='objectSet' ): return sets( node, q=True, text=True ) == 'skeletonPrimitive' return False def getSkeletonPartContainers(): ''' returns a list of all skeleton part containers in the scene ''' return [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == 'skeletonPrimitive' ] def buildSkeletonPartContainer( typeClass, kwDict, items ): ''' builds a container for the given skeleton part items, and tags it with the various attributes needed to track the state for a skeleton part. ''' #if typeClass is an instance, then set its container attribute, otherwise instantiate an instance and return it if isinstance( typeClass, SkeletonPart ): theInstance = typeClass typeClass = type( typeClass ) #build the container, and add the special attribute to it to if 'idx' in kwDict: idx = kwDict[ 'idx' ] else: kwDict[ 'idx' ] = idx = typeClass.GetUniqueIdx() theContainer = createSkeletonPartContainer( 'a%sPart_%s' % (typeClass.__name__, idx) ) addAttr( theContainer, ln='_skeletonPrimitive', attributeType='compound', numberOfChildren=7 ) addAttr( theContainer, ln='typeName', dt='string', parent='_skeletonPrimitive' ) addAttr( theContainer, ln='version', at='long', parent='_skeletonPrimitive' ) addAttr( theContainer, ln='script', dt='string', parent='_skeletonPrimitive' ) addAttr( theContainer, ln='buildKwargs', dt='string', parent='_skeletonPrimitive' ) #stores the kwarg dict used to build this part addAttr( theContainer, ln='rigKwargs', dt='string', parent='_skeletonPrimitive' ) #stores the kwarg dict to pass to the rig method addAttr( theContainer, ln='items', multi=True, indexMatters=False, attributeType='message', parent='_skeletonPrimitive' ) addAttr( theContainer, ln='placers', multi=True, indexMatters=False, attributeType='message', parent='_skeletonPrimitive' ) #now set the attribute values... setAttr( '%s._skeletonPrimitive.typeName' % theContainer, typeClass.__name__, type='string' ) setAttr( '%s._skeletonPrimitive.version' % theContainer, typeClass.__version__ ) setAttr( '%s._skeletonPrimitive.script' % theContainer, inspect.getfile( typeClass ), type='string' ) setAttr( '%s._skeletonPrimitive.buildKwargs' % theContainer, str( kwDict ), type='string' ) #now add all the items items = map( str, items ) for item in set( items ): if nodeType( item ) == 'joint': sets( item, e=True, add=theContainer ) #if the node is a rig part container add it to this container otherwise skip it elif objectType( item, isAType='objectSet' ): if isSkeletonPartContainer( item ): sets( item, e=True, add=theContainer ) #and now hook up all the controls for idx, item in enumerate( items ): if item is None: continue connectAttr( '%s.message' % item, '%s._skeletonPrimitive.items[%d]' % (theContainer, idx), f=True ) return theContainer def d_disconnectJointsFromSkinning( f ): ''' Will unhook all skinning before performing the decorated method - and re-hooks it up after the fact. Basically decorating anything with this function will allow you do perform operations that would otherwise cause maya to complain about skin clusters being attached ''' def new( *a, **kw ): #for all skin clusters iterate through all their joints and detach them #so we can freeze transforms - make sure to store initial state so we can #restore connections afterward skinClustersConnections = [] skinClusters = ls( typ='skinCluster' ) or [] for c in skinClusters: cons = listConnections( c, destination=False, plugs=True, connections=True ) if cons is None: print 'WARNING - no connections found on the skinCluster %s' % c continue conIter = iter( cons ) for tgtConnection in conIter: srcConnection = conIter.next() #cons is a list of what should be tuples, but maya just returns a flat list - basically every first item is the destination plug, and every second is the source plug #if the connection is originating from a joint delete the connection - otherwise leave it alone - we only want to disconnect joints from the skin cluster node = srcConnection.split( '.' )[0] if nodeType( node ) == 'joint': disconnectAttr( srcConnection, tgtConnection ) skinClustersConnections.append( (srcConnection, tgtConnection) ) try: f( *a, **kw ) #ALWAYS restore connections... finally: #re-connect all joints to skinClusters, and reset them for srcConnection, tgtConnection in skinClustersConnections: connectAttr( srcConnection, tgtConnection, f=True ) if skinClustersConnections: for skinCluster in skinClusters: resetSkinCluster( skinCluster ) new.__name__ = f.__name__ new.__doc__ = f.__doc__ return new def d_disableDrivingRelationships( f ): ''' tries to unhook all driver/driven relationships first, and re-hook them up afterwards NOTE: needs to wrap a SkeletonPart method ''' def new( self, *a, **kw ): #store any driving or driven part, so when we're done we can restore the relationships driver = self.getDriver() drivenParts = self.getDriven() #break driving relationships self.breakDriver() for part in drivenParts: part.breakDriver() try: f( self, *a, **kw ) #restore driver/driven relationships... finally: #restore any up/downstream relationships if any... if driver: driver.driveOtherPart( self ) for part in drivenParts: try: self.driveOtherPart( part ) except AssertionError: continue #the parts may have changed size since the initial connection, so if they differ in size just ignore the assertion... new.__name__ = f.__name__ new.__doc__ = f.__doc__ return new def d_performInSkeletonPartScene( f ): def new( self, *a, **kw ): assert isinstance( self, SkeletonPart ) #if the part isn't referenced - nothing to do! execute the function as usual if not self.isReferenced(): return f( self, *a, **kw ) partContainerFilepath = filesystem.Path( referenceQuery( self.getContainer(), filename=True ) ) curScene = filesystem.Path( file( q=True, sn=True ) ) if not curScene.exists(): raise TypeError( "This scene isn't saved! Please save this scene somewhere before executing the decorated method!" ) initialContainer = ReferencedNode( self.getContainer() ) self.setContainer( initialContainer.getUnreferencedNode() ) if not curScene.getWritable(): curScene.edit() file( save=True, f=True ) file( partContainerFilepath, open=True, f=True ) try: return f( self, *a, **kw ) finally: self.setContainer( initialContainer.getNode() ) if not partContainerFilepath.getWritable(): partContainerFilepath.edit() file( save=True, f=True ) file( curScene, open=True, f=True ) new.__name__ = f.__name__ new.__doc__ = f.__doc__ return new class SkeletonPart(typeFactories.trackableClassFactory()): __version__ = 0 #parity is "sided-ness" of the part. Ie if the part can exist on the left OR right side of the skeleton, the part has parity. the spine #is an example of a part that has no parity, as is the head HAS_PARITY = True PART_SCALE = TYPICAL_HEIGHT AUTO_NAME = True AVAILABLE_IN_UI = True #determines whether this part should appear in the UI or not... #some variables generally used by the auto volume creation methods AUTO_VOLUME_SIDES = 8 #number of cylinder sides #this list should be overridden for sub classes require named end placers such as feet PLACER_NAMES = [] RigTypes = () def __new__( cls, partContainer ): if cls is SkeletonPart: clsName = getAttr( '%s._skeletonPrimitive.typeName' % partContainer ) cls = cls.GetNamedSubclass( clsName ) if cls is None: raise TypeError( "Cannot determine the part class for the given part container!" ) return object.__new__( cls, partContainer ) def __init__( self, partContainer ): if partContainer is not None: assert isSkeletonPartContainer( partContainer ), "Must pass a valid skeleton part container! (received %s - a %s)" % (partContainer, nodeType( partContainer )) self._container = partContainer self._items = None def __unicode__( self ): return u"%s( %r )" % (self.__class__.__name__, self._container) __str__ = __unicode__ def __repr__( self ): return repr( unicode( self ) ) def __hash__( self ): return hash( self._container ) def __eq__( self, other ): return self._container == other.getContainer() def __neq__( self, other ): return not self == other def __getitem__( self, idx ): return self.getItems().__getitem__( idx ) def __getattr__( self, attr ): if attr in self.__dict__: return self.__dict__[ attr ] if attr not in self.PLACER_NAMES: raise AttributeError( "No such attribute %s" % attr ) idx = list( self.PLACER_NAMES ).index( attr ) cons = listConnections( '%s._skeletonPrimitive.placers[%d]' % (self.base, n), d=False ) if cons: return cons[ 0 ] return None def __len__( self ): return len( self.getItems() ) def __iter__( self ): return iter( self.getItems() ) def getContainer( self ): return self._container def setContainer( self, container ): self._container = container self._items = None def getItems( self ): if self._items is not None: return self._items[:] self._items = items = [] idxs = getAttr( '%s._skeletonPrimitive.items' % self._container, multiIndices=True ) or [] for idx in idxs: cons = listConnections( '%s._skeletonPrimitive.items[%d]' % (self._container, idx), d=False ) if cons: assert len( cons ) == 1, "More than one joint was found!!!" items.append( cons[ 0 ] ) #items = castToMObjects( items ) return items[:] #return a copy... items = property( getItems ) @property def version( self ): try: return getAttr( '%s._skeletonPrimitive.version' % self._container ) except: return None def isDisabled( self ): ''' returns whether the part has been disabled for rigging or not ''' rigKwargs = self.getRigKwargs() return 'disable' in rigKwargs def getPlacers( self ): placerAttrpath = '%s._skeletonPrimitive.placers' % self._container if not objExists( placerAttrpath ): return [] placers = [] placerIdxs = getAttr( placerAttrpath, multiIndices=True ) if placerIdxs: for idx in placerIdxs: cons = listConnections( '%s[%d]' % (placerAttrpath, idx), d=False ) if cons: placers.append( cons[ 0 ] ) return placers def verifyPart( self ): ''' this is merely a "hook" that can be used to fix anything up should the way skeleton parts are defined change ''' #make sure all items have the appropriate attributes on them baseItem = self[ 0 ] for n, item in enumerate( self ): delete( '%s.inverseScale' % item, icn=True ) #remove the inverse scale relationship... setAttr( '%s.segmentScaleCompensate' % item, False ) if not objExists( '%s._skeletonPartName' % item ): addAttr( item, ln='_skeletonPartName', dt='string' ) if not objExists( '%s._skeletonPartArgs' % item ): addAttr( item, ln='_skeletonPartArgs', dt='string' ) if n: if not isConnected( '%s._skeletonPartName' % baseItem, '%s._skeletonPartName' % item ): connectAttr( '%s._skeletonPartName' % baseItem, '%s._skeletonPartName' % item, f=True ) if not isConnected( '%s._skeletonPartArgs' % baseItem, '%s._skeletonPartArgs' % item ): connectAttr( '%s._skeletonPartArgs' % baseItem, '%s._skeletonPartArgs' % item, f=True ) def convert( self, buildKwargs ): ''' called when joints built outside of skeleton builder are converted to a skeleton builder part ''' if not buildKwargs: for argName, value in self.GetDefaultBuildKwargList(): buildKwargs[ argName ] = value if 'idx' not in buildKwargs: idx = self.GetUniqueIdx() buildKwargs[ 'idx' ] = idx if 'parent' in buildKwargs: buildKwargs.pop( 'parent' ) self.setBuildKwargs( buildKwargs ) #lock scale attrState( self.items, ['s'], lock=True, keyable=False, show=True ) #lock rotate axis attrState( self.items, ['rotateAxis'], lock=True, keyable=False, show=False ) #build placers... self.buildPlacers() def hasParity( self ): return self.HAS_PARITY def isReferenced( self ): return referenceQuery( self._container, inr=True ) @classmethod def ParityMultiplier( cls, idx ): return Parity( idx ).asMultiplier() @classmethod def GetPartName( cls ): ''' can be used to get a "nice" name for the part class ''' return camelCaseToNice( cls.__name__ ) def getIdx( self ): ''' returns the index of the part - all parts have a unique index associated with them ''' return self.getBuildKwargs()[ 'idx' ] def getBuildScale( self ): return self.getBuildKwargs().get( 'partScale', self.PART_SCALE ) def getParity( self ): return Parity( self.getIdx() ) def getParityColour( self ): parity = self.getParity() if parity == Parity.LEFT: return Colour( 'green' ) if parity == Parity.RIGHT: return Colour( 'red' ) if parity == Parity.NONE: return Colour( 'darkblue' ) return Colour( 'black' ) getParityColor = getParityColour def getParityMultiplier( self ): return self.getParity().asMultiplier() def getOppositePart( self ): ''' Finds the opposite part - if any - in the scene to this part. If no opposite part is found None is returned. The opposite part is defined as the part that has opposite parity - the part with the closest index is returned if there are multiple parts with opposite parity in the scene. If this part has no parity None is returned. ''' #is this a parity part? if not then there is no such thing as an opposite part... if not self.hasParity(): return None #get some data about this part thisIdx = self.getIdx() thisParity = self.getParity() #is this a left or right parity part? isLeft = thisIdx == Parity.LEFT possibleMatches = [] for part in self.IterAllParts( True ): parity = part.getParity() if parity.isOpposite( thisParity ): idx = part.getIdx() #if "self" is a left part then its exact opposite will be self.getIdx() + 1, otherwise if "self" is a right #sided part then its exact opposite will be self.getIdx() - 1. So figure out the "index delta" and use it #as a sort metric to find the most appropriate match for the cases where there are multiple, non-ideal matches idxDelta = 0 if isLeft: idxDelta = idx - thisIdx else: idxDelta = thisIdx - idx if idxDelta == 1: return part possibleMatches.append( (idxDelta, part) ) possibleMatches.sort() if possibleMatches: return possibleMatches[0][1] return None @property def base( self ): return self[ 0 ] @property def bases( self ): ''' returns all the bases for this part - bases are joints with parents who don't belong to this part ''' allItems = set( self ) bases = [] for item in self: itemParent = getNodeParent( item ) if itemParent not in allItems: bases.append( item ) return bases @property def end( self ): return self[ -1 ] @property def ends( self ): ''' returns all the ends for the part - ends are joints that either have no children, or have children that don't belong to this part ''' allItems = set( self ) ends = [] for item in self: itemChildren = listRelatives( item, pa=True ) #so if the item has children, see if any of them are in allItems - if not, its an end if itemChildren: childrenInAllItems = allItems.intersection( set( itemChildren ) ) if not childrenInAllItems: ends.append( item ) #if it has no children, its an end else: ends.append( item ) return ends @property def chains( self ): ''' returns a list of hierarchy "chains" in the current part - parts that have more than one base are comprised of "chains": ie hierarchies that don't have a parent as a member of this part For a hand part for example, this method will return a list of finger hierarchies NOTE: the chains are ordered hierarchically ''' bases = set( self.bases ) chains = [] for end in self.ends: currentChain = [ end ] p = getNodeParent( end ) while p: currentChain.append( p ) if p in bases: break p = getNodeParent( p ) currentChain.reverse() chains.append( currentChain ) return chains @property def endPlacer( self ): try: return self.getPlacers()[ 0 ] except IndexError: return None @classmethod def GetIdxStr( cls, idx ): ''' returns an "index string". For parts with parity this index string increments with pairs (ie a left and a right) while non-parity parts always increment ''' #/2 because parts are created in pairs so arm 2 and 3 are prefixed with "Arm1", and the first arm is simply "Arm" if cls.HAS_PARITY: return str( idx / 2 ) if idx > 1 else '' return str( idx ) if idx else '' def getBuildKwargs( self ): ''' returns the kwarg dict that was used to create this particular part ''' buildFunc = self.GetBuildFunction() #get the default build kwargs for the part argNames, vArgs, vKwargs, defaults = inspect.getargspec( buildFunc ) if defaults is None: defaults = [] argNames = argNames[ 1: ] #strip the first arg - which is the class arg (usually cls) kw = {} for argName, default in zip( argNames, defaults ): kw[ argName ] = default #now update the default kwargs with the actual kwargs argStr = getAttr( '%s._skeletonPrimitive.buildKwargs' % self._container ) kw.update( eval( argStr ) ) return kw def setBuildKwargs( self, kwargs ): ''' returns the kwarg dict that was used to create this particular part ''' setAttr( '%s._skeletonPrimitive.buildKwargs' % self._container, str( kwargs ), type='string' ) def getRigKwargs( self ): ''' returns the kwarg dict that should be used to create the rig for this part ''' try: argStr = getAttr( '%s._skeletonPrimitive.rigKwargs' % self._container ) except: return {} if argStr is None: return {} kw = eval( argStr ) return kw def setRigKwargs( self, kwargs ): setAttr( '%s._skeletonPrimitive.rigKwargs' % self._container, str( kwargs ), type='string' ) def updateRigKwargs( self, **kw ): currentKwargs = self.getRigKwargs() currentKwargs.update( kw ) self.setRigKwargs( currentKwargs ) def getPartName( self ): idx = self.getIdx() if self.hasParity(): parityStr = 'Left ' if self.getParity() == Parity.LEFT else 'Right ' idxStr = '' if idx < 2 else ' %d' % idx else: parityStr = '' idxStr = ' %d' % idx if idx else '' name = camelCaseToNice( self.getBuildKwargs().get( 'partName', '' ) ) clsName = camelCaseToNice( type( self ).__name__ ) return '%s%s %s%s' % (parityStr, name, clsName, idxStr) def getActualScale( self ): return rigUtils.getObjsScale( self ) def getParent( self ): ''' returns the parent of the part - the actual node name. use getParentPart to query the part this part is parented to (if any) ''' return getNodeParent( self.base ) def setParent( self, parent ): ''' parents the part to a new object in the scene - if parent is None, the part is parented to the world ''' if parent is None: cmd.parent( self.base, w=True ) else: cmd.parent( self.base, parent ) def getParentPart( self ): ''' returns the part this part is parented to - if any. if this part isn't parented to a part, None is returned. NOTE: this part may be parented to something that isn't a member of a part, so a result of None from this query doesn't mean the part has no parent, just that its parent isn't a member of a part ''' parent = self.getParent() if parent is None: return None return self.InitFromItem( parent ) @classmethod def GetBuildFunction( cls ): ''' returns the build function for the part ''' buildFunc = getattr( cls, '_build', None ) if buildFunc is None: raise SkeletonError( 'no such part type' ) return buildFunc @classmethod def GetDefaultBuildKwargList( cls ): ''' returns a list of 2 tuples: argName, defaultValue ''' buildFunc = cls.GetBuildFunction() spec = inspect.getargspec( buildFunc ) argNames = spec[ 0 ][ 1: ] #strip the first item because the _build method is a bound method - so the first item is always the class arg (usually called cls) defaults = spec[ 3 ] if defaults is None: defaults = [] assert len( argNames ) == len( defaults ), "%s has no default value set for one of its args - this is not allowed" % cls kwargList = [] for argName, default in zip( argNames, defaults ): kwargList.append( (argName, default) ) return kwargList @classmethod def InitFromItem( cls, item ): ''' will instantiate a SkeletonPart from an item of a previously built part. if an item is given that isn't involved in a part None is returned ''' if isSkeletonPartContainer( item ): typeClassStr = getAttr( '%s._skeletonPrimitive.typeName' % item ) typeClass = SkeletonPart.GetNamedSubclass( typeClassStr ) return typeClass( item ) cons = listConnections( '%s.message' % item, s=False, type='objectSet' ) if not cons: raise SkeletonError( "Cannot find a skeleton part container for %s" % item ) for con in cons: if isSkeletonPartContainer( con ): typeClassStr = getAttr( '%s._skeletonPrimitive.typeName' % con ) typeClass = SkeletonPart.GetNamedSubclass( typeClassStr ) return typeClass( con ) raise SkeletonError( "Cannot find a skeleton container for %s" % item ) ### CREATION ### def buildPlacers( self ): ''' Don't override this method - instead override the _buildPlacers method. This method handles connecting the placers to the part appropriately ''' try: buildPlacers = self._buildPlacers except AttributeError: return [] placers = buildPlacers() if not placers: return container = self._container idx = self.getIdx() idxStr = self.GetIdxStr( idx ) parityStr = Parity( idx % 2 ).asName() if self.hasParity() else '' for n, placer in enumerate( placers ): connectAttr( '%s.message' % placer, '%s._skeletonPrimitive.placers[%d]' % (container, n), f=True ) #name the placer appropriately try: placerName = self.PLACER_NAMES[ n ] except IndexError: proposedName = '%s%s_plc%d%s' % (type( self ).__name__, idxStr, idx, parityStr) else: proposedName = '%s%s_plc%d%s' % (placerName, idxStr, idx, parityStr) if objExists( proposedName ): proposedName = proposedName +'#' placer = rename( placer, proposedName ) return placers def _buildPlacers( self ): ''' the default placer building method just creates a placer at teh end of every joint chain in the part ''' placers = [] for end in self.ends: placer = buildEndPlacer() setAttr( '%s.t' % placer, *getAttr( '%s.t' % end )[0] ) placer = parent( placer, end, r=True )[ 0 ] placers.append( placer ) return placers #NOTE!!! this method gets decorated below !!! def Create( cls, *a, **kw ): ''' this is the primary way to create a skeleton part. build functions are defined outside the class and looked up by name. this method ensures that all build methods (a build method is only required to return the list of nodes that define it) register nodes properly, and encode data about how the part was built into the part so that the part can be re-instantiated at a later date ''' partScale = kw.setdefault( 'partScale', cls.PART_SCALE ) #grab any kwargs out of the dict that shouldn't be there visualize = kw.pop( 'visualize', True ) autoMirror = kw.pop( 'autoMirror', True ) #now turn the args passed in are a single kwargs dict buildFunc = cls.GetBuildFunction() argNames, vArgs, vKwargs, defaults = inspect.getargspec( buildFunc ) if defaults is None: defaults = [] argNames = argNames[ 1: ] #strip the first arg - which is the class arg (usually cls) if vArgs is not None: raise SkeletonError( 'cannot have *a in skeleton build functions' ) for argName, value in zip( argNames, a ): kw[ argName ] = value #now explicitly add the defaults for argName, default in zip( argNames, defaults ): kw.setdefault( argName, default ) #generate an index for the part - each part must have a unique index idx = cls.GetUniqueIdx() kw[ 'idx' ] = idx #run the build function and remove the parent from the kw dict - we don't need to serialize this... items = buildFunc( **kw ) kw.pop( 'parent', None ) partContainer = buildSkeletonPartContainer( cls, kw, items ) #now rename all the joints appropriately if we're supposed to... if cls.AUTO_NAME: partName = kw.get( 'partName', cls.__name__ ) if not partName: partName = cls.__name__ partName = partName[0].upper() + partName[ 1: ] #capitalize the first letter always... kw[ 'partName' ] = partName renamedItems = [] idxStr = cls.GetIdxStr( idx ) parityStr = Parity( idx % 2 ).asName() if cls.HAS_PARITY else '' for n, item in enumerate( items ): renamedItems.append( rename( item, '%s%s_%s%s' % (partName, idxStr, n, parityStr) ) ) items = renamedItems #instantiate the part and align newPart = cls( partContainer ) newPart.convert( kw ) newPart._align( _initialAlign=True ) #are we doing visualizations? if visualize: newPart.visualize() return newPart #in 2009 wrapping the Create with d_unifyUndo will crash maya... :( if mayaVar >= 2011: Create = classmethod( d_unifyUndo( Create ) ) else: Create = classmethod( d_unifyUndo( Create ) ) def rebuild( self, **newBuildKwargs ): ''' rebuilds the part by storing all the positions of the existing members, re-creating the part with optionally changed build args, positioning re-created joints as best as possible, and re-parenting child parts ''' #grab the build kwargs used to create this part, and update it with the new kwargs passed in buildKwargs = self.getBuildKwargs() buildKwargs.update( newBuildKwargs ) buildKwargs[ 'parent' ] = getNodeParent( self ) self.unvisualize() posRots = [] attrs = 't', 'r' for item in self: pos = xform( item, q=True, ws=True, rp=True ) rot = xform( item, q=True, ws=True, ro=True ) posRots.append( (item, pos, rot) ) childParts = self.getChildParts() childParents = [] childPartDrivers = [] for part in childParts: childParents.append( part.getParent() ) childPartDrivers.append( part.getDriver() ) part.breakDriver() part.setParent( None ) orphans = self.getOrphanJoints() orphanParents = [] for orphan in orphans: orphanParents.append( getNodeParent( orphan ) ) cmd.parent( orphan, w=True ) delete( self.items ) newPart = self.Create( **buildKwargs ) oldToNewNameMapping = {} for (oldItemName, pos, rot), item in zip( posRots, newPart.items ): move( pos[ 0 ], pos[ 1 ], pos[ 2 ], item, ws=True, a=True, rpr=True ) rotate( rot[ 0 ], rot[ 1 ], rot[ 2 ], item, ws=True, a=True ) oldToNewNameMapping[ oldItemName ] = item #reparent child parts for childPart, childParent in zip( childParts, childParents ): childParent = oldToNewNameMapping.get( childParent, childParent ) childPart.setParent( childParent ) #re-setup driver/driven relationships (should be done after re-parenting is done) for childPart, childDriver in zip( childParts, childPartDrivers ): if childDriver is not None: childDriver.driveOtherPart( childPart ) #reparent orphans for orphan, orphanParent in zip( orphans, orphanParents ): orphanParent = oldToNewNameMapping.get( orphanParent, orphanParent ) cmd.parent( orphan, orphanParent ) newPart.visualize() return newPart ### REDISCOVERY ### @classmethod def IterAllParts( cls, exactType=False ): ''' iterates over all SkeletonParts in the current scene ''' for partContainer in getSkeletonPartContainers(): thisPartCls = SkeletonPart.GetNamedSubclass( getAttr( '%s._skeletonPrimitive.typeName' % partContainer ) ) #if the user only wants the exact type then compare the classes - if they're not the same keep loopin if exactType: if cls is not thisPartCls: continue #otherwise test to see if this part's class is a subclass of else: if not issubclass( thisPartCls, cls ): continue yield thisPartCls( partContainer ) @classmethod def IterAllPartsInOrder( cls ): allParts = [ part for part in cls.IterAllParts() ] allParts = sortPartsByHierarchy( allParts ) return iter( allParts ) @classmethod def FindParts( cls, partClass, withKwargs=None ): ''' given a part name and a kwargs dict (may be a partial dict) this method will return all matching parts in the current scene. so if you wanted to get a list of all the finger parts with 3 joints you would do: SkeletonPart.FindParts( finger, { 'fingerJointCount': 3 } ) ''' withKwargs = withKwargs or {} matches = [] for part in cls.IterAllParts( partClass ): partKwargs = part.getBuildKwargs() match = True for argName, argValue in withKwargs.iteritems(): try: if partKwargs[ argName ] != argValue: match = False break except KeyError: continue if match: matches.append( part ) return matches @classmethod def GetUniqueIdx( cls ): ''' returns a unique index (unique against the universe of existing indices in the scene) for the current part class ''' allPartContainers = getSkeletonPartContainers() thisTypeName = cls.__name__ existingIdxs = set() for container in allPartContainers: typeStr = getAttr( '%s._skeletonPrimitive.typeName' % container ) typeCls = SkeletonPart.GetNamedSubclass( typeStr ) if typeCls is cls: attrPath = '%s._skeletonPrimitive.buildKwargs' % container attrStr = getAttr( attrPath ) if attrStr: buildArgs = eval( getAttr( attrPath ) ) existingIdxs.add( buildArgs[ 'idx' ] ) existingIdxs = list( sorted( existingIdxs ) ) #return the first, lowest, available index for orderedIdx, existingIdx in enumerate( existingIdxs ): if existingIdx != orderedIdx: return orderedIdx if existingIdxs: return existingIdxs[ -1 ] + 1 return 0 @classmethod def GetRigMethod( cls, methodName ): for method in cls.RigTypes: if method.__name__ == methodName: return method return None def getChildParts( self ): ''' returns a list of all the parts parented directly to a member of this part ''' #first get a list of all the joints directly parented to a memeber of this part selfItems = self.getItems() + self.getPlacers() allChildren = listRelatives( selfItems, typ='transform', pa=True ) if not allChildren: return #subtract all the items of this part from the children - to give us all the children of this part that don't belong to this part allChildren = set( allChildren ).difference( set( selfItems ) ) return getPartsFromObjects( allChildren ) def getOrphanJoints( self ): ''' orphan joints are joints parented to a member of this part, but don't belong to a part. orphan joints get aligned using the same alignment method used by their parent part ''' #first get a list of all the joints directly parented to a memeber of this part allChildren = listRelatives( self, typ='joint', pa=True ) if not allChildren: return [] childPartItems = [] for part in self.getChildParts(): childPartItems += list( part ) jointsInSomePart = set( childPartItems + self.items ) orphanChildren = set( allChildren ).difference( jointsInSomePart ) orphanChildren = list( orphanChildren ) childrenOfChildren = [] for i in orphanChildren: iChildren = listRelatives( i, typ='joint', pa=True ) if not iChildren: continue for c in iChildren: if objExists( '%s._skeletonPartName' % c ): continue childrenOfChildren.append( c ) return orphanChildren + childrenOfChildren def selfAndOrphans( self ): return list( self ) + self.getOrphanJoints() @d_unifyUndo def delete( self ): if self.isRigged(): self.deleteRig() for node in self.items: rigUtils.cleanDelete( node ) if objExists( self._container ): delete( self._container ) ### ALIGNMENT ### @d_unifyUndo @d_disableDrivingRelationships @d_disconnectJointsFromSkinning def align( self, _initialAlign=False ): self._align( _initialAlign ) def _align( self, _initialAlign=False ): for item in self.selfAndOrphans(): autoAlignItem( item ) @d_unifyUndo @d_disableDrivingRelationships @d_disconnectJointsFromSkinning def freeze( self ): ''' freezes the transforms for all joints in this part ''' makeIdentity( self.items, a=True, t=True, r=True ) ### VISUALIZATION ### @d_unifyUndo def visualize( self ): ''' can be used to create visualization for item orientation or whatever else. NOTE: visualizations should never add joints, but can use any other node machinery available. ''' pass @d_unifyUndo def unvisualize( self ): ''' removes any visualization on the part ''' for i in self.selfAndOrphans(): children = listRelatives( i, shapes=True, pa=True ) or [] for c in children: try: if nodeType( c ) == 'joint': continue delete( c ) #this can happen if the deletion of a previous child causes some other child to also be deleted - its a fringe case but possible (i think) except TypeError: continue ### SYMMETRICAL SKELETON BUILDING ### def driveOtherPart( self, otherPart ): ''' drives the specified part with this part - meaning that all translations and rotations of items in this part will drive the corresponding items in the other part. attributes are hooked up for the most part using direct connections, but some attributes are driven via an expression ''' assert isinstance( otherPart, SkeletonPart ) #this is just for WING... if type( self ) is not type( otherPart ): raise SkeletonError( "Sorry, you cannot connect different types together" ) if len( self ) != len( otherPart ): raise SkeletonError( "Sorry, seems the two parts are different sizes (%d, %d) - not sure what to do" % (len( self ), len( otherPart )) ) attrs = 't', 'r' #first unlock trans and rot channels attrState( otherPart.items, attrs, False ) #if the parts have parity AND differing parities, we may have to deal with mirroring differently if self.hasParity() and self.getParity() != otherPart.getParity(): selfItems = self.items + self.getPlacers() otherItems = otherPart.items + otherPart.getPlacers() for thisItem, otherItem in zip( selfItems, otherItems ): rotNode = cmd.rotationMirror( thisItem, otherItem, ax=BONE_AIM_AXIS.asName() ) #access via cmd namespace as the plugin may or may not have been loaded when all was imported from maya.cmds #if the joints have the same parent, reverse position if getNodeParent( thisItem ) == getNodeParent( otherItem ): setAttr( '%s.mirrorTranslation' % rotNode, 2 ) else: setAttr( '%s.mirrorTranslation' % rotNode, 1 ) #otherwise setting up the driven relationship is straight up attribute connections... else: for thisItem, otherItem in zip( self.items, otherPart.items ): for attr in attrs: for c in CHANNELS: connectAttr( '%s.%s%s' % (thisItem, attr, c), '%s.%s%s' % (otherItem, attr, c), f=True ) def breakDriver( self ): attrs = 't', 'r' for item in (self.items + self.getPlacers()): for a in attrs: attrPaths = [ a ] + [ '%s%s' % (a, c) for c in CHANNELS ] for attrPath in attrPaths: attrPath = '%s.%s' % (item, attrPath) isLocked = getAttr( attrPath, lock=True ) if isLocked: setAttr( attrPath, lock=False ) #need to make sure attributes are unlocked before trying to break a connection - regardless of whether the attribute is the source or destination... 8-o delete( attrPath, inputConnectionsAndNodes=True ) if isLocked: setAttr( attrPath, lock=True ) def getDriver( self ): ''' returns the part driving this part if any, otherwise None is returned ''' attrs = 't', 'r' for item in self: for attr in attrs: for c in CHANNELS: cons = listConnections( '%s.%s%s' % (item, attr, c), destination=False, skipConversionNodes=True, t='joint' ) if cons: for c in cons: part = SkeletonPart.InitFromItem( c ) if part: return part def getDriven( self ): ''' returns a list of driven parts if any, otherwise an empty list is returned ''' attrs = 't', 'r' allOutConnections = [] for item in self: for attr in attrs: for c in CHANNELS: allOutConnections += listConnections( '%s.%s%s' % (item, attr, c), source=False, skipConversionNodes=True, t='joint' ) or [] if allOutConnections: allOutConnections = filesystem.removeDupes( allOutConnections ) return getPartsFromObjects( allOutConnections ) return [] ### FINALIZATION ### def generateItemHash( self, item ): ''' creates a hash for the position and orientation of the joint so we can ensure the state is still the same at a later date ''' tHashAccum = 0 joHashAccum = 0 tChanValues = [] joChanValues = [] for c in CHANNELS: #we hash the rounded string of the float to eliminate floating point error t = getAttr( '%s.t%s' % (item, c) ) jo = getAttr( '%s.jo%s' % (item, c) ) val = '%0.4f %0.4f' % (t, jo) tHashAccum += hash( val ) tChanValues.append( t ) joChanValues.append( jo ) iParent = getNodeParent( item ) return iParent, tHashAccum, tChanValues, joChanValues @d_performInSkeletonPartScene def finalize( self ): ''' performs some finalization on the skeleton - ensures everything is aligned, and then stores a has of the orientations into the skeleton so that we can later compare the skeleton orientation with the stored state ''' #early out if finalization is valid if self.compareAgainstHash(): return #make sure any driver relationship is broken self.breakDriver() #make sure the part has been aligned self.align() #remove any visualizations self.unvisualize() #unlock all channels and make keyable - we cannot change lock/keyability #state once the skeleton is referenced into the rig, and we need them to #be in such a state to build the rig attrState( self.selfAndOrphans(), ('t', 'r'), False, True, True ) attrState( self.selfAndOrphans(), ('s', 'v'), False, False, True ) #create a hash for the position and orientation of the joint so we can ensure the state is still the same at a later date for i in self.selfAndOrphans(): if not objExists( '%s._skeletonFinalizeHash' % i ): addAttr( i, ln='_skeletonFinalizeHash', dt='string' ) setAttr( '%s._skeletonFinalizeHash' % i, str( self.generateItemHash( i ) ), type='string' ) def compareAgainstHash( self ): ''' compares the current orientation of the partto the stored state hash when the part was last finalized. if the part has differing a bool indicating whether the current state matches the stored finalization state is returned ''' #if the part is rigged, then return True - if its been rigged then it should have been properly finalized so we should be good if self.isRigged(): return True #create a hash for the position and orientation of the joint so we can ensure the state is still the same at a later date for i in self.selfAndOrphans(): #if the joint is marked with the align skip state, skip the finalization check if getAlignSkipState( i ): continue #if it doesn't have the finalization hash attribute it can't possibly be finalized if not objExists( '%s._skeletonFinalizeHash' % i ): return False #figure out what the hash should be and compare it to the one that is stored iParent, xformHash, xxa, yya = self.generateItemHash( i ) try: storedParent, stored_xHash, xxb, yyb = eval( getAttr( '%s._skeletonFinalizeHash' % i ) ) except: print 'stored hash differs from the current hashing routine - please re-finalize' return False #if the stored parent is different from the current parent, there may only be a namespace conflict - so strip namespace prefixes and redo the comparison if iParent != storedParent: if Name( iParent ).strip() != Name( storedParent ).strip(): print 'parenting mismatch on %s since finalization (%s vs %s)' % (i, iParent, storedParent) return False TOLERANCE = 1e-6 #tolerance used to compare floats def doubleCheckValues( valuesA, valuesB ): for va, vb in zip( valuesA, valuesB ): va, vb = float( va ), float( vb ) if va - vb > TOLERANCE: return False return True if xformHash != stored_xHash: #so did we really fail? sometimes 0 gets stored as -0 or whatever, so make sure the values are actually different if not doubleCheckValues( xxa, xxb ): print 'the translation on %s changed since finalization (%s vs %s)' % (i, xxa, xxb) return False if not doubleCheckValues( yya, yyb ): print 'joint orienatation on %s changed since finalization (%s vs %s)' % (i, yya, yyb) return False return True ### RIGGING ### @d_unifyUndo def rig( self, **kw ): ''' constructs the rig for this part ''' #check the skeleton part to see if it already has a rig rigContainerAttrname = 'rigContainer' rigContainerAttrpath = '%s.%s' % (self._container, rigContainerAttrname) if not objExists( rigContainerAttrpath ): addAttr( self._container, ln=rigContainerAttrname, at='message' ) #check to see if there is already a rig built if listConnections( rigContainerAttrpath, d=False ): print 'Rig already built for %s - skipping' % self return #update the kw dict for the part rigKw = self.getBuildKwargs() rigKw.update( self.getRigKwargs() ) rigKw.update( kw ) kw = rigKw if kw.get( 'disable', False ): print 'Rigging disabled for %s - skipping' % self return #pop the rig method name out of the kwarg dict, and look it up try: rigMethodName = kw.pop( 'rigMethodName', self.RigTypes[ 0 ].__name__ ) except IndexError: print "No rig method defined for %s" % self return #make sure to break drivers before we rig self.breakDriver() #discover the rigging method rigType = self.GetRigMethod( rigMethodName ) if rigType is None: print 'ERROR :: there is no such rig method with the name %s' % rigMethodName return #bulid the rig and connect it to the part theRig = rigType.Create( self, **kw ) if theRig is None: MGlobal.displayError( "Failed to create the rig for part %s" % self ) return connectAttr( '%s.message' % theRig.getContainer(), '%s.rigContainer' % self._container, f=True ) def isRigged( self ): ''' returns whether this skeleton part is rigged or not ''' return self.getRigContainer() is not None ### VOLUME CREATION ### def buildVolumes( self ): ''' attempts to create volumes for the skeleton that reasonably tightly fits the character mesh. these volumes can then be modified quickly using standard modelling tools, and can be then used to generate a fairly good skinning solution for the character mesh ''' #remove any visualization - this can confuse the volume removal code as it can't tell what is a volume mesh and what is a visualization mesh self.unvisualize() #remove any existing volumes self.removeVolumes() #get the list of character meshes characterMeshes = getCharacterMeshes() for item in self: size, centre = rigUtils.getJointSizeAndCentre( item, ignoreSkinning=True ) #we just want to move the joint to the centre of the primary bone axis - not all axes... otherAxes = BONE_AIM_AXIS.otherAxes() centre[ otherAxes[0] ] = 0 centre[ otherAxes[1] ] = 0 volumes = self.buildItemVolume( item, size, centre ) for v in volumes: v = rename( v, '%s__sbVolume#' % item ) makeIdentity( v, a=True, t=True, r=True, s=True ) shrinkWrap( v, characterMeshes ) def iterItemVolumes( self ): ''' generator to yield a 2-tuple of each part item, and the list of volumes associated with it ''' for item in self: children = listRelatives( item, pa=True ) if children: childMeshes = listRelatives( children, pa=True, type='mesh' ) if childMeshes: meshParents = [ m for m in listRelatives( childMeshes, p=True, pa=True ) if nodeType( m ) != 'joint' ] #make sure not to remove joints... yield item, meshParents def removeVolumes( self ): ''' handles removing any existing volumes on the skeleton ''' for item, volumes in self.iterItemVolumes(): if volumes: delete( volumes ) def buildItemVolume( self, item, size, centre ): ''' handles creation of the actual volume - generally if you want control over volume creation for a part you'll just need to override this method. It gets given the joint's "size" and its "centre" and you're then free to build geometry accordingly ''' sides = self.AUTO_VOLUME_SIDES height = float( size[ BONE_AIM_AXIS ] ) geo = polyCylinder( h=height * 0.95, r=0.01, ax=BONE_AIM_VECTOR, sx=sides, sy=round( height/2.0 ), ch=False )[0] parent( geo, item, r=True ) setAttr( '%s.t' % geo, *centre ) #finally remove the top and bottom cylinder caps - they're always the last 2 faces numFaces = meshUtils.numFaces( geo ) delete( '%s.f[ %d:%d ]' % (geo, numFaces-2, numFaces-1) ) return [geo] def createRotationCurves( theJoint ): """ create the UI widget for each rotGUI """ rotGuiOverRideColor = [ 13 , 14 , 6 ] rotGuiCurves = [] c = curve( d=1, p=((0.000000, -0.000000, -1.000000), (-0.000000, 0.500000, -0.866025), (-0.000000, 0.866025, -0.500000), (-0.000000, 1.000000, -0.000000), (-0.000000, 0.350000, 0.000000), (-0.116667, 0.116667, -0.116667), (-0.000000, 0.000000, -0.350000), (0.000000, -0.436239, -0.464331), (0.000000, -0.866025, -0.350000), (0.000000, -1.000000, 0.000000), (0.000000, -0.866025, -0.500000), (0.000000, -0.500000, -0.866025), (0.000000, -0.000000, -1.000000)) ) rotGuiCurves.append( c ) c = curve( d=1, p=((0.000000, 0.000000, -1.000000), (-0.500000, 0.000000, -0.866025), (-0.866025, 0.000000, -0.500000), (-1.000000, 0.000000, -0.000000), (-0.350000, -0.000000, -0.000000), (-0.116667, 0.116666, -0.116667), (-0.000000, -0.000000, -0.350000), (0.436239, -0.000000, -0.464331), (0.866025, -0.000000, -0.350000), (1.000000, -0.000000, 0.000000), (0.866025, 0.000000, -0.500000), (0.500000, 0.000000, -0.866025), (0.000000, 0.000000, -1.000000)) ) rotGuiCurves.append( c ) c = curve( d=1, p=((0.000000, 1.000000, -0.000000), (-0.500000, 0.866025, -0.000000), (-0.866025, 0.500000, -0.000000), (-1.000000, 0.000000, -0.000000), (-0.350000, -0.000000, -0.000000), (-0.116667, 0.116667, -0.116666), (-0.000000, 0.350000, 0.000000), (0.436239, 0.464331, -0.000000), (0.866025, 0.350000, -0.000000), (1.000000, -0.000000, 0.000000), (0.866025, 0.500000, -0.000000), (0.500000, 0.866025, -0.000000), (0.000000, 1.000000, -0.000000)) ) rotGuiCurves.append( c ) for i, theCurve in enumerate( rotGuiCurves ): theScale = 3 setAttr( '%s.sx' % theCurve, theScale ) setAttr( '%s.sy' % theCurve, theScale ) setAttr( '%s.sz' % theCurve, theScale ) makeIdentity( theCurve, a=True, s=True ) theCurveShape = listRelatives( theCurve, s=True, pa=True )[ 0 ] setAttr( '%s.overrideEnabled' % theCurveShape, 1 ) setAttr( '%s.overrideDisplayType' % theCurveShape, 0 ) setAttr( '%s.overrideColor' % theCurveShape, rotGuiOverRideColor[i] ) parent( theCurveShape, theJoint, add=True, shape=True ) delete( theCurve ) def kwargsToOptionStr( kwargDict ): toks = [] for k, v in kwargDict.iteritems(): if isinstance( v, (list, tuple) ): v = ' '.join( v ) elif isinstance( v, bool ): v = int( v ) toks.append( '-%s %s' % (k, v) ) return ' '.join( toks ) def createJoint( name=None ): ''' simple wrapper to deal with joint creation - mainly provides a hook to control joint creation should that be needed ''' if name: if objExists( name ): name = name +'#' return createNode( 'joint', n=name ) return createNode( 'joint' ) def buildEndPlacer(): ''' builds a placer for the end of a chain. This is generally useful for aligning the last joint in a chain but can also be useful for marking up interesting pivots on parts such as feet with foot edges etc... ''' transform = createNode( 'transform' ) setAttr( '%s.displayHandle' % transform, True ) return transform def jointSize( jointName, size ): ''' convenience function to set the size of a joint ''' setAttr( '%s.radius' % jointName, size ) def getRoot(): joints = ls( typ='joint' ) for j in joints: if objExists( '%s.%s' % (j, TOOL_NAME) ): return j return None class Root(SkeletonPart): HAS_PARITY = False @classmethod def _build( cls, **kw ): idx = kw[ 'idx' ] partScale = kw[ 'partScale' ] root = createJoint() root = rename( root, 'root' ) move( 0, partScale / 1.75, 0, root, ws=True ) jointSize( root, 3 ) #tag the root joint with the tool name only if its the first root created - having multiple roots in a scene/skeleton is entirely valid if idx == 0: cmd.addAttr( ln=TOOL_NAME, at='message' ) #the root can only have a parent if its not the first root created if idx: move( 0, 0, -partScale / 2, root, r=True ) return [ root ] def _buildPlacers( self ): return [] def _align( self, _initialAlign=False ): for i in self.selfAndOrphans(): alignItemToWorld( self[ 0 ] ) def finalize( self ): #make sure the scale is unlocked on the base joint of the root part... attrState( self.base, 's', False, False, True ) super( self.__class__, Root ).finalize( self ) def buildItemVolume( self, item, size, centre ): height = size[2] / 3 width = max( size[0], size[1] ) / 3 geo = polyCube( w=width, h=height, d=width, sx=3, sy=3, sz=2, ax=(0, 0, 1), ch=True )[0] parent( geo, item, r=True ) setAttr( '%s.t' % geo, *centre ) return [geo] def getParent( parent=None ): if parent is None: #grab the selection and walk up till we find a joint sel = ls( sl=True, type='transform' ) if sel: obj = sel[0] while nodeType( obj ) != 'joint': obj = getNodeParent( obj ) if obj is None: break return obj existingRoot = getRoot() return existingRoot or Root.Create().base if isinstance( parent, SkeletonPart ): return parent.end if objExists( parent ): return parent return getRoot() or Root.Create().base def sortPartsByHierarchy( parts ): ''' returns a list of the given parts in a list sorted by hierarchy ''' sortedParts = sortByHierarchy( [ p.base for p in parts ] ) return [ SkeletonPart.InitFromItem( p ) for p in sortedParts ] def getPartsFromObjects( objs ): ''' returns a list of parts that have at least one of their items selected ''' parts = [] for o in objs: try: parts.append( SkeletonPart.InitFromItem( o ) ) except SkeletonError: continue selectedParts = filesystem.removeDupes( parts ) return selectedParts @d_unifyUndo @api.d_maintainSceneSelection def realignSelectedParts(): ''' re-aligns all selected parts ''' sel = ls( sl=True ) selectedParts = sortPartsByHierarchy( getPartsFromObjects( sel ) ) for part in selectedParts: part.align() @d_unifyUndo @api.d_maintainSceneSelection def realignAllParts(): ''' re-aligns all parts in the current scene ''' for part in SkeletonPart.IterAllPartsInOrder(): try: part.align() except: print 'ERROR: %s failed to align properly' % part continue @d_unifyUndo @api.d_maintainSceneSelection def finalizeAllParts(): #do a pre-pass on the skin clusters to remove un-used influences - this can speed up the speed of the alignment code #is directly impacted by the number of joints involved in the skin cluster skinClusters = ls( typ='skinCluster' ) for s in skinClusters: skinCluster( s, e=True, removeUnusedInfluence=True ) failedParts = [] for part in sortPartsByHierarchy( part for part in SkeletonPart.IterAllParts() ): part.breakDriver() if not part.compareAgainstHash(): try: part.finalize() except: failedParts.append( part ) if filesystem.IS_WING_DEBUG: raise print 'ERROR: %s failed to finalize properly!' % part continue return failedParts @d_unifyUndo def freezeAllParts(): for part in SkeletonPart.IterAllParts(): part.freeze() @d_unifyUndo def setupAutoMirror(): partsInMirrorRelationship = set() for part in SkeletonPart.IterAllParts(): if part in partsInMirrorRelationship: continue if part.hasParity(): idx = part.getIdx() parity = part.getParity() #if we have a left, look for a right if parity == Parity.LEFT: partToDrive = None #try to find a matching part with the next index for partOfType in part.IterAllParts(): if partOfType.getIdx() == idx + 1: partToDrive = partOfType break #if we can't find a part with an incremented index, look for a part with the opposing parity if not partToDrive: for partOfType in part.IterAllParts(): if partOfType.getParity() == Parity.RIGHT: partToDrive = partOfType break #if an appropriate part was found, setup the driven relationship if partToDrive: try: part.driveOtherPart( partToDrive ) #if a skeleton error is thrown, ignore it (it means the parts are incompatible) but add the part to the partsInMirrorRelationship set except SkeletonError: pass partsInMirrorRelationship.add( part ) partsInMirrorRelationship.add( partToDrive ) def getNamespaceFromReferencing( node ): ''' returns the namespace contribution from referencing. this is potentially different from just querying the namespace directly from the node because the node in question may have had a namespace before it was referenced ''' if referenceQuery( node, isNodeReferenced=True ): refNode = referenceQuery( node, referenceNode=True ) namespace = cmd.file( cmd.referenceQuery( refNode, filename=True ), q=True, namespace=True ) return '%s:' % namespace return '' @d_unifyUndo @api.d_showWaitCursor @api.d_maintainSceneSelection def buildAllVolumes(): #align all parts first for part in SkeletonPart.IterAllParts(): if not part.compareAgainstHash(): part.align() for part in SkeletonPart.IterAllParts(): part.buildVolumes() @d_unifyUndo def removeAllVolumes(): for part in SkeletonPart.IterAllParts(): part.removeVolumes() def shrinkWrap( obj, shrinkTo=None, performReverse=False ): if shrinkTo is None: shrinkTo = getCharacterMeshes() if not isinstance( shrinkTo, (list, tuple) ): shrinkTo = [ shrinkTo ] from maya.OpenMaya import MFnMesh, MFloatPointArray, MFloatArray, MPoint, MFloatPoint, MVector, MFloatVector, MItMeshVertex, MDagPath, MSpace kWorld = MSpace.kWorld kTransform = MSpace.kTransform obj = asMObject( obj ) shrinkTo = map( asMObject, shrinkTo ) #get the shape nodes... dagObj = MDagPath.getAPathTo( obj ) dagObj.extendToShape() #NOTE: we use the exclusive matrix because we want the object's parent - which is assumed to be the joint dagWorldMatrix = dagObj.exclusiveMatrix() dagWorldMatrixInv = dagObj.exclusiveMatrixInverse() dagShinkTo = map( MDagPath.getAPathTo, shrinkTo ) for dag in dagShinkTo: dag.extendToShape() fnObj = MFnMesh( dagObj ) fnShrinkTo = map( MFnMesh, dagShinkTo ) aimIdx = BONE_AIM_AXIS otherIdxs = idxA, idxB = BONE_AIM_AXIS.otherAxes() #construct the MMeshIntersector instances accellerators = [] for fnShrink in fnShrinkTo: a = MFnMesh.autoUniformGridParams() accellerators.append( a ) #now iterate over the verts in the obj, shoot rays outward in the direction of the normal and try to fit as best as #possible to the given shrink meshes itObjVerts = MItMeshVertex( dagObj ) vertPositions = [] while not itObjVerts.isDone(): intersects = [] pos = itObjVerts.position( kWorld ) actualPos = Vector( (pos.x, pos.y, pos.z) ) normal = MVector() itObjVerts.getNormal( normal, kWorld ) #holy BAWLS maya is shite... MVector and MFloatVector are COMPLETELY different classes, and you can't construct one from the other?! What kind of retard wrote this API pos = MFloatPoint( pos.x, pos.y, pos.z ) normal = MFloatVector( normal.x, normal.y, normal.z ) normal.normalize() #now get ray intersections with the shrinkTo meshes for fnShrinkMesh, accel in zip( fnShrinkTo, accellerators ): hitPoints = MFloatPointArray() def go( rev=False ): fnShrinkMesh.allIntersections( pos, normal, #raySource, rayDirection None, None, False, #faceIds, triIds, idsSorted kWorld, 1000, rev, #space, maxParam, testBothDirs accel, True, #accelParams, sortHits hitPoints, #this is all we really care about... None, None, None, None, None ) go() if performReverse and not hitPoints.length(): go( performReverse ) for n in range( hitPoints.length() ): p = hitPoints[ n ] intersects.append( Vector( (p.x, p.y, p.z) ) ) #deal with native vectors for now... #if there is just one intersection, easy peasy if len( intersects ) == 1: newPosition = intersects[0] #otherwise we need to figure out which one is the best match... elif intersects: #first sort them by their distance to the vert - I think they should be sorted already, but... sortByDist = [ ((p-actualPos).get_magnitude(), p) for p in intersects ] sortByDist.sort() #not sure how much guesswork to do here - so just use the closest... newPosition = sortByDist[0][1] #if there are no matches just use the actual vert position so we don't have to handle this case below... else: newPosition = actualPos vertPositions.append( (actualPos, newPosition) ) vert = itObjVerts.next() #now we have a list of vertex positions, figure out the average delta and clamp deltas that are too far away from this average deltaSum = 0 numZeroDeltas = 0 for pos, newPos in vertPositions: delta = (pos - newPos).get_magnitude() if not delta: numZeroDeltas += 1 deltaSum += delta #if all deltas are zero, there is nothing to do... bail! if len( vertPositions ) == numZeroDeltas: return deltaAverage = float( deltaSum ) / (len( vertPositions ) - numZeroDeltas) #don't count deltas that are zero... clampedVertPositions = [] MAX_DIVERGENCE = 1.1 #the maximum allowable variance from the average delta acceptableDelta = deltaAverage * MAX_DIVERGENCE for pos, newPos in vertPositions: if newPos is None: clampedVertPositions.append( None ) continue delta = (pos - newPos).get_magnitude() #if the magnitude of the delta is too far from the average, scale down the magnitude if delta > acceptableDelta: deltaVector = newPos - pos deltaVector = deltaVector * (acceptableDelta / delta) clampedVertPositions.append( pos + deltaVector ) else: clampedVertPositions.append( newPos ) #now set the vert positions n = 0 itObjVerts.reset() while not itObjVerts.isDone(): newPos = clampedVertPositions[ n ] position = MPoint( *newPos ) itObjVerts.setPosition( position, kWorld ) n += 1 vert = itObjVerts.next() def shrinkWrapSelection( shrinkTo=None ): for obj in ls( sl=True, type=('mesh', 'transform') ): makeIdentity( obj, a=True, t=True, r=True, s=True ) shrinkWrap( obj, shrinkTo ) def volumesToSkinning(): #first grab all the volumes and combine them into a single mesh, then generate weights from the original volumes (this should #result in the duplicates being rigidly skinned to the skeleton) then transfer the weights from the combined mesh to the #character meshes allVolumes = [] for part in SkeletonPart.IterAllParts(): for item, volumes in part.iterItemVolumes(): allVolumes += volumes #get the character meshes before we build the temp transfer surface charMeshes = getCharacterMeshes() import skinWeights #combine them all duplicateVolumes = duplicate( allVolumes, renameChildren=True ) makeIdentity( duplicateVolumes, a=True, t=True, r=True, s=True ) combinedVolumes = polyUnite( duplicateVolumes, ch=False )[0] #generate weights skinWeights.saveWeights( allVolumes ) skinWeights.loadWeights( [combinedVolumes], tolerance=2 ) #now transfer weights to the character meshes for charMesh in charMeshes: targetSkinCluster = skinWeights.transferSkinning( combinedVolumes, charMesh ) #now lets do a little smoothing #skinCluster( targetSkinCluster, e=True, smoothWeights=0.65 ) """ #JESUS!!! for some weird as piss reason maya doesn't like this python command: skinCluster( targetSkinCluster, q=True, smoothWeights=0.75 ) #nor this mel command: skinCluster -q -smoothWeights 0.75 targetSkinCluster #you NEED to run this mel command: skinCluster -smoothWeights 0.75 -q targetSkinCluster #which makes no goddamn sense - fuuuuuuuuuuuuuu alias! #not to mention that the stupid as piss command returns vert indices, not components... what a bullshit api. vertIdxs = mel.eval( "skinCluster -smoothWeights 0.5 -q %s" % targetSkinCluster ) baseStr = targetMesh +'.vtx[%d]' select( [ baseStr % idx for idx in vertIdxs ] ) polySelectConstraint( pp=1, t=0x0001 ) #expand the selection skinCluster( targetSkinCluster, e=True, smoothWeights=0.7, smoothWeightsMaxIterations=1 ) """ #delete the combined meshes - we're done with them delete( combinedVolumes ) def getSkeletonBuilderJointCount(): ''' returns a 2-tuple containing the total skeleton builder joint count, and the total number of joints that are involved in a skin cluster ''' #get the root joint and get a list of all joints under it skeletonBuilderJoints = [] for rootPart in Root.IterAllParts(): skeletonBuilderJoints += rootPart.items skeletonBuilderJoints += listRelatives( rootPart.items, ad=True, type='joint' ) or [] #generate a list of joints involved in skinning skinnedJoints = [] for mesh in ls( type='mesh' ): skinCluster = mel.findRelatedSkinCluster( mesh ) if skinCluster: skinnedJoints += mel.eval( 'skinPercent -ib 0.001 -q -t %s "%s.vtx[*]"' % (skinCluster, mesh) ) #now get the intersection of the two lists - these are the joints on the character that are skinned skinnedSkeletonBuilderJoints = set( skeletonBuilderJoints ).intersection( set( skinnedJoints ) ) return len( skeletonBuilderJoints ), len( skinnedSkeletonBuilderJoints ) def displaySkeletonBuilderJointCount(): totalJoints, skinnedJoints = getSkeletonBuilderJointCount() return '%d skinned / %d total' % (skinnedJoints, totalJoints) def setupSkeletonBuilderJointCountHUD(): if headsUpDisplay( HUD_NAME, ex=True ): headsUpDisplay( HUD_NAME, rem=True ) else: jointbb = headsUpDisplay( nfb=0 ) headsUpDisplay( HUD_NAME, section=0, block=jointbb, blockSize="small", label="Joint Count:", labelFontSize="small", command=displaySkeletonBuilderJointCount, event="SelectionChanged" ) #, nodeChanges="attributeChange" #end
Python
from rigPrim_ikFkBase import * from rigPrim_stretchy import StretchRig class IkFkArm(IkFkBase): __version__ = 3 + IkFkBase.__version__ #factor in the version of the ikfk sub rig part SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Arm' ), ) CONTROL_NAMES = 'control', 'fkBicep', 'fkElbow', 'fkWrist', 'poleControl', 'clavicle', 'allPurpose' def getFkControls( self ): return self.getControl( 'fkBicep' ), self.getControl( 'fkElbow' ), self.getControl( 'fkWrist' ) def getIkHandle( self ): ikCons = listConnections( '%s.message' % self.getControl( 'fkBicep' ), s=False, type='ikHandle' ) if ikCons: return ikCons[0] def _build( self, skeletonPart, translateClavicle=True, stretchy=True, **kw ): return self.doBuild( skeletonPart.bicep, skeletonPart.elbow, skeletonPart.wrist, skeletonPart.clavicle, translateClavicle, stretchy, **kw ) def doBuild( self, bicep, elbow, wrist, clavicle=None, translateClavicle=True, stretchy=False, **kw ): getWristToWorldRotation( wrist, True ) colour = self.getParityColour() wireColor = 14 if self.getParity() == Parity.LEFT else 13 parentControl, rootControl = getParentAndRootControl( clavicle or bicep ) #build the base controls self.buildBase( ARM_NAMING_SCHEME ) #create variables for each control used ikHandle = self.ikHandle ikArmSpace, fkArmSpace = self.ikSpace, self.fkSpace fkControls = driverBicep, driverElbow, driverWrist = self.driverUpper, self.driverMid, self.driverLower elbowControl = self.poleControl #build the clavicle if clavicle: clavOffset = AX_Y.asVector() * getAutoOffsetAmount( clavicle, listRelatives( clavicle, pa=True ), AX_Y ) clavControl = buildControl( 'clavicleControl%s' % self.getParity().asName(), PlaceDesc( bicep, clavicle, clavicle ), shapeDesc=ShapeDesc( 'sphere' ), scale=self.scale*1.25, offset=clavOffset, offsetSpace=SPACE_WORLD, colour=colour ) clavControlOrient = getNodeParent( clavControl ) parent( clavControlOrient, parentControl ) parent( fkArmSpace, clavControl ) if not translateClavicle: attrState( clavControl, 't', *LOCK_HIDE ) else: clavControl = None parent( fkArmSpace, parentControl ) #build space switching allPurposeObj = self.buildAllPurposeLocator( 'arm' ) buildDefaultSpaceSwitching( bicep, elbowControl, **spaceSwitching.NO_ROTATION ) buildDefaultSpaceSwitching( bicep, self.control, [ allPurposeObj ], [ 'All Purpose' ], True ) buildDefaultSpaceSwitching( bicep, driverBicep, **spaceSwitching.NO_TRANSLATION ) #make the limb stretchy? if stretchy: StretchRig.Create( self.getSkeletonPart(), self.control, fkControls, '%s.ikBlend' % ikHandle, parity=self.getParity() ) controls = self.control, driverBicep, driverElbow, driverWrist, elbowControl, clavControl, allPurposeObj namedNodes = self.ikSpace, self.fkSpace, self.ikHandle, self.endOrient, self.lineNode return controls, namedNodes class IkFkLeg(IkFkBase): __version__ = 2 + IkFkBase.__version__ #factor in the version of the ikfk sub rig part SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Leg' ), ) CONTROL_NAMES = 'control', 'fkThigh', 'fkKnee', 'fkAnkle', 'poleControl', 'allPurpose' def getFkControls( self ): return self.getControl( 'fkThigh' ), self.getControl( 'fkKnee' ), self.getControl( 'fkAnkle' ) def getIkHandle( self ): ikCons = listConnections( '%s.message' % self.getControl( 'fkThigh' ), s=False, type='ikHandle' ) if ikCons: return ikCons[0] def _build( self, skeletonPart, stretchy=True, **kw ): return self.doBuild( skeletonPart.thigh, skeletonPart.knee, skeletonPart.ankle, stretchy=stretchy, **kw ) def doBuild( self, thigh, knee, ankle, stretchy=True, **kw ): partParent, rootControl = getParentAndRootControl( thigh ) #first rotate the foot so its aligned to a world axis footCtrlRot = Vector( getAnkleToWorldRotation( str( ankle ), 'z', True ) ) footCtrlRot = (0, -footCtrlRot.y, 0) #build the base controls self.buildBase( LEG_NAMING_SCHEME ) #if the legs are parented to a root part - which is usually the case but not always - grab the hips and parent the fk control space to the hips hipsControl = partParent partParentRigPart = RigPart.InitFromItem( partParent ) if isinstance( partParentRigPart.getSkeletonPart(), Root ): hipsControl = partParentRigPart.getControl( 'hips' ) #if the part parent in a Root primitive, grab the hips control instead of the root gimbal - for the leg parts this is preferable parentRigPart = RigPart.InitFromItem( partParent ) if isinstance( parentRigPart, Root ): partParent = parentRigPart.getControl( 'hips' ) #create variables for each control used legControl = self.control legControlSpace = getNodeParent( legControl ) ikLegSpace, fkLegSpace = self.ikSpace, self.fkSpace driverThigh, driverKnee, driverAnkle = self.driverUpper, self.driverMid, self.driverLower fkControls = driverThigh, driverKnee, driverAnkle kneeControl = self.poleControl kneeControlSpace = getNodeParent( kneeControl ) parent( kneeControlSpace, partParent ) toe = listRelatives( ankle, type='joint', pa=True ) or None toeTip = None if toe: toe = toe[0] #if the toe doesn't exist, build a temp one if not toe: toe = group( em=True ) parent( toe, ankle, r=True ) move( 0, -self.scale, self.scale, toe, r=True, ws=True ) toeTip = self.getSkeletonPart().endPlacer if not toeTip: possibleTips = listRelatives( toe, type='joint', pa=True ) if possibleTips: toeTip = possibleTips[ 0 ] #build the objects to control the foot suffix = self.getSuffix() footControlSpace = buildNullControl( "foot_controlSpace"+ suffix, ankle, parent=legControl ) heelRoll = buildNullControl( "heel_roll_piv"+ suffix, ankle, offset=(0, 0, -self.scale), parent=footControlSpace ) select( heelRoll ) #move command doesn't support object naming when specifying a single axis move, so we must selec the object first move( 0, 0, 0, rpr=True, y=True ) if toeTip: toeRoll = buildNullControl( "leg_toe_roll_piv"+ suffix, toeTip, parent=heelRoll ) else: toeRoll = buildNullControl( "leg_toe_roll_piv"+ suffix, toe, parent=heelRoll, offset=(0, 0, self.scale) ) footBankL = buildNullControl( "bank_in_piv"+ suffix, toe, parent=toeRoll ) footBankR = buildNullControl( "bank_out_piv"+ suffix, toe, parent=footBankL ) footRollControl = buildNullControl( "roll_piv"+ suffix, toe, parent=footBankR ) #move bank pivots to a good spot on the ground placers = self.getSkeletonPart().getPlacers() numPlacers = len( placers ) if placers: toePos = Vector( xform( toe, q=True, ws=True, rp=True ) ) if numPlacers >= 2: innerPlacer = Vector( xform( placers[1], q=True, ws=True, rp=True ) ) move( innerPlacer[0], innerPlacer[1], innerPlacer[2], footBankL, a=True, ws=True, rpr=True ) if numPlacers >= 3: outerPlacer = Vector( xform( placers[2], q=True, ws=True, rp=True ) ) move( outerPlacer[0], outerPlacer[1], outerPlacer[2], footBankR, a=True, ws=True, rpr=True ) if numPlacers >= 4: heelPlacer = Vector( xform( placers[3], q=True, ws=True, rp=True ) ) move( heelPlacer[0], heelPlacer[1], heelPlacer[2], heelRoll, a=True, ws=True, rpr=True ) #move the knee control so its inline with the leg rotate( footCtrlRot[0], footCtrlRot[1], footCtrlRot[2], kneeControlSpace, p=xform( thigh, q=True, ws=True, rp=True ), a=True, ws=True ) makeIdentity( kneeControl, apply=True, t=True ) #add attributes to the leg control, to control the pivots addAttr( legControl, ln='rollBall', at='double', min=0, max=10, k=True ) addAttr( legControl, ln='rollToe', at='double', min=-10, max=10, k=True ) addAttr( legControl, ln='twistFoot', at='double', min=-10, max=10, k=True ) addAttr( legControl, ln='bank', at='double', min=-10, max=10, k=True ) #replace the legControl as a target to the parent constraint on the endOrient transform so the ikHandle respects the foot slider controls footFinalPivot = buildNullControl( "final_piv"+ suffix, ankle, parent=footRollControl ) delete( parentConstraint( footFinalPivot, self.ikHandle, mo=True ) ) parent( self.ikHandle, footFinalPivot ) replaceGivenConstraintTarget( self.endOrientSpaceConstraint, legControl, footFinalPivot ) #build the SDK's to control the pivots setDrivenKeyframe( '%s.rx' % footRollControl, cd='%s.rollBall' % legControl, dv=0, v=0 ) setDrivenKeyframe( '%s.rx' % footRollControl, cd='%s.rollBall' % legControl, dv=10, v=90 ) setDrivenKeyframe( '%s.rx' % footRollControl, cd='%s.rollBall' % legControl, dv=-10, v=-90 ) setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=0, v=0 ) setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=10, v=90 ) setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=0, v=0 ) setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=-10, v=-90 ) setDrivenKeyframe( '%s.ry' % toeRoll, cd='%s.twistFoot' % legControl, dv=-10, v=-90 ) setDrivenKeyframe( '%s.ry' % toeRoll, cd='%s.twistFoot' % legControl, dv=10, v=90 ) min = -90 if self.getParity() == Parity.LEFT else 90 max = 90 if self.getParity() == Parity.LEFT else -90 setDrivenKeyframe( '%s.rz' % footBankL, cd='%s.bank' % legControl, dv=0, v=0 ) setDrivenKeyframe( '%s.rz' % footBankL, cd='%s.bank' % legControl, dv=10, v=max ) setDrivenKeyframe( '%s.rz' % footBankR, cd='%s.bank' % legControl, dv=0, v=0 ) setDrivenKeyframe( '%s.rz' % footBankR, cd='%s.bank' % legControl, dv=-10, v=min ) #setup the toe if we have one if toe: toeSDK = buildControl( "toeSDK%s" % suffix, toe, shapeDesc=SHAPE_NULL, parent=footBankR, scale=self.scale, colour=self.getParityColour() ) toeConstraint = parentConstraint( driverAnkle, toe, w=0, mo=True )[0] toeConstraintAttrs = listAttr( toeConstraint, ud=True ) expression( s='%s.%s = %s.ikBlend;\n%s.%s = 1 - %s.ikBlend;' % (toeConstraint, toeConstraintAttrs[ 0 ], self.control, toeConstraint, toeConstraintAttrs[ 1 ], self.control), n='toe_parentingConstraintSwitch' ) addAttr( legControl, ln='toe', at='double', min=-10, max=10, k=True ) setDrivenKeyframe( '%s.r%s' % (toeSDK, ROT_AXIS.asCleanName()), cd='%s.toe' % legControl, dv=-10, v=90 ) setDrivenKeyframe( '%s.r%s' % (toeSDK, ROT_AXIS.asCleanName()), cd='%s.toe' % legControl, dv=10, v=-90 ) #build space switching parent( fkLegSpace, hipsControl ) allPurposeObj = self.buildAllPurposeLocator( 'leg' ) spaceSwitching.build( legControl, (self.getWorldControl(), hipsControl, rootControl, allPurposeObj), ('World', None, 'Root', 'All Purpose'), space=legControlSpace ) spaceSwitching.build( kneeControl, (legControl, partParent, rootControl, self.getWorldControl()), ("Leg", None, "Root", "World"), **spaceSwitching.NO_ROTATION ) spaceSwitching.build( driverThigh, (hipsControl, rootControl, self.getWorldControl()), (None, 'Root', 'World'), **spaceSwitching.NO_TRANSLATION ) spaceSwitching.build( kneeControl, (self.getWorldControl(), hipsControl, rootControl), ('World', None, 'Root'), **spaceSwitching.NO_ROTATION ) #make the limb stretchy if stretchy: StretchRig.Create( self.getSkeletonPart(), legControl, fkControls, '%s.ikBlend' % self.ikHandle, parity=self.getParity() ) if objExists( '%s.elbowPos' % legControl ): renameAttr( '%s.elbowPos' % legControl, 'kneePos' ) controls = legControl, driverThigh, driverKnee, driverAnkle, kneeControl, allPurposeObj namedNodes = self.ikSpace, self.fkSpace, self.ikHandle, self.endOrient, self.lineNode return controls, namedNodes #end
Python
from maya.cmds import * from devTest_base import d_makeNewScene, _BaseTest import skeletonBuilder import skeletonBuilderUI import rigPrimitives __all__ = [ 'TestSkeletonBuilder' ] #PERFORM_RELOAD = False SkeletonPart = skeletonBuilder.SkeletonPart Root = SkeletonPart.GetNamedSubclass( 'Root' ) Spine = SkeletonPart.GetNamedSubclass( 'Spine' ) Head = SkeletonPart.GetNamedSubclass( 'Head' ) Arm = SkeletonPart.GetNamedSubclass( 'Arm' ) Hand = SkeletonPart.GetNamedSubclass( 'Hand' ) Leg = SkeletonPart.GetNamedSubclass( 'Leg' ) QuadrupedFrontLeg = SkeletonPart.GetNamedSubclass( 'QuadrupedFrontLeg' ) ArbitraryChain = SkeletonPart.GetNamedSubclass( 'ArbitraryChain' ) ArbitraryParityChain = SkeletonPart.GetNamedSubclass( 'ArbitraryParityChain' ) class TestSkeletonBuilder(_BaseTest): def runTest( self ): self.testUberSkeleton() self.testUberSkeletonAndReferencing() self.testUI() def _buildTestSkeleton( self ): allPartClasses = [ part for part in SkeletonPart.GetSubclasses() if part.AVAILABLE_IN_UI ] #now remove the ones we're going to create manually for part in (Root, Spine, Head, Arm, Leg): allPartClasses.remove( part ) scale = 100 root = Root.Create( partScale=scale ) theSpine = Spine.Create( root, 5, partScale=scale ) theHead = Head.Create( theSpine.end, 2, partScale=scale ) armL = Arm.Create( theSpine.end, partScale=scale ) armR = Arm.Create( theSpine.end, partScale=scale ) legL = Leg.Create( root, partScale=scale ) legR = Leg.Create( root, partScale=scale ) armL.driveOtherPart( armR ) legL.driveOtherPart( legR ) handL = Hand.Create( armL.wrist ) handR = Hand.Create( armR.wrist ) quadSpine = ArbitraryChain.Create( root, 'quadSpine', 6, '-z' ) ArbitraryChain.Create( theHead.end, 'hair1', 3, 'x' ) ArbitraryChain.Create( theHead.end, 'hair2', 3, '-x' ) backlegA = QuadrupedFrontLeg.Create( quadSpine[-1] ) backlegB = QuadrupedFrontLeg.Create( quadSpine[-1] ) quadSpine = ArbitraryChain.Create( quadSpine[-1], 'tail', 4, '-z' ) #make sure skeleton builder can now enumerate the parts it just created partsCreated = list( SkeletonPart.IterAllParts() ) assert len( partsCreated ) == 15, "Iterating over parts just created failed!" def testUberSkeleton( self ): ''' Test that a simple scene gets setup and exports properly ''' self.new() self._buildTestSkeleton() skeletonBuilder.finalizeAllParts() rigPrimitives.buildRigForAllParts() #build the rig within the current scene @d_makeNewScene( 'testUberSkeleton_mesh' ) def testUberSkeletonAndReferencing( self ): ''' Test that a simple scene gets setup and exports properly ''' self._buildTestSkeleton() rigScene = rigPrimitives.buildRigForModel() #build the model in a referenced scene assert rigScene.exists(), "Cannot find the rig scene!" rigScene.delete() def testUI( self ): ''' Test that a simple scene gets setup and exports properly ''' self.new() self._buildTestSkeleton() #test the UI - make sure it loads and doesn't error with the built skeleton in the scene ui = skeletonBuilderUI.SkeletonBuilderUI() tabs = skeletonBuilderUI.CreateEditRigTabLayout.IterInstances().next() #walk through the tabs for n in range( len( tabs ) ): tabs.setSelectedTabIdx( n ) #end
Python
import filesystem import typeFactories from maya.cmds import * from maya import cmds as cmd from rigUtils import * from control import * from names import Parity, Name, camelCaseToNice, stripParity from skeletonBuilder import * from vectors import Vector, Matrix from mayaDecorators import d_unifyUndo from common import printInfoStr, printWarningStr, printErrorStr import apiExtensions import skeletonBuilder import spaceSwitching import triggered import poseSym import vectors import control import api __author__ = 'hamish@macaronikazoo.com' Trigger = triggered.Trigger AXES = Axis.BASE_AXES Vector = vectors.Vector AIM_AXIS = AX_X ROT_AXIS = AX_Y #make sure all setDrivenKeys have linear tangents setDrivenKeyframe = lambda *a, **kw: cmd.setDrivenKeyframe( inTangentType='linear', outTangentType='linear', *a, **kw ) def connectAttrReverse( srcAttr, destAttr, **kw ): ''' puts a reverse node in between the two given attributes ''' revNode = shadingNode( 'reverse', asUtility=True ) connectAttr( srcAttr, '%s.inputX' % revNode, **kw ) connectAttr( '%s.outputX' % revNode, destAttr, **kw ) return revNode class RigPartError(Exception): pass def isRigPartContainer( node ): if objectType( node, isType='objectSet' ): return sets( node, q=True, text=True ) == 'rigPrimitive' return False def getRigPartContainers( compatabilityMode=False ): existingContainers = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == 'rigPrimitive' ] if compatabilityMode: existingContainers += [ node.split( '.' )[0] for node in ls( '*._rigPrimitive', r=True ) ] return existingContainers def getNodesCreatedBy( function, *args, **kwargs ): ''' returns a 2-tuple containing all the nodes created by the passed function, and the return value of said function NOTE: if any container nodes were created, their contents are omitted from the resulting node list - the container itself encapsulates them ''' newNodes, ret = apiExtensions.getNodesCreatedBy( function, *args, **kwargs ) #now remove nodes from all containers from the newNodes list newContainers = apiExtensions.filterByType( newNodes, apiExtensions.MFn.kSet ) #NOTE: nodes are MObject instances at this point newNodes = set( [ node for node in newNodes if node is not None ] ) for c in newContainers: for n in sets( c, q=True ) or []: if n in newNodes: newNodes.remove( n ) #containers contained by other containers don't need to be returned (as they're already contained by a parent) newTopLevelContainers = [] for c in newContainers: parentContainer = sets( c, q=True, parentContainer=True ) if parentContainer: continue newTopLevelContainers.append( c ) newNodes.add( c ) return newNodes, ret def buildContainer( typeClass, kwDict, nodes, controls, namedNodes=() ): ''' builds a container for the given nodes, and tags it with various attributes to record interesting information such as rig primitive version, and the args used to instantiate the rig. it also registers control objects with attributes, so the control nodes can queried at a later date by their name ''' #if typeClass is an instance, then set its container attribute, otherwise instantiate an instance and return it if isinstance( typeClass, RigPart ): theInstance = typeClass typeClass = type( typeClass ) elif issubclass( typeClass, RigPart ): theInstance = typeClass( None ) #build the container, and add the special attribute to it to theContainer = sets( em=True, n='%s_%s' % (typeClass.__name__, kwDict.get( 'idx', 'NOIDX' )), text='rigPrimitive' ) theInstance.setContainer( theContainer ) addAttr( theContainer, ln='_rigPrimitive', attributeType='compound', numberOfChildren=7 ) addAttr( theContainer, ln='typeName', dt='string', parent='_rigPrimitive' ) addAttr( theContainer, ln='script', dt='string', parent='_rigPrimitive' ) addAttr( theContainer, ln='version', at='long', parent='_rigPrimitive' ) addAttr( theContainer, ln='skeletonPart', at='message', parent='_rigPrimitive' ) addAttr( theContainer, ln='buildKwargs', dt='string', parent='_rigPrimitive' ) addAttr( theContainer, ln='controls', multi=True, indexMatters=True, attributeType='message', parent='_rigPrimitive' ) addAttr( theContainer, ln='namedNodes', multi=True, indexMatters=True, attributeType='message', parent='_rigPrimitive' ) #now set the attribute values... setAttr( '%s._rigPrimitive.typeName' % theContainer, typeClass.__name__, type='string' ) setAttr( '%s._rigPrimitive.script' % theContainer, inspect.getfile( typeClass ), type='string' ) setAttr( '%s._rigPrimitive.version' % theContainer, typeClass.__version__ ) setAttr( '%s._rigPrimitive.buildKwargs' % theContainer, str( kwDict ), type='string' ) #now add all the nodes nodes = [ str( node ) if node is not None else node for node in nodes ] controls = [ str( node ) if node is not None else node for node in controls ] for node in set( nodes ) | set( controls ): if node is None: continue if objectType( node, isAType='dagNode' ): sets( node, e=True, add=theContainer ) #if the node is a rig part container add it to this container otherwise skip it elif objectType( node, isAType='objectSet' ): if isRigPartContainer( node ): sets( node, e=True, add=theContainer ) #and now hook up all the controls controlNames = typeClass.CONTROL_NAMES or [] #CONTROL_NAMES can validly be None, so in this case just call it an empty list for idx, control in enumerate( controls ): if control is None: continue connectAttr( '%s.message' % control, '%s._rigPrimitive.controls[%d]' % (theContainer, idx), f=True ) #set the kill state on the control if its a transform node if objectType( control, isAType='transform' ): triggered.setKillState( control, True ) #hook up all the named nodes for idx, node in enumerate( namedNodes ): if node is None: continue connectAttr( '%s.message' % node, '%s._rigPrimitive.namedNodes[%d]' % (theContainer, idx), f=True ) return theInstance class RigPart(typeFactories.trackableClassFactory()): ''' base rig part class. deals with rig part creation. rig parts are instantiated by passing the class a rig part container node to create a new rig part, simply call the RigPartClass.Create( skeletonPart, *args ) where the skeletonPart is the SkeletonPart instance created via the skeleton builder ''' __version__ = 0 PRIORITY = 0 CONTROL_NAMES = None NAMED_NODE_NAMES = None AVAILABLE_IN_UI = False #determines whether this part should appear in the UI or not... ADD_CONTROLS_TO_QSS = True AUTO_PICKER = True #if you want to customize the name as it appears in the UI, set this to the desired string DISPLAY_NAME = None def __new__( cls, partContainer, skeletonPart=None ): if cls is RigPart: clsName = getAttr( '%s._rigPrimitive.typeName' % partContainer ) cls = cls.GetNamedSubclass( clsName ) if cls is None: raise TypeError( "Cannot determine the part class for the given part container!" ) return object.__new__( cls, partContainer, skeletonPart ) def __init__( self, partContainer, skeletonPart=None ): if partContainer is not None: assert isRigPartContainer( partContainer ), "Must pass a valid rig part container! (received %s - a %s)" % (partContainer, nodeType( partContainer )) self._container = partContainer self._skeletonPart = skeletonPart self._worldPart = None self._worldControl = None self._partsNode = None self._qss = None self._idx = None if partContainer: if skeletonPart is None: try: self.getSkeletonPart() #this isn't fatal, although its not good except RigPartError, x: printWarningStr( str( x ) ) def __unicode__( self ): return u"%s_%d( %r )" % (self.__class__.__name__, self.getIdx(), self._container) __str__ = __unicode__ def __repr__( self ): return repr( unicode( self ) ) def __hash__( self ): ''' the hash for the container mobject uniquely identifies this rig control ''' return hash( apiExtensions.asMObject( self._container ) ) def __eq__( self, other ): return self._container == other.getContainer() def __neq__( self, other ): return not self == other def __getitem__( self, idx ): ''' returns the control at <idx> ''' connected = listConnections( '%s._rigPrimitive.controls[%d]' % (self._container, idx), d=False ) if connected: assert len( connected ) == 1, "More than one control was found!!!" return connected[ 0 ] return None def __len__( self ): ''' returns the number of controls registered on the rig ''' return getAttr( '%s._rigPrimitive.controls' % self._container, size=True ) def __iter__( self ): ''' iterates over all controls in the rig ''' for n in range( len( self ) ): yield self[ n ] def getContainer( self ): return self._container def setContainer( self, container ): self._container = container def getNodes( self ): ''' returns ALL the nodes that make up this rig part ''' return sets( self._container, q=True ) nodes = getNodes def isReferenced( self ): return referenceQuery( self._container, inr=True ) @classmethod def GetPartName( cls ): ''' can be used to get a "nice" name for the part class ''' if cls.DISPLAY_NAME is None: return camelCaseToNice( cls.__name__ ) return cls.DISPLAY_NAME @classmethod def InitFromItem( cls, item ): ''' inits the rigPart from a member item - the RigPart instance returned is cast to teh most appropriate type ''' if isRigPartContainer( item ): typeClassStr = getAttr( '%s._rigPrimitive.typeName' % partContainer ) typeClass = RigPart.GetNamedSubclass( typeClassStr ) return typeClass( item ) cons = listConnections( item, s=False, type='objectSet' ) if not cons: raise RigPartError( "Cannot find a rig container for %s" % item ) for con in cons: if isRigPartContainer( con ): typeClassStr = getAttr( '%s._rigPrimitive.typeName' % con ) typeClass = RigPart.GetNamedSubclass( typeClassStr ) return typeClass( con ) raise RigPartError( "Cannot find a rig container for %s" % item ) @classmethod def IterAllParts( cls, skipSubParts=True ): ''' iterates over all RigParts in the current scene NOTE: if skipSubParts is True will skip over parts that inherit from RigSubPart - these are assumed to be contained by another part ''' for c in getRigPartContainers(): if objExists( '%s._rigPrimitive' % c ): thisClsName = getAttr( '%s._rigPrimitive.typeName' % c ) thisCls = RigPart.GetNamedSubclass( thisClsName ) if thisCls is None: raise SkeletonError( "No RigPart called %s" % thisClsName ) if skipSubParts and issubclass( thisCls, RigSubPart ): continue if issubclass( thisCls, cls ): yield cls( c ) @classmethod def IterAllPartsInOrder( cls, skipSubParts=False ): for skeletonPart in SkeletonPart.IterAllPartsInOrder(): rigPart = skeletonPart.getRigPart() if rigPart is None: continue if skipSubParts and isinstance( rigPart, RigSubPart ): continue yield rigPart @classmethod def GetUniqueIdx( cls ): ''' returns a unique index (unique against the universe of existing indices in the scene) for the current part class ''' existingIdxs = [] for part in cls.IterAllParts(): idx = part.getBuildKwargs()[ 'idx' ] existingIdxs.append( idx ) existingIdxs.sort() assert len( existingIdxs ) == len( set( existingIdxs ) ), "There is a duplicate ID! %s, %s" % (cls, existingIdxs) #return the first, lowest, available index for orderedIdx, existingIdx in enumerate( existingIdxs ): if existingIdx != orderedIdx: return orderedIdx if existingIdxs: return existingIdxs[ -1 ] + 1 return 0 def createSharedShape( self, name ): return asMObject( createNode( 'nurbsCurve', n=name +'#', p=self.sharedShapeParent ) ) @classmethod def Create( cls, skeletonPart, *a, **kw ): ''' you can pass in the following kwargs to control the build process addControlsToQss defaults to cls.ADD_CONTROLS_TO_QSS ''' #check to see if the given skeleton part can actually be rigged by this method if not cls.CanRigThisPart( skeletonPart ): return addControlsToQss = kw.get( 'addControlsToQss', cls.ADD_CONTROLS_TO_QSS ) buildFunc = getattr( cls, '_build', None ) if buildFunc is None: raise RigPartError( "The rigPart %s has no _build method!" % cls.__name__ ) assert isinstance( skeletonPart, SkeletonPart ), "Need a SkeletonPart instance, got a %s instead" % skeletonPart.__class__ if not skeletonPart.compareAgainstHash(): raise NotFinalizedError( "ERROR :: %s hasn't been finalized!" % skeletonPart ) #now turn the args passed in are a single kwargs dict argNames, vArgs, vKwargs, defaults = inspect.getargspec( buildFunc ) if defaults is None: defaults = [] argNames = argNames[ 2: ] #strip the first two args - which should be the instance arg (usually self) and the skeletonPart if vArgs is not None: raise RigPartError( 'cannot have *a in rig build functions' ) for argName, value in zip( argNames, a ): kw[ argName ] = value #now explicitly add the defaults for argName, default in zip( argNames, defaults ): kw.setdefault( argName, default ) #generate an index for the rig part - each part must have a unique index idx = cls.GetUniqueIdx() kw[ 'idx' ] = idx #construct an empty instance - empty RigPart instances are only valid inside this method... self = cls( None ) self._skeletonPart = skeletonPart self._idx = idx #generate a default scale for the rig part kw.setdefault( 'scale', getScaleFromSkeleton() / 10.0 ) self.scale = kw[ 'scale' ] #make sure the world part is created first - if its created by the part, then its nodes will be included in its container... self.getWorldPart() #create the shared shape transform - this is the transform under which all shared shapes are temporarily parented to, and all #shapes under this transform are automatically added to all controls returned after the build function returns self.sharedShapeParent = asMObject( createNode( 'transform', n='_tmp_sharedShape' ) ) defaultSharedShape = self.createSharedShape( '%s_sharedAttrs' % cls.GetPartName() ) kw[ 'sharedShape' ] = defaultSharedShape #run the build function newNodes, (controls, namedNodes) = getNodesCreatedBy( self._build, skeletonPart, **kw ) realControls = [ c for c in controls if c is not None ] #its possible for a build function to return None in the control list because it wants to preserve the length of the control list returned - so construct a list of controls that actually exist realNamedNodes = [ c for c in namedNodes if c is not None ] if addControlsToQss: for c in realControls: sets( c, add=self._qss ) #check to see if there is a layer for the rig controls and add controls to it if controls: if objExists( 'rig_controls' ) and nodeType( 'rig_controls' ) == 'displayLayer': rigLayer = 'rig_controls' else: rigLayer = createDisplayLayer( name='rig_controls', empty=True ) editDisplayLayerMembers( rigLayer, controls, noRecurse=True ) #make sure there are no intermediate shapes for c in realControls: for shape in listRelatives( c, s=True, pa=True ) or []: if getAttr( '%s.intermediateObject' % shape ): delete( shape ) #build the container and initialize the rigPrimtive buildContainer( self, kw, newNodes, controls, namedNodes ) #add shared shapes to all controls, and remove shared shapes that are empty sharedShapeParent = self.sharedShapeParent sharedShapes = listRelatives( sharedShapeParent, pa=True, s=True ) or [] for c in realControls: if objectType( c, isAType='transform' ): for shape in sharedShapes: parent( shape, c, add=True, s=True ) for shape in sharedShapes: if not listAttr( shape, ud=True ): delete( shape ) delete( sharedShapeParent ) del( self.sharedShapeParent ) #stuff the part container into the world container - we want a clean top level in the outliner theContainer = self._container sets( theContainer, e=True, add=self._worldPart.getContainer() ) #make sure the container "knows" the skeleton part - its not always obvious trawling through #the nodes in teh container which items are the skeleton part connectAttr( '%s.message' % skeletonPart.getContainer(), '%s._rigPrimitive.skeletonPart' % theContainer ) return self @classmethod def GetControlName( cls, control ): ''' returns the name of the control as defined in the CONTROL_NAMES attribute for the part class ''' cons = listConnections( control.message, s=False, p=True, type='objectSet' ) for c in cons: typeClassStr = getAttr( '%s._rigPrimitive.typeName' % c.node() ) typeClass = RigPart.GetNamedSubclass( typeClassStr ) if typeClass.CONTROL_NAMES is None: return str( control ) idx = c[ c.rfind( '[' )+1:-1 ] try: name = typeClass.CONTROL_NAMES[ idx ] except ValueError: printErrorStr( 'type: %s control: %s' % (typeClass, control) ) raise RigPartError( "Doesn't have a name!" ) return name raise RigPartError( "The control isn't associated with a rig primitive" ) @classmethod def CanRigThisPart( cls, skeletonPart ): return True @classmethod def GetDefaultBuildKwargList( cls ): ''' returns a list of 2 tuples: argName, defaultValue ''' buildFunc = getattr( cls, '_build', None ) spec = inspect.getargspec( buildFunc ) argNames = spec[ 0 ][ 2: ] #strip the first two items because the _build method is a bound method - so the first item is always the class arg (usually called cls), and the second arg is always the skeletonPart defaults = spec[ 3 ] if defaults is None: defaults = [] assert len( argNames ) == len( defaults ), "%s has no default value set for one of its args - this is not allowed" % cls kwargList = [] for argName, default in zip( argNames, defaults ): kwargList.append( (argName, default) ) return kwargList def isPartContained( self ): ''' returns whether this rig part is "contained" by another rig part. Ie if a rig part was build from within another rig part, then it is contained. Examples of this are things like the arm rig which builds upon the ikfk sub primitive rig - the sub-primitive is contained within the arm rig ''' cons = listConnections( '%s.message' % self._container, s=False, type='objectSet' ) if cons: for con in cons: if isRigPartContainer( con ): rigPart = RigPart( con ) if isinstance( rigPart, WorldPart ): continue return True return False def getBuildKwargs( self ): theDict = eval( getAttr( '%s._rigPrimitive.buildKwargs' % self._container ) ) return theDict def getIdx( self ): ''' returns the index of the part - all parts have a unique index associated with them ''' if self._idx is None: if self._container is None: raise RigPartError( 'No index has been defined yet!' ) else: buildKwargs = self.getBuildKwargs() self._idx = buildKwargs[ 'idx' ] return self._idx def getParity( self ): return self.getSkeletonPart().getParity() def getSuffix( self ): return self.getParity().asName() def getParityColour( self ): return ColourDesc( 'green 0.7' ) if self.getParity() == Parity.LEFT else ColourDesc( 'red 0.7' ) def getBuildScale( self ): return self.getBuildKwargs().get( 'scale', self.PART_SCALE ) def getWorldPart( self ): if self._worldPart is None: self._worldPart = worldPart = WorldPart.Create() self._worldControl = worldPart.getControl( 'control' ) self._partsNode = worldPart.getNamedNode( 'parts' ) self._qss = worldPart.getNamedNode( 'qss' ) return self._worldPart def getWorldControl( self ): if self._worldControl is None: self.getWorldPart() return self._worldControl def getPartsNode( self ): if self._partsNode is None: self.getWorldPart() return self._partsNode def getQssSet( self ): if self._qss is None: self.getWorldPart() return self._qss def getSkeletonPart( self ): ''' returns the skeleton part this rig part is driving ''' #have we cached the skeleton part already? if so, early out! if self._skeletonPart: return self._skeletonPart if self._container is None: return None connected = listConnections( '%s.skeletonPart' % self._container ) if connected is None: raise RigPartError( "There is no skeleton part associated with this rig part! This can happen for a variety of reasons such as name changes on the skeleton in the model file (if you're using referencing), or a incomplete conversion from the old rig format..." ) if nodeType( connected[0] ) == 'reference': raise RigPartError( "A reference node is connected to the skeletonPart attribute - this could mean the model reference isn't loaded, or a node name from the referenced file has changed - either way I can't determine the skeleton part used by this rig!" ) #cache the value so we can quickly return it on consequent calls self._skeletonPart = skeletonPart = SkeletonPart.InitFromItem( connected[0] ) return skeletonPart def getSkeletonPartParity( self ): return self.getSkeletonPart().getParity() def getControl( self, attrName ): ''' returns the control named <attrName>. control "names" are defined by the CONTROL_NAMES class variable. This list is asked for the index of <attrName> and the control at that index is returned ''' if self.CONTROL_NAMES is None: raise AttributeError( "The %s rig primitive has no named controls" % self.__class__.__name__ ) idx = list( self.CONTROL_NAMES ).index( attrName ) if idx < 0: raise AttributeError( "No control with the name %s" % attrName ) connected = listConnections( '%s._rigPrimitive.controls[%d]' % (self._container, idx), d=False ) if connected: assert len( connected ) == 1, "More than one control was found!!!" return connected[ 0 ] return None def getControlIdx( self, control ): ''' returns the index of the given control - each control is plugged into a given "slot" ''' cons = cmd.listConnections( '%s.message' % control, s=False, p=True ) or [] for c in cons: node = c.split( '.' )[0] if not isRigPartContainer( node ): continue if objExists( node ): if node != self._container: continue idx = int( c[ c.rfind( '[' )+1:-1 ] ) return idx raise RigPartError( "The control %s isn't associated with this rig primitive %s" % (control, self) ) def getControlName( self, control ): ''' returns the name of the control as defined in the CONTROL_NAMES attribute for the part class ''' if self.CONTROL_NAMES is None: return str( control ) controlIdx = self.getControlIdx( control ) try: return self.CONTROL_NAMES[ controlIdx ] except IndexError: return None raise RigPartError( "The control %s isn't associated with this rig primitive %s" % (control, self) ) def getNamedNode( self, nodeName ): ''' returns the "named node" called <nodeName>. Node "names" are defined by the NAMED_NODE_NAMES class variable. This list is asked for the index of <nodeName> and the node at that index is returned ''' if self.NAMED_NODE_NAMES is None: raise AttributeError( "The %s rig primitive has no named nodes" % self.__class__.__name__ ) idx = list( self.NAMED_NODE_NAMES ).index( nodeName ) if idx < 0: raise AttributeError( "No node with the name %s" % nodeName ) connected = listConnections( '%s._rigPrimitive.namedNodes[%d]' % (self._container, idx), d=False ) if connected: assert len( connected ) == 1, "More than one node was found!!!" return connected[ 0 ] return None def delete( self ): nodes = sets( self._container, q=True ) for node in nodes: cleanDelete( node ) if objExists( self._container ): delete( self._container ) #if the skeleton part is referenced, clean all reference edits off skeleton part joints skeletonPart = self.getSkeletonPart() if skeletonPart.isReferenced(): skeletonPartJoints = skeletonPart.items #now unload the reference partReferenceFile = Path( referenceQuery( skeletonPart.getContainer(), filename=True ) ) file( partReferenceFile, unloadReference=True ) #remove edits from each joint in the skeleton part for j in skeletonPartJoints: referenceEdit( j, removeEdits=True, successfulEdits=True, failedEdits=True ) #reload the referenced file file( partReferenceFile, loadReference=True ) ### POSE MIRRORING/SWAPPING ### def getOppositePart( self ): ''' Finds the skeleton part opposite to the one this rig part controls, and returns its rig part. If no rig part can be found, or if no ''' thisSkeletonPart = self.getSkeletonPart() oppositeSkeletonPart = thisSkeletonPart.getOppositePart() if oppositeSkeletonPart is None: return None return oppositeSkeletonPart.getRigPart() def getOppositeControl( self, control ): ''' Finds the control that is most likely to be opposite the one given. It first gets the name of the given control. It then finds the opposite rig part, and then queries it for the control with the determined name ''' controlIdx = self.getControlIdx( control ) oppositePart = self.getOppositePart() if oppositePart: return oppositePart[ controlIdx ] return None def setupMirroring( self ): for control in self: if control is None: continue oppositeControl = self.getOppositeControl( control ) pair = poseSym.ControlPair.Create( control, oppositeControl ) printInfoStr( 'setting up mirroring on %s %s' % (control, oppositeControl) ) def getFilePartDict(): ''' returns a dictionary keyed by scene name containing a list of the parts contained in that scene ''' scenePartDict = {} #special case! we want to skip parts that are of this exact type - in older rigs this class was a RigSubPart, not a super class for the biped limb classes IkFkBaseCls = RigPart.GetNamedSubclass( 'IkFkBase' ) for rigPart in RigPart.IterAllParts(): if IkFkBaseCls: if type( rigPart ) is IkFkBaseCls: continue isReferenced = rigPart.isReferenced() if isReferenced: rigScene = Path( referenceQuery( rigPart.getContainer(), filename=True ) ) else: rigScene = Path( file( q=True, sn=True ) ) scenePartDict.setdefault( rigScene, [] ) partList = scenePartDict[ rigScene ] partList.append( rigPart ) return scenePartDict def generateNiceControlName( control ): niceName = getNiceName( control ) if niceName is not None: return niceName try: rigPart = RigPart.InitFromItem( control ) if rigPart is None: raise RigPartError( "null" ) controlName = rigPart.getControlName( control ) except RigPartError: controlName = str( control ) controlName = Name( controlName ) parity = controlName.get_parity() if parity == Parity.LEFT: controlName = 'Left '+ str( stripParity( controlName ) ) if parity == Parity.RIGHT: controlName = 'Right '+ str( stripParity( controlName ) ) else: controlName = str( controlName ) return camelCaseToNice( controlName ) def getSpaceSwitchControls( theJoint ): ''' walks up the joint chain and returns a list of controls that drive parent joints ''' parentControls = [] for p in api.iterParents( theJoint ): theControl = getItemRigControl( p ) if theControl is not None: parentControls.append( theControl ) return parentControls def buildDefaultSpaceSwitching( theJoint, control=None, additionalParents=(), additionalParentNames=(), reverseHierarchy=False, **buildKwargs ): if control is None: control = getItemRigControl( theJoint ) theWorld = WorldPart.Create() spaces = getSpaceSwitchControls( theJoint ) spaces.append( theWorld.getControl( 'control' ) ) #determine default names for the given controls names = [] for s in spaces: names.append( generateNiceControlName( s ) ) additionalParents = list( additionalParents ) additionalParentNames = list( additionalParentNames ) for n in range( len( additionalParentNames ), len( additionalParents ) ): additionalParentNames.append( generateNiceControlName( additionalParents[ n ] ) ) spaces += additionalParents names += additionalParentNames #we don't care about space switching if there aren't any non world spaces... if not spaces: return if reverseHierarchy: spaces.reverse() names.reverse() return spaceSwitching.build( control, spaces, names, **buildKwargs ) def getParentAndRootControl( theJoint ): ''' returns a 2 tuple containing the nearest control up the hierarchy, and the most likely control to use as the "root" control for the rig. either of these may be the world control, but both values are guaranteed to be an existing control object ''' parentControl, rootControl = None, None for p in api.iterParents( theJoint ): theControl = getItemRigControl( p ) if theControl is None: continue if parentControl is None: parentControl = theControl skelPart = SkeletonPart.InitFromItem( p ) if isinstance( skelPart, skeletonBuilder.Root ): rootControl = theControl if parentControl is None or rootControl is None: world = WorldPart.Create() if parentControl is None: parentControl = world.getControl( 'control' ) if rootControl is None: rootControl = world.getControl( 'control' ) return parentControl, rootControl def createLineOfActionMenu( controls, joints ): ''' deals with adding a "draw line of action" menu to each control in the controls list. the line is drawn through the list of joints passed ''' if not joints: return if not isinstance( controls, (list, tuple) ): controls = [ controls ] joints = list( joints ) jParent = getNodeParent( joints[ 0 ] ) if jParent: joints.insert( 0, jParent ) for c in controls: cTrigger = Trigger( c ) spineConnects = [ cTrigger.connect( j ) for j in joints ] Trigger.CreateMenu( c, "draw line of action", "zooLineOfAction;\nzooLineOfAction_multi { %s } \"\";" % ', '.join( '"%%%d"'%idx for idx in spineConnects ) ) class RigSubPart(RigPart): ''' ''' #this attribute describes what skeleton parts the rig primitive is associated with. If the attribute's value is None, then the rig primitive #is considered a "hidden" primitive that has SKELETON_PRIM_ASSOC = None class PrimaryRigPart(RigPart): ''' all subclasses of this class are exposed as available rigging methods to the user ''' AVAILABLE_IN_UI = True class WorldPart(RigPart): ''' the world part can only be created once per scene. if an existing world part instance is found when calling WorldPart.Create() it will be returned instead of creating a new instance ''' __version__ = 0 CONTROL_NAMES = 'control', 'exportRelative' NAMED_NODE_NAMES = 'parts', 'masterQss', 'qss' WORLD_OBJ_MENUS = [ ('toggle rig vis', """{\nstring $childs[] = `listRelatives -pa -type transform #`;\nint $vis = !`getAttr ( $childs[0]+\".v\" )`;\nfor($a in $childs) if( `objExists ( $a+\".v\" )`) if( `getAttr -se ( $a+\".v\" )`) setAttr ( $a+\".v\" ) $vis;\n}"""), ('draw all lines of action', """string $menuObjs[] = `zooGetObjsWithMenus`;\nfor( $m in $menuObjs ) {\n\tint $cmds[] = `zooObjMenuListCmds $m`;\n\tfor( $c in $cmds ) {\n\t\tstring $name = `zooGetObjMenuCmdName $m $c`;\n\t\tif( `match \"draw line of action\" $name` != \"\" ) eval(`zooPopulateCmdStr $m (zooGetObjMenuCmdStr($m,$c)) {}`);\n\t\t}\n\t}"""), ('show "export relative" node', """""") ] @classmethod @d_unifyUndo def Create( cls, **kw ): for existingWorld in cls.IterAllParts(): return existingWorld #try to determine scale - walk through all existing skeleton parts in the scene for skeletonPart in SkeletonPart.IterAllPartsInOrder(): kw.setdefault( 'scale', skeletonPart.getBuildScale() ) break worldNodes, (controls, namedNodes) = getNodesCreatedBy( cls._build, **kw ) worldPart = buildContainer( WorldPart, { 'idx': 0 }, worldNodes, controls, namedNodes ) #check to see if there is a layer for the rig controls and add controls to it if objExists( 'rig_controls' ) and nodeType( 'rig_controls' ) == 'displayLayer': rigLayer = 'rig_controls' else: rigLayer = createDisplayLayer( name='rig_controls', empty=True ) editDisplayLayerMembers( rigLayer, controls, noRecurse=True ) return worldPart @classmethod def _build( cls, **kw ): scale = kw.get( 'scale', skeletonBuilder.TYPICAL_HEIGHT ) scale /= 1.5 world = buildControl( 'main', shapeDesc=ShapeDesc( None, 'hex', AX_Y ), oriented=False, scale=scale, niceName='The World' ) parts = group( empty=True, name='parts_grp' ) qss = sets( empty=True, text="gCharacterSet", n="body_ctrls" ) masterQss = sets( empty=True, text="gCharacterSet", n="all_ctrls" ) exportRelative = buildControl( 'exportRelative', shapeDesc=ShapeDesc( None, 'cube', AX_Y_NEG ), pivotModeDesc=PivotModeDesc.BASE, oriented=False, size=(1, 0.5, 1), scale=scale ) parentConstraint( world, exportRelative ) attrState( exportRelative, ('t', 'r', 's'), *LOCK_HIDE ) attrState( exportRelative, 'v', *HIDE ) setAttr( '%s.v' % exportRelative, False ) #turn scale segment compensation off for all joints in the scene for j in ls( type='joint' ): setAttr( '%s.ssc' % j, False ) sets( qss, add=masterQss ) attrState( world, 's', *NORMAL ) connectAttr( '%s.scale' % world, '%s.scale' % parts ) connectAttr( '%s.scaleX' % world, '%s.scaleY' % world ) connectAttr( '%s.scaleX' % world, '%s.scaleZ' % world ) #add right click items to the world controller menu worldTrigger = Trigger( str( world ) ) qssIdx = worldTrigger.connect( str( masterQss ) ) #add world control to master qss sets( world, add=masterQss ) sets( exportRelative, add=masterQss ) #turn unwanted transforms off, so that they are locked, and no longer keyable attrState( world, 's', *NO_KEY ) attrState( world, ('sy', 'sz'), *LOCK_HIDE ) attrState( parts, [ 't', 'r', 's', 'v' ], *LOCK_HIDE ) controls = world, exportRelative namedNodes = parts, masterQss, qss return controls, namedNodes def getSkeletonPart( self ): #the world part has no skeleton part... return None def setupMirroring( self ): pair = poseSym.ControlPair.Create( self.getControl( 'control' ) ) pair.setFlips( 0 ) ### <CHEEKY!> ### ''' these functions get added to the SkeletonPart class as a way of implementing functionality that relies on the RigPart class - which isn't available in the baseSkeletonPart script (otherwise you'd have a circular import dependency) ''' def _getRigContainer( self ): ''' returns the container for the rig part - if this part is rigged. None is returned otherwise NOTE: the container is returned instead of the rig instance because this script can't import the RigPart base class without causing circular import statements - there is a getRigPart method that is implemented in the baseRigPrimitive script that gets added to this class ''' rigContainerAttrpath = '%s.rigContainer' % self.getContainer() if objExists( rigContainerAttrpath ): cons = listConnections( rigContainerAttrpath, d=False ) if cons: return cons[0] cons = listConnections( '%s.message' % self.getContainer(), s=False, type='objectSet' ) if cons: connectedRigParts = [] for con in cons: if isRigPartContainer( con ): connectedRigParts.append( RigPart( con ) ) #now we have a list of connected rig parts - lets figure out which ones are "top level" parts - ie don't belong to another part if connectedRigParts: for rigPart in connectedRigParts: if not rigPart.isPartContained(): return rigPart return None def _getRigPart( self ): rigContainer = self.getRigContainer() if rigContainer: return RigPart( self.getRigContainer() ) return None SkeletonPart.getRigContainer = _getRigContainer SkeletonPart.getRigPart = _getRigPart def _deleteRig( self ): rigPart = self.getRigPart() rigPart.delete() SkeletonPart.deleteRig = d_unifyUndo( _deleteRig ) ### </CHEEKY!> ### @d_unifyUndo def setupMirroring(): ''' sets up all controls in the scene for mirroring ''' for rigPart in RigPart.IterAllParts(): rigPart.setupMirroring() @d_unifyUndo @api.d_showWaitCursor def buildRigForModel( scene=None, referenceModel=True, deletePlacers=False ): ''' given a model scene whose skeleton is assumed to have been built by the skeletonBuilder tool, this function will create a rig scene by referencing in said model, creating the rig as best it knows how, saving the scene in the appropriate spot etc... ''' #if no scene was passed, assume we're acting on the current scene if scene is None: scene = filesystem.Path( cmd.file( q=True, sn=True ) ) #if the scene WAS passed in, open the desired scene if it isn't already open else: scene = filesystem.Path( scene ) curScene = filesystem.Path( cmd.file( q=True, sn=True ) ) if curScene: if scene != curScene: mel.saveChanges( 'file -f -open "%s"' % scene ) else: cmd.file( scene, f=True, open=True ) #if the scene is still none bail... if not scene and referenceModel: raise SceneNotSavedError( "Uh oh, your scene hasn't been saved - Please save it somewhere on disk so I know where to put the rig. Thanks!" ) #backup the current state of the scene, just in case something goes south... if scene.exists(): backupFilename = scene.up() / ('%s_backup.%s' % (scene.name(), scene.getExtension())) if backupFilename.exists(): backupFilename.delete() cmd.file( rename=backupFilename ) cmd.file( save=True, force=True ) cmd.file( rename=scene ) #finalize failedParts = finalizeAllParts() if failedParts: confirmDialog( t='Finalization Failure', m='The following parts failed to finalize properly:\n\n%s' % '\n'.join( map( str, failedParts ) ), b='OK', db='OK' ) return #delete placers if desired - NOTE: this should be done after after finalization because placers are often used to define alignment for end joints if deletePlacers: for part in SkeletonPart.IterAllParts(): placers = part.getPlacers() if placers: delete( placers ) #if desired, create a new scene and reference in the model if referenceModel: #remove any unknown nodes in the scene - these cause maya to barf when trying to save unknownNodes = ls( type='unknown' ) if unknownNodes: delete( unknownNodes ) #scene.editoradd() cmd.file( f=True, save=True ) cmd.file( f=True, new=True ) api.referenceFile( scene, 'model' ) #rename the scene to the rig rigSceneName = '%s_rig.ma' % scene.name() rigScene = scene.up() / rigSceneName cmd.file( rename=rigScene ) cmd.file( f=True, save=True, typ='mayaAscii' ) else: rigScene = scene buildRigForAllParts() setupMirroring() return rigScene @d_unifyUndo def buildRigForAllParts(): for part in SkeletonPart.IterAllPartsInOrder(): part.rig() #create a layer for the skeleton for rootPart in Root.IterAllParts(): pass @d_unifyUndo def cleanMeshControls( doConfirm=True ): shapesRemoved = 0 for node in getRigPartContainers( True ): clsName = getAttr( '%s._rigPrimitive.typeName' % node ) cls = RigPart.GetNamedSubclass( clsName ) if cls is None: continue rigPart = cls( node ) for c in rigPart: for shape in listRelatives( c, s=True, pa=True ) or []: if getAttr( '%s.intermediateObject' % shape ): delete( shape ) shapesRemoved += 1 printInfoStr( "Clean up %d bogus shapes" % shapesRemoved ) if doConfirm: cmd.confirmDialog( t='Done!', m="I'm done polishing your rig!\n%d shapes removed." % shapesRemoved, b='OK', db='OK' ) #end
Python
from __future__ import with_statement import os import re import sys import time import marshal import datetime import subprocess import tempfile import path from path import * from misc import iterBy ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ### IMPORTANT: perforce is disabled by default - to enable call enablePerforce() ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def getDefaultWorkingDir(): ''' perforce can be setup to use p4config files - if a user has done this, then setting the working directory properly becomes critically important. This function gets called before spawning the p4 processes to set the working directory. Implement the appropriate logic here for your particular environment ''' return None class FinishedP4Operation(Exception): pass class TimedOutP4Operation(Exception): pass class P4Exception(Exception): pass def _p4fast( *args ): p = subprocess.Popen( 'p4 -G '+ ' '.join( args ), cwd=getDefaultWorkingDir(), shell=True, stdout=subprocess.PIPE ) results = [] try: while True: results.append( marshal.loads( p.stdout.read() ) ) except EOFError: pass p.wait() return results class P4Output(dict): EXIT_PREFIX = 'exit:' ERROR_PREFIX = 'error:' # START_DIGITS = re.compile( '(^[0-9]+)(.*)' ) END_DIGITS = re.compile( '(.*)([0-9]+$)' ) def __init__( self, outStr, keysColonDelimited=False ): EXIT_PREFIX = self.EXIT_PREFIX ERROR_PREFIX = self.ERROR_PREFIX self.errors = [] if isinstance( outStr, basestring ): lines = outStr.split( '\n' ) elif isinstance( outStr, (list, tuple) ): lines = outStr else: print outStr raise P4Exception( "unsupported type (%s) given to %s" % (type( outStr ), self.__class__.__name__) ) delimiter = (' ', ':')[ keysColonDelimited ] for line in lines: line = line.strip() if not line: continue if line.startswith( EXIT_PREFIX ): break elif line.startswith( ERROR_PREFIX ): self.errors.append( line ) continue idx = line.find( delimiter ) if idx == -1: prefix = line data = True else: prefix = line[ :idx ].strip() data = line[ idx + 1: ].strip() if data.isdigit(): data = int( data ) if keysColonDelimited: prefix = ''.join( [ (s, s.capitalize())[ n ] for n, s in enumerate( prefix.lower().split() ) ] ) else: prefix = prefix[ 0 ].lower() + prefix[ 1: ] self[ prefix ] = data #finally, if there are prefixes which have a numeral at the end, strip it and pack the data into a list multiKeys = {} for k in self.keys(): m = self.END_DIGITS.search( k ) if m is None: continue prefix, idx = m.groups() idx = int( idx ) data = self.pop( k ) try: multiKeys[ prefix ].append( (idx, data) ) except KeyError: multiKeys[ prefix ] = [ (idx, data) ] for prefix, dataList in multiKeys.iteritems(): try: self.pop( prefix ) except KeyError: pass dataList.sort() self[ prefix ] = [ d[ 1 ] for d in dataList ] def __unicode__( self ): return self.__str__() def __getattr__( self, attr ): return self[ attr ] def asStr( self ): if self.errors: return '\n'.join( self.errors ) return '\n'.join( '%s: %s' % items for items in self.iteritems() ) INFO_PREFIX_RE = re.compile( '^info([0-9]*): ' ) def _p4run( *args ): if not isPerforceEnabled(): return False global INFO_PREFIX_RE if '-s' not in args: #if the -s flag is in the global flags, perforce sends all data to the stdout, and prefixes all errors with "error:" args = ('-s',) + args cmdStr = 'p4 '+ ' '.join( map( str, args ) ) with tempfile.TemporaryFile() as tmpFile: try: p4Proc = subprocess.Popen( cmdStr, cwd=getDefaultWorkingDir(), shell=True, stdout=tmpFile.fileno() ) except OSError: P4File.USE_P4 = False return False p4Proc.wait() tmpFile.seek( 0 ) return [ INFO_PREFIX_RE.sub( '', line ) for line in tmpFile.readlines() ] def p4run( *args, **kwargs ): ret = _p4run( *args ) if ret is False: return False return P4Output( ret, **kwargs ) P4INFO = None def p4Info(): global P4INFO if P4INFO: return P4INFO P4INFO = p4run( 'info', keysColonDelimited=True ) if not P4INFO: disablePerforce() return P4INFO def populateChange( change ): changeNum = change[ 'change' ] if isinstance( changeNum, int ) and changeNum: fullChange = P4Change.FetchByNumber( changeNum ) for key, value in fullChange.iteritems(): change[ key ] = value class P4Change(dict): def __init__( self ): self[ 'user' ] = '' self[ 'change' ] = None self[ 'description' ] = '' self[ 'files' ] = [] self[ 'actions' ] = [] self[ 'revisions' ] = [] def __setattr__( self, attr, value ): if isinstance( value, basestring ): if value.isdigit(): value = int( value ) self[ attr ] = value def __getattr__( self, attr ): ''' if the value of an attribute is the populateChanges function (in the root namespace), then the full changelist data is queried. This is useful for commands like the p4 changes command (wrapped by the FetchChanges class method) which lists partial changelist data. The method returns P4Change objects with partial data, and when more detailed data is required, a full query can be made. This ensures minimal server interaction. ''' value = self[ attr ] if value is populateChange: populateChange( self ) value = self[ attr ] return value def __str__( self ): return str( self.change ) def __int__( self ): return self[ 'change' ] __hash__ = __int__ def __lt__( self, other ): return self.change < other.change def __le__( self, other ): return self.change <= other.change def __eq__( self, other ): return self.change == other.change def __ne__( self, other ): return self.change != other.change def __gt__( self, other ): return self.change > other.change def __ge__( self, other ): return self.change >= other.change def __len__( self ): return len( self.files ) def __eq__( self, other ): if isinstance( other, int ): return self.change == other elif isinstance( other, basestring ): if other == 'default': return self.change == 0 return self.change == other.change def __iter__( self ): return zip( self.files, self.revisions, self.actions ) @classmethod def Create( cls, description, files=None ): #clean the description line description = '\n\t'.join( [ line.strip() for line in description.split( '\n' ) ] ) info = p4Info() contents = '''Change:\tnew\n\nClient:\t%s\n\nUser:\t%s\n\nStatus:\tnew\n\nDescription:\n\t%s\n''' % (info.clientName, info.userName, description) global INFO_PREFIX_RE p4Proc = subprocess.Popen( 'p4 -s change -i', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = p4Proc.communicate( contents ) p4Proc.wait() stdout = [ INFO_PREFIX_RE.sub( '', line ) for line in stdout.split( '\n' ) ] output = P4Output( stdout ) changeNum = int( P4Output.START_DIGITS.match( output.change ).groups()[ 0 ] ) new = cls() new.description = description new.change = changeNum if files is not None: p4run( 'reopen -c', changeNum, *files ) return new @classmethod def FetchByNumber( cls, number ): lines = _p4run( 'describe', number ) if not lines: return None change = cls() change.change = number toks = lines[ 0 ].split() if 'by' in toks: idx = toks.index( 'by' ) change.user = toks[ idx+1 ] change.description = '' lineIter = iter( lines[ 2: ] ) try: prefix = 'text:' PREFIX_LEN = len( prefix ) line = lineIter.next() while line.startswith( prefix ): line = line[ PREFIX_LEN: ].lstrip() if line.startswith( 'Affected files ...' ): break change.description += line line = lineIter.next() lineIter.next() line = lineIter.next() while not line.startswith( prefix ): idx = line.rfind( '#' ) depotFile = Path( line[ :idx ] ) revAndAct = line[ idx + 1: ].split() rev = int( revAndAct[ 0 ] ) act = revAndAct[ 1 ] change.files.append( depotFile ) change.actions.append( act ) change.revisions.append( rev ) line = lineIter.next() except StopIteration: pass return change @classmethod def FetchByDescription( cls, description, createIfNotFound=False ): ''' fetches a changelist based on a given description from the list of pending changelists ''' cleanDesc = ''.join( [ s.strip() for s in description.lower().strip().split( '\n' ) ] ) for change in cls.IterPending(): thisDesc = ''.join( [ s.strip() for s in change.description.lower().strip().split( '\n' ) ] ) if thisDesc == cleanDesc: return change if createIfNotFound: return cls.Create( description ) @classmethod def FetchChanges( cls, *args ): ''' effectively runs the command: p4 changes -l *args a list of P4Change objects is returned ''' lines = _p4run( 'changes -l %s' % ' '.join( args ) ) changes = [] if lines: lineIter = iter( lines ) curChange = None try: while True: line = lineIter.next() if line.startswith( 'Change' ): curChange = cls() changes.append( curChange ) toks = line.split() curChange.change = int( toks[ 1 ] ) curChange.user = toks[ -1 ] curChange.date = datetime.date( *list( map( int, toks[ 3 ].split( '/' ) ) ) ) curChange.description = '' #setup triggers for other data in the changelist that doesn't get returned by the changes command - see the __getattr__ doc for more info curChange.files = populateChange curChange.actions = populateChange curChange.revisions = populateChange elif curChange is not None: curChange.description += line except StopIteration: return changes @classmethod def IterPending( cls ): ''' iterates over pending changelists ''' info = p4Info() for line in _p4run( 'changes -u %s -s pending -c %s' % (info.userName, info.clientName) ): toks = line.split() try: changeNum = int( toks[ 1 ] ) except IndexError: continue yield cls.FetchByNumber( changeNum ) #the number of the default changelist P4Change.CHANGE_NUM_DEFAULT = P4Change() P4Change.CHANGE_NUM_DEFAULT.change = 0 #the object to represent invalid changelist numbers P4Change.CHANGE_NUM_INVALID = P4Change() #all opened perforce files get added to a changelist with this description by default DEFAULT_CHANGE = 'default auto-checkout' #gets called when a perforce command takes too long (defined by P4File.TIMEOUT_PERIOD) P4_LENGTHY_CALLBACK = None #gets called when a lengthy perforce command finally returns P4_RETURNED_CALLBACK = None class P4File(Path): ''' provides a more convenient way of interfacing with perforce. NOTE: where appropriate all actions are added to the changelist with the description DEFAULT_CHANGE ''' USE_P4 = False #the default change description for instances DEFAULT_CHANGE = DEFAULT_CHANGE BINARY = 'binary' XBINARY = 'xbinary' TIMEOUT_PERIOD = 5 def run( self, *args, **kwargs ): return p4run( *args, **kwargs ) def getFile( self, f=None ): if f is None: return self return Path( f ) def getFileStr( self, f=None, allowMultiple=False, verifyExistence=True ): if f is None: return '"%s"' % self if isinstance( f, (list, tuple) ): if verifyExistence: return '"%s"' % '" "'.join( [ anF for anF in f if Path( anF ).exists() ] ) else: return '"%s"' % '" "'.join( f ) return '"%s"' % Path( f ) def getStatus( self, f=None ): ''' returns the status dictionary for the instance. if the file isn't managed by perforce, None is returned ''' if not self.USE_P4: return None f = self.getFile( f ) try: return self.run( 'fstat', f ) except Exception: return None def isManaged( self, f=None ): ''' returns True if the file is managed by perforce, otherwise False ''' if not self.USE_P4: return False f = self.getFile( f ) stat = self.getStatus( f ) if stat: #if the file IS managed - only return true if the head action isn't delete - which effectively means the file #ISN'T managed... try: return stat[ 'headAction' ] != 'delete' except KeyError: #this can happen if the file is a new file and is opened for add return True return False managed = isManaged def isUnderClient( self, f=None ): ''' returns whether the file is in the client's root ''' if not self.USE_P4: return False f = self.getFile( f ) results = _p4fast( 'fstat', f ) if results: fstatDict = results[0] if 'code' in fstatDict: if fstatDict[ 'code' ] == 'error': phrases = [ "not in client view", "not under" ] dataStr = fstatDict[ 'data' ].lower() for ph in phrases: if ph in dataStr: return False return True def getAction( self, f=None ): ''' returns the head "action" of the file - if the file isn't in perforce None is returned... ''' if not self.USE_P4: return None f = self.getFile( f ) data = self.getStatus( f ) try: return data.get( 'action', None ) except AttributeError: return None action = property( getAction ) def getHaveHead( self, f=None ): if not self.USE_P4: return False f = self.getFile( f ) data = self.getStatus( f ) try: return data[ 'haveRev' ], data[ 'headRev' ] except (AttributeError, TypeError, KeyError): return None, None def isEdit( self, f=None ): if not self.USE_P4: return False editActions = [ 'add', 'edit' ] action = self.getAction( f ) #if the action is none, the file may not be managed - check if action is None: if not self.getStatus( f ): return None return action in editActions def isLatest( self, f=None ): ''' returns True if the user has the latest version of the file, otherwise False ''' #if no p4 integration, always say everything is the latest to prevent complaints from tools if not self.USE_P4: return True status = self.getStatus( f ) if not status: return None #if there is any action on the file then always return True if 'action' in status: return True #otherwise check revision numbers try: headRev, haveRev = status[ 'headRev' ], status[ 'haveRev' ] return headRev == haveRev except KeyError: return False def add( self, f=None, type=None ): if not self.USE_P4: return False try: args = [ 'add', '-c', self.getOrCreateChange() ] except: return False #if the type has been specified, add it to the add args if type is not None: args += [ '-t', type ] args.append( self.getFile( f ) ) ret = p4run( *args ) if ret.errors: return False return True def edit( self, f=None ): f = self.getFile( f ) if not isPerforceEnabled(): #if p4 is disabled but the file is read-only, set it to be writeable... if not f.getWritable(): f.setWritable() return False #if the file is already writeable, assume its checked out already if f.getWritable(): return True try: ret = p4run( 'edit', '-c', self.getOrCreateChange(), self.getFile( f ) ) except: return False if ret.errors: return False return True def editoradd( self, f=None ): if self.edit( f ): return True if self.add( f ): return True return False def revert( self, f=None ): if not self.USE_P4: return False return self.run( 'revert', self.getFile( f ) ) def sync( self, f=None, force=False, rev=None, change=None ): ''' rev can be a negative number - if it is, it works as previous revisions - so rev=-1 syncs to the version prior to the headRev. you can also specify the change number using the change arg. if both a rev and a change are specified, the rev is used ''' if not self.USE_P4: return False f = self.getFile( f ) #if file is a directory, then we want to sync to the dir f = str( f.asfile() ) if not f.startswith( '//' ): #depot paths start with // - but windows will try to poll the network for a computer with the name, so if it starts with //, assume its a depot path if os.path.isdir( f ): f = '%s/...' % f if rev is not None: if rev == 0: f += '#none' elif rev < 0: status = self.getStatus() headRev = status[ 'headRev' ] rev += int( headRev ) if rev <= 0: rev = 'none' f += '#%s' % rev else: f += '#%s' % rev elif change is not None: f += '@%s' % change if force: return self.run( 'sync', '-f', f ) else: return self.run( 'sync', f ) def delete( self, f=None ): if not self.USE_P4: return False f = self.getFile( f ) action = self.getAction( f ) if action is None and self.managed( f ): return self.run( 'delete', '-c', self.getOrCreateChange(), f ) def remove( self, f=None ): if not self.USE_P4: return False self.sync( f, rev=0 ) def rename( self, newName, f=None ): if not self.USE_P4: return False f = self.getFile( f ) try: action = self.getAction( f ) if action is None and self.managed( f ): self.run( 'integrate', '-c', self.getOrCreateChange(), f, str( newName ) ) return self.run( 'delete', '-c', self.getOrCreateChange(), f ) except Exception: pass return False def copy( self, newName, f=None ): if not self.USE_P4: return False f = self.getFile( f ) newName = self.getFile( newName ) action = self.getAction( f ) if self.managed( f ): return self.run( 'integrate', '-c', self.getOrCreateChange(), f, newName ) return False def submit( self, change=None ): if not self.USE_P4: return if change is None: change = self.getChange().change self.run( 'submit', '-c', change ) def getChange( self, f=None ): if not self.USE_P4: return P4Change.CHANGE_NUM_INVALID f = self.getFile( f ) stat = self.getStatus( f ) try: return stat.get( 'change', P4Change.CHANGE_NUM_DEFAULT ) except (AttributeError, ValueError): return P4Change.CHANGE_NUM_DEFAULT def setChange( self, newChange=None, f=None ): ''' sets the changelist the file belongs to. the changelist can be specified as either a changelist number, a P4Change object, or a description. if a description is given, the existing pending changelists are searched for a matching description. use 0 for the default changelist. if None is passed, then the changelist as described by self.DEFAULT_CHANGE is used ''' if not self.USE_P4: return if isinstance( newChange, (int, long) ): change = newChange elif isinstance( newChange, P4Change ): change = newChange.change else: change = P4Change.FetchByDescription( newChange, True ).change f = self.getFile( f ) self.run( 'reopen', '-c', change, f ) def getOtherOpen( self, f=None ): f = self.getFile( f ) statusDict = self.getStatus( f ) try: return statusDict[ 'otherOpen' ] except (KeyError, TypeError): return [] def getOrCreateChange( self, f=None ): ''' if the file isn't already in a changelist, this will create one. returns the change number ''' if not self.USE_P4: return P4Change.CHANGE_NUM_INVALID f = self.getFile( f ) ch = self.getChange( f ) if ch == P4Change.CHANGE_NUM_DEFAULT: return P4Change.FetchByDescription( self.DEFAULT_CHANGE, True ).change return ch def getChangeNumFromDesc( self, description=None, createIfNotFound=True ): if description is None: description = self.DEFAULT_CHANGE return P4Change.FetchByDescription( description, createIfNotFound ).change def allPaths( self, f=None ): ''' returns all perforce paths for the file (depot path, workspace path and disk path) ''' if not self.USE_P4: return None f = self.getFile( f ) return toDepotAndDiskPaths( [f] )[ 0 ] def toDepotPath( self, f=None ): ''' returns the depot path to the file ''' if not self.USE_P4: return None return self.allPaths( f )[ 0 ] def toDiskPath( self, f=None ): ''' returns the disk path to a depot file ''' if not self.USE_P4: return None return self.allPaths( f )[ 1 ] P4Data = P4File #used to be called P4Data - this is just for any legacy references... path.P4File = P4File #insert the class into the path script... HACKY! ###--- Add Perforce Integration To Path Class ---### def asP4( self ): ''' returns self as a P4File instance - the instance is cached so repeated calls to this method will result in the same P4File instance being returned. NOTE: the caching is done within the method, it doesn't rely on the cache decorators used elsewhere in this class, so it won't get blown away on cache flush ''' try: return self.p4 except AttributeError: self.p4 = P4File(self) return self.p4 def edit( self ): ''' if the file exists and is in perforce, this will open it for edit - if the file isn't in perforce AND exists then this will open the file for add, otherwise it does nothing ''' if self.exists(): return self.asP4().editoradd() return False editoradd = edit def add( self, type=None ): return self.asP4().add() def revert( self ): return self.asP4().revert() def asDepot( self ): ''' returns this instance as a perforce depot path ''' return self.asP4().toDepotPath() #now wrap existing methods on the Path class - like write, delete, copy etc so that they work nicely with perforce pathWrite = Path.write def _p4write( filepath, contentsStr, doP4=True ): ''' wraps Path.write: if doP4 is true, the file will be either checked out of p4 before writing or add to perforce after writing if its not managed already ''' assert isinstance( filepath, Path ) if doP4 and isPerforceEnabled(): hasBeenHandled = False isUnderClient = P4File().isUnderClient( filepath ) if filepath.exists(): #assume if its writeable that its open for edit already if not filepath.getWritable(): _p4fast( 'edit', filepath ) if not filepath.getWritable(): filepath.setWritable() hasBeenHandled = True ret = pathWrite( filepath, contentsStr ) if isUnderClient and not hasBeenHandled: _p4fast( 'add', filepath ) return ret return pathWrite( filepath, contentsStr ) pathPickle = Path.pickle def _p4Pickle( filepath, toPickle, doP4=True ): assert isinstance( filepath, Path ) if doP4 and isPerforceEnabled(): hasBeenHandled = False isUnderClient = P4File().isUnderClient( filepath ) if filepath.exists(): if not filepath.getWritable(): _p4fast( 'edit', filepath ) if not filepath.getWritable(): filepath.setWritable() hasBeenHandled = True ret = pathPickle( filepath, toPickle ) if isUnderClient and not hasBeenHandled: #need to explicitly add pickled files as binary type files, otherwise p4 mangles them _p4fast( 'add -t binary', filepath ) return ret return pathPickle( filepath, toPickle ) pathDelete = Path.delete def _p4Delete( filepath, doP4=True ): if doP4 and isPerforceEnabled(): try: asP4 = P4File( filepath ) if asP4.managed(): if asP4.action is None: asP4.delete() if not filepath.exists(): return else: asP4.revert() asP4.delete() #only return if the file doesn't exist anymore - it may have been open for add in #which case we still need to do a normal delete... if not filepath.exists(): return except Exception, e: pass return pathDelete( filepath ) pathRename = Path.rename def _p4Rename( filepath, newName, nameIsLeaf=False, doP4=True ): ''' it is assumed newPath is a fullpath to the new dir OR file. if nameIsLeaf is True then newName is taken to be a filename, not a filepath. the instance is modified in place. if the file is in perforce, then a p4 rename (integrate/delete) is performed ''' newPath = Path( newName ) if nameIsLeaf: newPath = filepath.up() / newName if filepath.isfile(): tgtExists = newPath.exists() if doP4 and isPerforceEnabled(): reAdd = False change = None asP4 = P4File( filepath ) #if its open for add, revert - we're going to rename the file... if asP4.action == 'add': asP4.revert() change = asP4.getChange() reAdd = True #so if we're managed by p4 - try a p4 rename, and return on success. if it #fails however, then just do a normal rename... if asP4.managed(): asP4.rename( newPath ) return newPath #if the target exists and is managed by p4, make sure its open for edit if tgtExists and asP4.managed( newPath ): _p4fast( 'edit', newPath ) #now perform the rename ret = pathRename( filepath, newName, nameIsLeaf ) if reAdd: _p4fast( 'add', newPath ) asP4.setChange( change, newPath ) return ret elif filepath.isdir(): raise NotImplementedError( 'dir renaming not implemented yet...' ) return pathRename( filepath, newName, nameIsLeaf ) pathCopy = Path.copy def _p4Copy( filepath, target, nameIsLeaf=False, doP4=True ): ''' same as rename - except for copying. returns the new target name ''' if filepath.isfile(): target = Path( target ) if nameIsLeaf: target = filepath.up() / target if doP4 and isPerforceEnabled(): try: asP4 = P4File( filepath ) tgtAsP4 = P4File( target ) if asP4.managed() and tgtAsP4.isUnderClient(): #so if we're managed by p4 - try a p4 rename, and return on success. if it #fails however, then just do a normal rename... asP4.copy( target ) return target except: pass return pathCopy( filepath ) def lsP4( queryStr, includeDeleted=False ): ''' returns a list of dict's containing the clientFile, depotFile, headRev, headChange and headAction ''' filesAndDicts = [] queryLines = _p4run( 'files', queryStr ) for line in queryLines: fDict = {} toks = line.split( ' ' ) #deal with error lines, or exit lines (an exit prefix may not actually mean the end of the data - the query may have been broken into batches) if line.startswith( 'exit' ): continue if line.startswith( 'error' ): continue fData = toks[ 0 ] idx = fData.index( '#' ) f = Path( fData[ :idx ] ) fDict[ 'depotPath' ] = f rev = int( fData[ idx+1: ] ) fDict[ 'headRev' ] = rev action = toks[ 2 ] fDict[ 'headAction' ] = action if action == 'delete' and not includeDeleted: continue fDict[ 'headChange' ] = toks[ 4 ] filesAndDicts.append( (f, fDict) ) diskPaths = toDiskPaths( [f[0] for f in filesAndDicts] ) lsResult = [] for diskPath, (f, fDict) in zip( diskPaths, filesAndDicts ): fDict[ 'clientFile' ] = diskPath lsResult.append( fDict ) return lsResult def toDepotAndDiskPaths( files ): caseMatters = Path.DoesCaseMatter() lines = [] for filesChunk in iterBy( files, 15 ): lines += _p4run( 'where', *filesChunk )[ :-1 ] #last line is the "exit" line... paths = [] for f, line in zip( map( Path, files ), lines ): fName = f[ -1 ] fNameLen = len( fName ) manipLine = line if not caseMatters: manipLine = line.lower() fName = fName.lower() #I'm not entirely sure this is bullet-proof... but basically the return string for this command #is a simple space separated string, with three values. i guess I could try to match //HOSTNAME #and the client's depot root to find the start of files, but for now its simply looking for the #file name substring three times depotNameIdx = manipLine.find( fName ) + fNameLen depotName = P4File( line[ :depotNameIdx ], caseMatters ) workspaceNameIdx = manipLine.find( fName, depotNameIdx ) + fNameLen #workspaceName = P4File( line[ depotNameIdx + 1:workspaceNameIdx ], caseMatters ) diskNameIdx = manipLine.find( fName, workspaceNameIdx ) + fNameLen diskName = P4File( line[ workspaceNameIdx + 1:diskNameIdx ], caseMatters ) paths.append( (depotName, diskName) ) return paths def toDepotPaths( files ): ''' return the depot paths for the given list of disk paths ''' return [ depot for depot, disk in toDepotAndDiskPaths( files ) ] def toDiskPaths( files ): ''' return the depot paths for the given list of disk paths ''' return [ disk for depot, disk in toDepotAndDiskPaths( files ) ] def isPerforceEnabled(): return P4File.USE_P4 def enablePerforce( state=True ): ''' sets the enabled state of perforce ''' P4File.USE_P4 = bool( state ) #hook up various convenience functions on the Path class, and plug in the overrides for operations #such as write, delete, rename etc... This makes using perforce in conjunction with the Path class #transparent to the programmer if state: Path.asP4 = asP4 Path.edit = edit Path.editoradd = edit Path.add = add Path.revert = revert Path.asDepot = asDepot Path.write = _p4write Path.pickle = _p4Pickle Path.delete = _p4Delete Path.rename = _p4Rename Path.copy = _p4Copy #restore the overridden methods on the Path class and delete any of the convenience methods added else: try: del( Path.asP4 ) del( Path.edit ) del( Path.editoradd ) del( Path.add ) del( Path.revert ) del( Path.asDepot ) #if any of the above throw an Attribute error, presumably perforce hasn't been setup yet so assume none are present and just pass except AttributeError: pass #if perforce hasn't been setup already, doing this is harmless... Path.write = pathWrite Path.pickle = pathPickle Path.delete = pathDelete Path.rename = pathRename Path.copy = pathCopy def disablePerforce(): ''' alias for enablePerforce( False ) ''' enablePerforce( False ) def d_preserveDefaultChange(f): ''' decorator to preserve the default changelist ''' def newF( *a, **kw ): global DEFAULT_CHANGE preChange = DEFAULT_CHANGE try: f( *a, **kw ) except: DEFAULT_CHANGE = preChange raise DEFAULT_CHANGE = preChange newF.__doc__ = f.__doc__ newF.__name__ = f.__name__ return newF def syncFiles( files, force=False, rev=None, change=None ): ''' syncs a given list of files to either the headRev (default) or a given changelist, or a given revision number ''' p4 = P4File() if rev is not None: ret = [] for f in files: if force: r = p4.sync( '-f', f, rev ) else: r = p4.sync( f, rev ) ret.append( r ) return ret elif change is not None: args = [ 'sync' ] if force: args.append( '-f' ) args += [ '%s@%d' % (f, change) for f in files ] return p4run( *args ) else: args = files if force: args = [ '-f' ] + args return p4.run( 'sync', *args ) def findStaleFiles( fileList ): ''' given a list of files (can be string paths or Path instances) returns a list of "stale" files. stale files are simply files that aren't at head revision ''' p4 = P4File() stale = [] for f in fileList: latest = p4.isLatest( f ) if latest is None: continue if not latest: stale.append( f ) return stale def gatherFilesIntoChange( files, change=None ): ''' gathers the list of files into a single changelist - if no change is specified, then the default change is used ''' p4 = P4File() filesGathered = [] for f in files: if not isinstance( f, Path ): f = Path( f ) try: stat = p4.getStatus( f ) except IndexError: continue if not stat: try: if not f.exists(): continue except TypeError: continue #in this case, the file isn't managed by perforce - so add it print 'adding file:', f p4.add( f ) p4.setChange(change, f) filesGathered.append( f ) continue #otherwise, see what the action is on the file - if there is no action then the user hasn't #done anything to the file, so move on... try: action = stat[ 'action' ] p4.setChange( change, f ) filesGathered.append( f ) except KeyError: continue return filesGathered def cleanEmptyChanges(): p4 = P4File() for change in P4Change.IterPending(): deleteIt = False try: deleteIt = not change.files except KeyError: deleteIt = True if deleteIt: p4run( 'change -d', str( change ) ) def findRedundantPYCs( rootDir=None, recursive=True ): ''' lists all orphaned files under a given directory. it does this by looking at the pyc/pyo file and seeing if its corresponding py file exists on disk, or in perforce in any form. if it does, it deletes the file... ''' if rootDir is None: rootDir = tools() bytecodeExtensions = [ 'pyc', 'pyo' ] exceptions = [ 'p4' ] rootDir = Path( rootDir ) orphans = [] if rootDir.exists(): p4 = P4File() files = rootDir.files( recursive=recursive ) bytecodeFiles = [] for f in files: for byteXtn in bytecodeExtensions: if f.hasExtension( byteXtn ): if f.name().lower() in exceptions: continue bytecodeFiles.append( f ) for f in bytecodeFiles: pyF = Path( f ).setExtension( 'py' ) #is there a corresponding py script for this file? if it does, the pyc is safe to delete - so delete it if pyF.exists(): f.reason = 'corresponding py script found' orphans.append( f ) continue #if no corresponding py file exists for the pyc, then see if there is/was one in perforce... if the #corresponding py file is in perforce in any way, shape or form, then delete the .pyc file - its derivative and #can/will be re-generated when needed stat = p4.getStatus( pyF ) if stat is None: continue f.reason = 'corresponding py file in perforce' orphans.append( f ) return rootDir, orphans def deleteRedundantPYCs( rootDir=None, recursive=True, echo=False ): ''' does a delete on orphaned pyc/pyo files ''' rootDir, orphans = findRedundantPYCs( rootDir, recursive ) for f in orphans: if echo: try: print f - rootDir, f.reason except AttributeError: pass f.delete()
Python
from path import * from misc import removeDupes LOCALES = LOCAL, GLOBAL = 'local', 'global' DEFAULT_XTN = 'preset' #define where the base directories are for presets kLOCAL_BASE_DIR = Path('%HOME%/presets/') kGLOBAL_BASE_DIR = Path( __file__ ).up( 2 ) class PresetException(Exception): def __init__( self, *args ): Exception.__init__(self, *args) def getPresetDirs( locale, tool ): ''' returns the base directory for a given tool's preset files ''' if locale == LOCAL: localDir = kLOCAL_BASE_DIR / tool localDir.create() return [localDir] globalDir = kGLOBAL_BASE_DIR / tool globalDir.create() return [globalDir] def presetPath( locale, tool, presetName, ext=DEFAULT_XTN ): preset = getPresetDirs(locale, tool)[0] + scrubName(presetName, exceptions='./') preset = preset.setExtension( ext ) return preset def readPreset( locale, tool, presetName, ext=DEFAULT_XTN ): ''' reads in a preset file if it exists, returning its contents ''' file = getPresetPath(presetName, tool, ext, locale) if file is not None: return file.read() return [] def savePreset( locale, tool, presetName, ext=DEFAULT_XTN, contentsStr='' ): ''' given a contents string, this convenience method will store it to a preset file ''' preset = Preset(locale, tool, presetName, ext) preset.write( contentsStr ) return preset def unpicklePreset( locale, tool, presetName, ext=DEFAULT_XTN ): ''' same as readPreset except for pickled presets ''' dirs = getPresetDirs(locale, tool) for dir in dirs: cur = dir/presetName cur.extension = ext if cur.exists: return cur.unpickle() raise IOError("file doesn't exist!") def picklePreset( locale, tool, presetName, ext=DEFAULT_XTN, contentsObj=None ): preset = presetPath(locale, tool, presetName, ext) preset.pickle(contentsObj, locale==GLOBAL) def listPresets( locale, tool, ext=DEFAULT_XTN ): ''' lists the presets in a given local for a given tool ''' files = [] alreadyAdded = set() for d in getPresetDirs(locale, tool): if d.exists: for f in d.files(): if f.name() in alreadyAdded: continue if f.hasExtension( ext ): files.append( f ) alreadyAdded.add( f.name() ) #remove duplicates files = removeDupes( files ) files = [ Preset.FromFile( f ) for f in files ] return files def listAllPresets( tool, ext=DEFAULT_XTN, localTakesPrecedence=False ): ''' lists all presets for a given tool and returns a dict with local and global keys. the dict values are lists of Path instances to the preset files, and are unique - so a preset in the global list will not appear in the local list by default. if localTakesPrecedence is True, then this behaviour is reversed, and locals will trump global presets of the same name ''' primaryLocale = GLOBAL secondaryLocale = LOCAL primary = listPresets(primaryLocale, tool, ext) secondary = listPresets(secondaryLocale, tool, ext) if localTakesPrecedence: primary, secondary = secondary, primary primaryLocale, secondaryLocale = secondaryLocale, primaryLocale #so teh localTakesPrecedence determines which locale "wins" when there are leaf name clashes #ie if there is a preset in both locales called "yesplease.preset", if localTakesPrecedence is #False, then the global one gets included, otherwise the local one is listed alreadyAdded = set() locales = {LOCAL:[], GLOBAL:[]} for p in primary: locales[ primaryLocale ].append( p ) alreadyAdded.add( p.name() ) for p in secondary: if p.name() in alreadyAdded: continue locales[ secondaryLocale ].append( p ) return locales def getPresetPath( presetName, tool, ext=DEFAULT_XTN, locale=GLOBAL ): ''' given a preset name, this method will return a path to that preset if it exists. it respects the project's mod hierarchy, so it may return a path to a file not under the current mod's actual preset directory... ''' searchPreset = '%s.%s' % (presetName, ext) dirs = getPresetDirs(locale, tool) for dir in dirs: presetPath = dir / searchPreset if presetPath.exists: return presetPath def findPreset( presetName, tool, ext=DEFAULT_XTN, startLocale=LOCAL ): ''' looks through all locales and all search mods for a given preset name. the startLocale simply dictates which locale is searched first - so if a preset exists under both locales, then then one found in the startLocale will get returned ''' other = list( LOCALES ).remove( startLocale ) for loc in [ startLocale, other ]: p = getPresetPath( presetName, tool, ext, loc ) if p is not None: return p def dataFromPresetPath( path ): ''' returns a tuple containing the locale, tool, name, extension for a given Path instance. a PresetException is raised if the path given isn't an actual preset path ''' locale, tool, name, ext = None, None, None, None pathCopy = Path( path ) if pathCopy.isUnder( kGLOBAL_BASE_DIR ): locale = GLOBAL pathCopy -= kGLOBAL_BASE_DIR elif pathCopy.isUnder( kLOCAL_BASE_DIR ): locale = LOCAL pathCopy -= kLOCAL_BASE_DIR else: raise PresetException("%s isn't under the local or the global preset dir" % file) tool = pathCopy[ -2 ] ext = pathCopy.getExtension() name = pathCopy.name() return locale, tool, name, ext def scrubName( theStr, replaceChar='_', exceptions=None ): invalidChars = """`~!@#$%^&*()-+=[]\\{}|;':"/?><., """ if exceptions: for char in exceptions: invalidChars = invalidChars.replace(char, '') for char in invalidChars: theStr = theStr.replace(char, '_') return theStr #these are a bunch of variables used for keys in the export dict. they're provided mainly for #the sake of auto-completion... kEXPORT_DICT_USER = 'user' kEXPORT_DICT_MACHINE = 'machine' kEXPORT_DICT_DATE = 'date' kEXPORT_DICT_TIME = 'time' kEXPORT_DICT_PROJECT = 'project' kEXPORT_DICT_CONTENT = 'content' kEXPORT_DICT_TOOL = 'tool_name' kEXPORT_DICT_TOOL_VER = 'tool_version' kEXPORT_DICT_SOURCE = 'scene' #the source of the file - if any def writeExportDict( toolName=None, toolVersion=None, **kwargs ): ''' returns a dictionary containing a bunch of common info to write when generating presets or other such export type data ''' d = {} now = datetime.datetime.now() d[ kEXPORT_DICT_DATE ], d[ kEXPORT_DICT_TIME ] = now.date(), now.time() d[ kEXPORT_DICT_TOOL ] = toolName d[ kEXPORT_DICT_TOOL_VER ] = toolVersion #add the data in kwargs to the export dict - NOTE: this is done using setdefault so its not possible #to clobber existing keys by specifying them as kwargs... for key, value in kwargs.iteritems(): d.setdefault(key, value) return d class PresetManager(object): def __init__( self, tool, ext=DEFAULT_XTN ): self.tool = tool self.extension = ext def getPresetDirs( self, locale=GLOBAL ): ''' returns the base directory for a given tool's preset files ''' return getPresetDirs(locale, self.tool) def presetPath( self, name, locale=GLOBAL ): return Preset(locale, self.tool, name, self.extension) def findPreset( self, name, startLocale=LOCAL ): return Preset( *dataFromPresetPath( findPreset(name, self.tool, self.extension, startLocale) ) ) def listPresets( self, locale=GLOBAL ): return listPresets(locale, self.tool, self.extension) def listAllPresets( self, localTakesPrecedence=False ): return listAllPresets(self.tool, self.extension, localTakesPrecedence) class Preset(Path): ''' provides a convenient way to write/read and otherwise handle preset files ''' def __new__( cls, locale, tool, name, ext=DEFAULT_XTN ): ''' locale should be one of either GLOBAL or LOCAL object references. tool is the toolname used to refer to all presets of that kind, while ext is the file extension used to differentiate between multiple preset types a tool may have ''' name = scrubName(name, exceptions='./') path = getPresetPath(name, tool, ext, locale) if path is None: path = presetPath(locale, tool, name, ext) return Path.__new__( cls, path ) def __init__( self, locale, tool, name, ext=DEFAULT_XTN ): self.locale = locale self.tool = tool @staticmethod def FromFile( filepath ): return Preset(*dataFromPresetPath(filepath)) FromPreset = FromFile def up( self, levels=1 ): return Path( self ).up( levels ) def other( self ): ''' returns the "other" locale - ie if teh current instance points to a GLOBAL preset, other() returns LOCAL ''' if self.locale == GLOBAL: return LOCAL else: return GLOBAL def copy( self ): ''' copies the current instance from its current locale to the "other" locale. handles all perforce operations when copying a file from one locale to the other. NOTE: the current instance is not affected by a copy operation - a new Preset instance is returned ''' other = self.other() otherLoc = getPresetDirs(other, self.tool)[0] dest = otherLoc / self[-1] destP4 = None addToP4 = False ##in this case, we want to make sure the file is open for edit, or added to p4... #if other == GLOBAL: #destP4 = P4File(dest) #if destP4.managed(): #destP4.edit() #print 'opening %s for edit' % dest #else: #addToP4 = True Path.copy(self, dest) #if addToP4: ##now if we're adding to p4 - we need to know if the preset is a pickled preset - if it is, we need ##to make sure we add it as a binary file, otherwise p4 assumes text, which screws up the file #try: #self.unpickle() #destP4.add(type=P4File.BINARY) #except Exception, e: ##so it seems its not a binary file, so just do a normal add #print 'exception when trying to unpickle - assuming a text preset', e #destP4.add() #print 'opening %s for add' % dest return Preset(self.other(), self.tool, self.name(), self.extension) def move( self ): ''' moves the preset from the current locale to the "other" locale. all instance variables are updated to point to the new location for the preset ''' newLocation = self.copy() #delete the file from disk - and handle p4 reversion if appropriate self.delete() #now point instance variables to the new locale self.locale = self.other() return self.FromFile( newLocation ) def rename( self, newName ): ''' newName needs only be the new name for the preset - extension is optional. All perforce transactions are taken care of. all instance attributes are modified in place ie: a = Preset(GLOBAL, 'someTool', 'presetName') a.rename('the_new_name) ''' if not newName.endswith(self.extension): newName = '%s.%s' % (newName, self.extension) return Path.rename(self, newName, True) def getName( self ): return Path(self).setExtension()[-1] #end
Python
from path import * from misc import * #from perforce import * from presets import * IS_WING_DEBUG = 'WINGDB_ACTIVE' in os.environ class GoodException(Exception): ''' good exceptions are just a general purpose way of breaking out of loops and whatnot. basically anytime an exception is needed to control code flow and not indicate an actual problem using a GoodException makes it a little more obvious what the code is doing in the absence of comments ''' pass BreakException = GoodException class Callback(object): ''' stupid little callable object for when you need to "bake" temporary args into a callback - useful mainly when creating callbacks for dynamicly generated UI items ''' def __init__( self, func, *args, **kwargs ): self.func = func self.args = args self.kwargs = kwargs def __call__( self, *args ): return self.func( *self.args, **self.kwargs ) #end
Python
import inspect def removeDupes( iterable ): ''' ''' unique = set() newIterable = iterable.__class__() for item in iterable: if item not in unique: newIterable.append(item) unique.add(item) return newIterable def iterBy( iterable, count ): ''' returns an generator which will yield "chunks" of the iterable supplied of size "count". eg: for chunk in iterBy( range( 7 ), 3 ): print chunk results in the following output: [0, 1, 2] [3, 4, 5] [6] ''' cur = 0 i = iter( iterable ) while True: try: toYield = [] for n in range( count ): toYield.append( i.next() ) yield toYield except StopIteration: if toYield: yield toYield break def findMostRecentDefitionOf( variableName ): ''' ''' try: fr = inspect.currentframe() frameInfos = inspect.getouterframes( fr, 0 ) #in this case, walk up the caller tree and find the first occurance of the variable named <variableName> for frameInfo in frameInfos: frame = frameInfo[0] var = None if var is None: try: var = frame.f_locals[ variableName ] return var except KeyError: pass try: var = frame.f_globals[ variableName ] return var except KeyError: pass #NOTE: this method should never ever throw an exception... except: pass def getArgDefault( function, argName ): ''' returns the default value of the given named arg. if the arg doesn't exist, or a NameError is raised. if the given arg has no default an IndexError is raised. ''' args, va, vkw, defaults = inspect.getargspec( function ) if argName not in args: raise NameError( "The given arg does not exist in the %s function" % function ) args.reverse() idx = args.index( argName ) try: return list( reversed( defaults ) )[ idx ] except IndexError: raise IndexError( "The function %s has no default for the %s arg" % (function, argName) ) #end
Python
from __future__ import with_statement from cacheDecorators import * import os import re import sys import stat import shutil import cPickle import datetime #the mail server used to send mail MAIL_SERVER = 'exchange' DEFAULT_AUTHOR = 'default_username@your_domain.com' #set the pickle protocol to use PICKLE_PROTOCOL = 2 #set some variables for separators NICE_SEPARATOR = '/' NASTY_SEPARATOR = '\\' NATIVE_SEPARATOR = (NICE_SEPARATOR, NASTY_SEPARATOR)[ os.name == 'nt' ] PATH_SEPARATOR = '/' #(NICE_SEPARATOR, NASTY_SEPARATOR)[ os.name == 'nt' ] OTHER_SEPARATOR = '\\' #(NASTY_SEPARATOR, NICE_SEPARATOR)[ os.name == 'nt' ] UNC_PREFIX = PATH_SEPARATOR * 2 def cleanPath( pathString ): ''' will clean out all nasty crap that gets into pathnames from various sources. maya will often put double, sometimes triple slashes, different slash types etc ''' pathString = os.path.expanduser( str( pathString ) ) path = pathString.strip().replace( OTHER_SEPARATOR, PATH_SEPARATOR ) isUNC = path.startswith( UNC_PREFIX ) while UNC_PREFIX in path: path = path.replace( UNC_PREFIX, PATH_SEPARATOR ) if isUNC: path = PATH_SEPARATOR + path return path ENV_REGEX = re.compile( "\%[^%]+\%" ) findall = re.findall def resolveAndSplit( path, envDict=None, raiseOnMissing=False ): ''' recursively expands all environment variables and '..' tokens in a pathname ''' if envDict is None: envDict = os.environ path = os.path.expanduser( str( path ) ) #first resolve any env variables if '%' in path: #performing this check is faster than doing the regex matches = findall( ENV_REGEX, path ) missingVars = set() while matches: for match in matches: try: path = path.replace( match, envDict[ match[ 1:-1 ] ] ) except KeyError: if raiseOnMissing: raise missingVars.add( match ) matches = set( findall( ENV_REGEX, path ) ) #remove any variables that have been found to be missing... for missing in missingVars: matches.remove( missing ) #now resolve any subpath navigation if OTHER_SEPARATOR in path: #believe it or not, checking this first is faster path = path.replace( OTHER_SEPARATOR, PATH_SEPARATOR ) #is the path a UNC path? isUNC = path[ :2 ] == UNC_PREFIX if isUNC: path = path[ 2: ] #remove duplicate separators duplicateSeparator = UNC_PREFIX while duplicateSeparator in path: path = path.replace( duplicateSeparator, PATH_SEPARATOR ) pathToks = path.split( PATH_SEPARATOR ) pathsToUse = [] pathsToUseAppend = pathsToUse.append for n, tok in enumerate( pathToks ): if tok == "..": try: pathsToUse.pop() except IndexError: if raiseOnMissing: raise pathsToUse = pathToks[ n: ] break else: pathsToUseAppend( tok ) #finally convert it back into a path and pop out the last token if its empty path = PATH_SEPARATOR.join( pathsToUse ) if not pathsToUse[-1]: pathsToUse.pop() #if its a UNC path, stick the UNC prefix if isUNC: return UNC_PREFIX + path, pathsToUse, True return path, pathsToUse, isUNC def resolve( path, envDict=None, raiseOnMissing=False ): return resolveAndSplit( path, envDict, raiseOnMissing )[0] resolvePath = resolve sz_BYTES = 0 sz_KILOBYTES = 1 sz_MEGABYTES = 2 sz_GIGABYTES = 3 class Path(str): __CASE_MATTERS = os.name != 'nt' @classmethod def SetCaseMatter( cls, state ): cls.__CASE_MATTERS = state @classmethod def DoesCaseMatter( cls ): return cls.__CASE_MATTERS @classmethod def Join( cls, *toks, **kw ): return cls( '/'.join( toks ), **kw ) def __new__( cls, path='', caseMatters=None, envDict=None ): ''' if case doesn't matter for the path instance you're creating, setting caseMatters to False will do things like caseless equality testing, caseless hash generation ''' #early out if we've been given a Path instance - paths are immutable so there is no reason not to just return what was passed in if isinstance( path, cls ): return path #set to an empty string if we've been init'd with None if path is None: path = '' resolvedPath, pathTokens, isUnc = resolveAndSplit( path, envDict ) new = str.__new__( cls, resolvedPath ) new.isUNC = isUnc new.hasTrailing = resolvedPath.endswith( PATH_SEPARATOR ) new._splits = tuple( pathTokens ) new._passed = path #case sensitivity, if not specified, defaults to system behaviour if caseMatters is not None: new.__CASE_MATTERS = caseMatters return new @classmethod def Temp( cls ): ''' returns a temporary filepath - the file should be unique (i think) but certainly the file is guaranteed to not exist ''' import datetime, random def generateRandomPathName(): now = datetime.datetime.now() rnd = '%06d' % (abs(random.gauss(0.5, 0.5)*10**6)) return '%TEMP%'+ PATH_SEPARATOR +'TMP_FILE_%s%s%s%s%s%s%s%s' % (now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, rnd) randomPathName = cls( generateRandomPathName() ) while randomPathName.exists(): randomPathName = cls( generateRandomPathName() ) return randomPathName def __nonzero__( self ): ''' a Path instance is "non-zero" if its not '' or '/' (although I guess '/' is actually a valid path on *nix) ''' selfStripped = self.strip() if selfStripped == '': return False if selfStripped == PATH_SEPARATOR: return False return True def __add__( self, other ): return self.__class__( '%s%s%s' % (self, PATH_SEPARATOR, other), self.__CASE_MATTERS ) #the / or + operator both concatenate path tokens __div__ = __add__ def __radd__( self, other ): return self.__class__( other, self.__CASE_MATTERS ) + self __rdiv__ = __radd__ def __getitem__( self, item ): return self._splits[ item ] def __getslice__( self, a, b ): isUNC = self.isUNC if a: isUNC = False return self._toksToPath( self._splits[ a:b ], isUNC, self.hasTrailing ) def __len__( self ): if not self: return 0 return len( self._splits ) def __contains__( self, item ): if not self.__CASE_MATTERS: return item.lower() in [ s.lower() for s in self._splits ] return item in list( self._splits ) def __hash__( self ): ''' the hash for two paths that are identical should match - the most reliable way to do this is to use a tuple from self.split to generate the hash from ''' if not self.__CASE_MATTERS: return hash( tuple( [ s.lower() for s in self._splits ] ) ) return hash( tuple( self._splits ) ) def _toksToPath( self, toks, isUNC=False, hasTrailing=False ): ''' given a bunch of path tokens, deals with prepending and appending path separators for unc paths and paths with trailing separators ''' toks = list( toks ) if isUNC: toks = ['', ''] + toks if hasTrailing: toks.append( '' ) return self.__class__( PATH_SEPARATOR.join( toks ), self.__CASE_MATTERS ) def resolve( self, envDict=None, raiseOnMissing=False ): ''' will re-resolve the path given a new envDict ''' if envDict is None: return self else: return Path( self._passed, self.__CASE_MATTERS, envDict ) def unresolved( self ): ''' returns the un-resolved path - this is the exact string that the path was instantiated with ''' return self._passed def isEqual( self, other ): ''' compares two paths after all variables have been resolved, and case sensitivity has been taken into account - the idea being that two paths are only equal if they refer to the same filesystem object. NOTE: this doesn't take into account any sort of linking on *nix systems... ''' if not isinstance( other, Path ): other = Path( other, self.__CASE_MATTERS ) selfStr = str( self.asFile() ) otherStr = str( other.asFile() ) if not self.__CASE_MATTERS: selfStr = selfStr.lower() otherStr = otherStr.lower() return selfStr == otherStr __eq__ = isEqual def __ne__( self, other ): return not self.isEqual( other ) def doesCaseMatter( self ): return self.__CASE_MATTERS @classmethod def getcwd( cls ): ''' returns the current working directory as a path object ''' return cls( os.getcwd() ) @classmethod def setcwd( cls, path ): ''' simply sets the current working directory - NOTE: this is a class method so it can be called without first constructing a path object ''' newPath = cls( path ) try: os.chdir( newPath ) except WindowsError: return None return newPath putcwd = setcwd def getStat( self ): try: return os.stat( self ) except: #return a null stat_result object return os.stat_result( [ 0 for n in range( os.stat_result.n_sequence_fields ) ] ) stat = property( getStat ) def isAbs( self ): try: return os.path.isabs( str( self ) ) except: return False def abs( self ): ''' returns the absolute path as is reported by os.path.abspath ''' return self.__class__( os.path.abspath( str( self ) ) ) def split( self ): ''' returns the splits tuple - ie the path tokens ''' return list( self._splits ) def asDir( self ): ''' makes sure there is a trailing / on the end of a path ''' if self.hasTrailing: return self return self.__class__( '%s%s' % (self._passed, PATH_SEPARATOR), self.__CASE_MATTERS ) asdir = asDir def asFile( self ): ''' makes sure there is no trailing path separators ''' if not self.hasTrailing: return self return self.__class__( str( self )[ :-1 ], self.__CASE_MATTERS ) asfile = asFile def isDir( self ): ''' bool indicating whether the path object points to an existing directory or not. NOTE: a path object can still represent a file that refers to a file not yet in existence and this method will return False ''' return os.path.isdir( self ) isdir = isDir def isFile( self ): ''' see isdir notes ''' return os.path.isfile( self ) isfile = isFile def getReadable( self ): ''' returns whether the current instance's file is readable or not. if the file doesn't exist False is returned ''' try: s = os.stat( self ) return s.st_mode & stat.S_IREAD except: #i think this only happens if the file doesn't exist return False def setWritable( self, state=True ): ''' sets the writeable flag (ie: !readonly) ''' try: setTo = stat.S_IREAD if state: setTo = stat.S_IWRITE os.chmod(self, setTo) except: pass def getWritable( self ): ''' returns whether the current instance's file is writeable or not. if the file doesn't exist True is returned ''' try: s = os.stat( self ) return s.st_mode & stat.S_IWRITE except: #i think this only happens if the file doesn't exist - so return true return True def getExtension( self ): ''' returns the extension of the path object - an extension is defined as the string after a period (.) character in the final path token ''' try: endTok = self[ -1 ] except IndexError: return '' idx = endTok.rfind( '.' ) if idx == -1: return '' return endTok[ idx+1: ] #add one to skip the period def setExtension( self, xtn=None, renameOnDisk=False ): ''' sets the extension the path object. deals with making sure there is only one period etc... if the renameOnDisk arg is true, the file on disk (if there is one) is renamed with the new extension ''' if xtn is None: xtn = '' #make sure there is are no start periods while xtn.startswith( '.' ): xtn = xtn[ 1: ] toks = list( self.split() ) try: endTok = toks.pop() except IndexError: endTok = '' idx = endTok.rfind( '.' ) name = endTok if idx >= 0: name = endTok[ :idx ] if xtn: newEndTok = '%s.%s' % (name, xtn) else: newEndTok = name if renameOnDisk: self.rename( newEndTok, True ) else: toks.append( newEndTok ) return self._toksToPath( toks, self.isUNC, self.hasTrailing ) extension = property(getExtension, setExtension) def hasExtension( self, extension ): ''' returns whether the extension is of a certain value or not ''' ext = self.getExtension() if not self.__CASE_MATTERS: ext = ext.lower() extension = extension.lower() return ext == extension isExtension = hasExtension def name( self, stripExtension=True, stripAllExtensions=False ): ''' returns the filename by itself - by default it also strips the extension, as the actual filename can be easily obtained using self[-1], while extension stripping is either a multi line operation or a lengthy expression ''' try: name = self[ -1 ] except IndexError: return '' if stripExtension: pIdx = -1 if stripAllExtensions: pIdx = name.find('.') else: pIdx = name.rfind('.') if pIdx != -1: return name[ :pIdx ] return name def up( self, levels=1 ): ''' returns a new path object with <levels> path tokens removed from the tail. ie: Path("a/b/c/d").up(2) returns Path("a/b") ''' if not levels: return self toks = list( self._splits ) levels = max( min( levels, len(toks)-1 ), 1 ) toksToJoin = toks[ :-levels ] if self.hasTrailing: toksToJoin.append( '' ) return self._toksToPath( toksToJoin, self.isUNC, self.hasTrailing ) def replace( self, search, replace='', caseMatters=None ): ''' a simple search replace method - works on path tokens. if caseMatters is None, then the system default case sensitivity is used ''' idx = self.find( search, caseMatters ) toks = list( self.split() ) toks[ idx ] = replace return self._toksToPath( toks, self.isUNC, self.hasTrailing ) def find( self, search, caseMatters=None ): ''' returns the index of the given path token ''' if caseMatters is None: #in this case assume system case sensitivity - ie sensitive only on *nix platforms caseMatters = self.__CASE_MATTERS if not caseMatters: toks = [ s.lower() for s in self.split() ] search = search.lower() else: toks = self.split() idx = toks.index( search ) return idx index = find def exists( self ): ''' returns whether the file exists on disk or not ''' return os.path.exists( self ) def matchCase( self ): ''' If running under an env where file case doesn't matter, this method will return a Path instance whose case matches the file on disk. It assumes the file exists ''' if self.doesCaseMatter(): return self for f in self.up().files(): if f == self: return f def getSize( self, units=sz_MEGABYTES ): ''' returns the size of the file in mega-bytes ''' div = float( 1024 ** units ) return os.path.getsize( self ) / div def create( self ): ''' if the directory doesn't exist - create it ''' if not self.exists(): os.makedirs( str( self ) ) def delete( self ): ''' WindowsError is raised if the file cannot be deleted ''' if self.isfile(): selfStr = str( self ) try: os.remove( selfStr ) except WindowsError, e: os.chmod( selfStr, stat.S_IWRITE ) os.remove( selfStr ) elif self.isdir(): selfStr = str( self.asDir() ) for f in self.files( recursive=True ): f.delete() os.chmod( selfStr, stat.S_IWRITE ) shutil.rmtree( selfStr, True ) remove = delete def rename( self, newName, nameIsLeaf=False ): ''' it is assumed newPath is a fullpath to the new dir OR file. if nameIsLeaf is True then newName is taken to be a filename, not a filepath. the fullpath to the renamed file is returned ''' newPath = Path( newName ) if nameIsLeaf: newPath = self.up() / newName if self.isfile(): if newPath != self: if newPath.exists(): newPath.delete() #now perform the rename os.rename( self, newPath ) elif self.isdir(): raise NotImplementedError( 'dir renaming not implemented yet...' ) return newPath move = rename def copy( self, target, nameIsLeaf=False ): ''' same as rename - except for copying. returns the new target name ''' if self.isfile(): target = Path( target ) if nameIsLeaf: asPath = self.up() / target target = asPath if self == target: return target shutil.copy2( str( self ), str( target ) ) return target elif self.isdir(): raise NotImplementedError( 'dir copying not implemented yet...' ) #shutil.copytree( str(self), str(target) ) def read( self, strip=True ): ''' returns a list of lines contained in the file. NOTE: newlines are stripped from the end but whitespace at the head of each line is preserved unless strip=False ''' if self.exists() and self.isfile(): fileId = file( self ) if strip: lines = [line.rstrip() for line in fileId.readlines()] else: lines = fileId.read() fileId.close() return lines def write( self, contentsStr ): ''' writes a given string to the file defined by self ''' #make sure the directory to we're writing the file to exists self.up().create() with open( self, 'w' ) as f: f.write( str(contentsStr) ) def pickle( self, toPickle ): ''' similar to the write method but pickles the file ''' self.up().create() with open( self, 'w' ) as f: cPickle.dump( toPickle, f, PICKLE_PROTOCOL ) def unpickle( self ): ''' unpickles the file ''' fileId = file( self, 'rb' ) data = cPickle.load(fileId) fileId.close() return data def relativeTo( self, other ): ''' returns self as a path relative to another ''' if not self: return None path = self other = Path( other ) pathToks = path.split() otherToks = other.split() caseMatters = self.__CASE_MATTERS if not caseMatters: pathToks = [ t.lower() for t in pathToks ] otherToks = [ t.lower() for t in otherToks ] #if the first path token is different, early out - one is not a subset of the other in any fashion if otherToks[0] != pathToks[0]: return None lenPath, lenOther = len( path ), len( other ) if lenPath < lenOther: return None newPathToks = [] pathsToDiscard = lenOther for pathN, otherN in zip( pathToks[ 1: ], otherToks[ 1: ] ): if pathN == otherN: continue else: newPathToks.append( '..' ) pathsToDiscard -= 1 newPathToks.extend( path[ pathsToDiscard: ] ) path = Path( PATH_SEPARATOR.join( newPathToks ), self.__CASE_MATTERS ) return path __sub__ = relativeTo def __rsub__( self, other ): return self.__class__( other, self.__CASE_MATTERS ).relativeTo( self ) def inject( self, other, envDict=None ): ''' injects an env variable into the path - if the env variable doesn't resolve to tokens that exist in the path, a path string with the same value as self is returned... NOTE: a string is returned, not a Path instance - as Path instances are always resolved NOTE: this method is alias'd by __lshift__ and so can be accessed using the << operator: d:/main/content/mod/models/someModel.ma << '%VCONTENT%' results in %VCONTENT%/mod/models/someModel.ma ''' toks = toksLower = self._splits otherToks = Path( other, self.__CASE_MATTERS, envDict=envDict ).split() newToks = [] n = 0 if not self.__CASE_MATTERS: toksLower = [ t.lower() for t in toks ] otherToks = [ t.lower() for t in otherToks ] while n < len( toks ): tok, tokLower = toks[ n ], toksLower[ n ] if tokLower == otherToks[ 0 ]: allMatch = True for tok, otherTok in zip( toksLower[ n + 1: ], otherToks[ 1: ] ): if tok != otherTok: allMatch = False break if allMatch: newToks.append( other ) n += len( otherToks ) - 1 else: newToks.append( toks[ n ] ) else: newToks.append( tok ) n += 1 return PATH_SEPARATOR.join( newToks ) __lshift__ = inject def findNearest( self ): ''' returns the longest path that exists on disk ''' path = self while not path.exists() and len( path ) > 1: path = path.up() if not path.exists(): raise IOError( "Cannot find any path above this one" ) return path getClosestExisting = findNearest nearest = findNearest def asNative( self ): ''' returns a string with system native path separators ''' return str( self ).replace( PATH_SEPARATOR, NATIVE_SEPARATOR ) def startswith( self, other ): ''' returns whether the current instance begins with a given path fragment. ie: Path('d:/temp/someDir/').startswith('d:/temp') returns True ''' if not isinstance( other, type( self ) ): other = Path( other, self.__CASE_MATTERS ) otherToks = other.split() selfToks = self.split() if not self.__CASE_MATTERS: otherToks = [ t.lower() for t in otherToks ] selfToks = [ t.lower() for t in selfToks ] if len( otherToks ) > len( selfToks ): return False for tokOther, tokSelf in zip(otherToks, selfToks): if tokOther != tokSelf: return False return True isUnder = startswith def endswith( self, other ): ''' determines whether self ends with the given path - it can be a string ''' #copies of these objects NEED to be made, as the results from them are often cached - hence modification to them #would screw up the cache, causing really hard to track down bugs... not sure what the best answer to this is, #but this is clearly not it... the caching decorator could always return copies of mutable objects, but that #sounds wasteful... for now, this is a workaround otherToks = list( Path( other ).split() ) selfToks = list( self._splits ) otherToks.reverse() selfToks.reverse() if not self.__CASE_MATTERS: otherToks = [ t.lower() for t in otherToks ] selfToks = [ t.lower() for t in selfToks ] for tokOther, tokSelf in zip(otherToks, selfToks): if tokOther != tokSelf: return False return True def _list_filesystem_items( self, itemtest, namesOnly=False, recursive=False ): ''' does all the listing work - itemtest can generally only be one of os.path.isfile or os.path.isdir. if anything else is passed in, the arg given is the full path as a string to the filesystem item ''' if not self.exists(): return if recursive: walker = os.walk( self ) for path, subs, files in walker: path = Path( path, self.__CASE_MATTERS ) for sub in subs: p = path / sub if itemtest( p ): if namesOnly: p = p.name() yield p else: break #if this doesn't match, none of the other subs will for item in files: p = path / item if itemtest( p ): if namesOnly: p = p.name() yield p else: break #if this doesn't match, none of the other items will else: for item in os.listdir( self ): p = self / item if itemtest( p ): if namesOnly: p = p.name() yield p def dirs( self, namesOnly=False, recursive=False ): ''' returns a generator that lists all sub-directories. If namesOnly is True, then only directory names (relative to the current dir) are returned ''' return self._list_filesystem_items( os.path.isdir, namesOnly, recursive ) def files( self, namesOnly=False, recursive=False ): ''' returns a generator that lists all files under the path (assuming its a directory). If namesOnly is True, then only directory names (relative to the current dir) are returned ''' return self._list_filesystem_items( os.path.isfile, namesOnly, recursive ) def findInPyPath( filename ): ''' given a filename or path fragment, will return the full path to the first matching file found in the sys.path variable ''' for p in map( Path, sys.path ): loc = p / filename if loc.exists(): return loc return None def findInPath( filename ): ''' given a filename or path fragment, will return the full path to the first matching file found in the PATH env variable ''' for p in map( Path, os.environ[ 'PATH' ].split( ';' ) ): loc = p / filename if loc.exists(): return loc return None #end
Python
from vectors import Vector _MAX_RECURSE = 35 class BinarySearchTree(list): SORT_DIMENSION = 0 def __init__( self, data ): list.__init__( self, data ) #sort by the desired dimension if self.SORT_DIMENSION == 0: self.sort() else: sortDimension = self.SORT_DIMENSION self.sort( key=lambda v: v[ sortDimension ] ) def getBestRange( self, value, data, breakRange=50 ): #50 is arbitrary, but smaller values than this provide either incremental improvements or possibly even performance degredation ''' returns a 2-tuple containing minIdx, maxIdx indices into the data list, with the given value somewhere within the range data[ minIdx:maxIdx ] breakRange - this is the delta between minIdx and maxIdx at which the iterative searching halts NOTE: the range returned may not be equal to the breakRange, breakRange is simply the point at which the search iteration breaks. It is true however that the range returned will always be greater than breakRange/2 ''' sortDimension = self.SORT_DIMENSION minIdx = 0 maxIdx = len( data )-1 rng = maxIdx - minIdx while rng >= breakRange: half = minIdx + (rng / 2) halfValue = data[ half ][ sortDimension ] if halfValue == value: #TODO: see what the cost of this is in the general case... return half, half if halfValue <= value: minIdx = half else: maxIdx = half rng = maxIdx - minIdx return minIdx, maxIdx def getWithin( self, theVector, tolerance=1e-6, maxCount=None ): ''' returns a list of vectors near theVector within a given tolerance - optionally limiting the number of matches to maxCount ''' #do some binary culling before beginning the search - the 50 number is arbitrary, #but values less than that don't lead to significant performance improvements, and #in fact can lead to performance degredation minX = theVector[0] - tolerance maxX = theVector[0] + tolerance minIdx, maxIdx = self.getBestRange( minX, self ) #see whether we need to find a different value for the maxIdx - it may be appropriate already and if it is save some cycles by skipping the search if self[ maxIdx ][0] <= maxX: _x, maxIdx = self.getBestRange( maxX, self[ minIdx: ] ) maxIdx += minIdx #because we searched within self[ minIdx: ] so we need to add minIdx to maxIdx #we have a good range for appriate x values, now check to see of that subset which y values fit our criteria matchingY = [] minY = theVector[1] - tolerance maxY = theVector[1] + tolerance for i in self[ minIdx:maxIdx ]: if minY <= i[1] <= maxY: matchingY.append( i ) #do the same for z matching = [] minZ = theVector[2] - tolerance maxZ = theVector[2] + tolerance for i in matchingY: if minZ <= i[2] <= maxZ: matching.append( i ) #now the matching vectors is a list of vectors that fall within the bounding box with length of 2*tolerance. #we want to reduce this to a list of vectors that fall within the bounding sphere with radius tolerance inSphere = [] sqTolerance = tolerance**2 for m in matching: #this is basically inlined code to get the distance between the point we were given, and all the points #in the matching list so we can return in distance sorted order. inlining the code is faster as is #comparing the squared distance to the squared tolerance sqD = (theVector[0] - m[0])**2 + (theVector[1] - m[1])**2 + (theVector[2] - m[2])**2 if sqD <= sqTolerance: inSphere.append( (sqD, m) ) inSphere.sort() if maxCount is not None: inSphere = inSphere[ :maxCount ] return [ v[1] for v in inSphere ] def getWithinRatio( self, theVector, ratio=2 ): global _MAX_RECURSE tolerance = 1 matching = self.getWithin( theVector, tolerance ) itCount = 0 while not matching: tolerance *= 1.25 itCount += 1 matching = self.getWithin( theVector, tolerance ) if itCount > _MAX_RECURSE: return None closestDist = (theVector - matching[0]).get_magnitude() if len( matching ) == 1 or not closestDist: return matching[ :1 ] return self.getWithin( theVector, closestDist*ratio ) #end
Python
import exportManagerCore, filesystem, datetime, api import maya.cmds as cmd from filesystem import resolvePath mel = api.mel melecho = api.melecho TOOL_NAME = 'visManager' TOOL_VERSION = 1 EXTENSION = filesystem.DEFAULT_XTN DEFAULT_LOCALE = filesystem.LOCAL def exportPreset( presetName, visHierarchyTop, locale=DEFAULT_LOCALE ): ''' exports a vis hierarchy preset file - this file contains a node hierarchy which represents a vis hierarchy. each empty transform node in the group represents a set, and each volume in the structure represents a face selection used to determine vis set membership ''' exportDict = api.writeExportDict(TOOL_NAME, TOOL_VERSION) #simply returns the def getVolumesAndEmptyGroups( node ): children = cmd.listRelatives(node, type='transform', path=True) volumes = [] groups = [] for child in children: shapes = cmd.listRelatives(child, shapes=True, type='nurbsSurface', path=True) if shapes: type = int( cmd.getAttr('%s.exportVolume' % child) ) pos = cmd.xform(child, q=True, ws=True, rp=True) rot = cmd.xform(child, q=True, ws=True, ro=True) scale = cmd.getAttr('%s.s' % child)[0] volumes.append( (child, type, pos, rot, scale) ) else: groups.append( child ) return volumes, groups topVolumes, topGroups = getVolumesAndEmptyGroups(visHierarchyTop) parentQueue = [(visHierarchyTop, topGroups)] #create the first entry toExport = [(visHierarchyTop, None, topVolumes)] while True: try: curNode = topGroups.pop(0) curParent = cmd.listRelatives(curNode, p=True)[0] curVolumes, curChildren = getVolumesAndEmptyGroups(curNode) topGroups.extend(curChildren) toExport.append( (curNode, curParent, curVolumes) ) except IndexError: break exportDict['preset'] = toExport thePreset = filesystem.Preset(locale, TOOL_NAME, presetName, EXTENSION) thePreset.pickle(exportDict) @api.d_showWaitCursor def importPreset( presetName, locale=DEFAULT_LOCALE, createSets=True, deleteAfterImport=True ): thePreset = filesystem.Preset(locale, TOOL_NAME, presetName, EXTENSION) presetData = thePreset.unpickle() volumesList = presetData['preset'] #if we're creating the vis sets, then we need to grab a list of meshes in the scene allMeshes = set(cmd.ls(type='mesh')) #this dict tracks what the names were when they were written out, vs what names they are #after building them in scene - names can change due to clashes etc... nodesDict = {} #this dict tracks teh nodes and their corresponding set representation (should one exist...) setDict = {} for node, parent, volumesData in volumesList: curNode = cmd.group(empty=True) curNode = cmd.rename(curNode, node) #if the parent exists in the node list (it should always exist except for the top node... try: curNode = cmd.parent(curNode, nodesDict[parent])[0] except KeyError: pass nodesDict[node] = curNode volumes = [] #build the volumes - place and parent them appropriately for volume, type, pos, rot, scale in volumesData: newVolume = exportManagerCore.createExportVolume( int(type) ) cmd.move(pos[0], pos[1], pos[2], newVolume, a=True, ws=True, rpr=True) cmd.rotate(rot[0], rot[1], rot[2], newVolume, a=True, ws=True) cmd.setAttr('%s.s' % newVolume, *scale) newVolume = cmd.rename(newVolume, volume) cmd.parent(newVolume, curNode) volumes.append(newVolume) if createSets: items = [] setParent = '' try: setParent = setDict[parent] except KeyError: pass for vol in volumes: items.extend( exportManagerCore.findFacesInVolumeForMaya(allMeshes, vol) ) newSet = mel.zooVisManCreateSet(setParent, node, items) setDict[node] = newSet if deleteAfterImport: cmd.delete( nodesDict[ volumesList[0][0] ] ) #return the created volumes return nodesDict.keys(), #end
Python
''' general utils to push changes to referenced scene data back to its original source currently just contains a function to take skin weights from the current scene and push them to the model file ''' from maya.cmds import * from filesystem import Path from api import mel from common import printWarningStr from referenceUtils import stripNamespaceFromNamePath import skinWeights def getRefFilepathDictForNodes( nodes ): ''' returns a dictionary keyed by the referenced filename. Key values are dictionaries which are keyed by reference node (any file can be referenced multiple times) the value of which are the given nodes that are referenced. example: we have a scene with three references: refA comes from c:/someFile.ma refB comes from c:/someFile.ma refC comes from c:/anotherFile.ma we have 3 nodes: nodeA, nodeB and nodeC. nodeA comes from refA nodeB comes from refB nodeA comes from refC in this example running getRefFilepathDictForNodes( ('nodeA', 'nodeB', 'nodeC') ) would return: { 'c:/someFile.ma': { 'refA': [ 'nodeA' ], 'refB': [ 'nodeB' ], 'c:/anotherFile.ma': { 'refC': [ 'nodeC' ] } ''' refFileDict = {} #find the referenced files for the given meshes for node in nodes: isReferenced = referenceQuery( node, inr=True ) if isReferenced: refNode = referenceQuery( node, referenceNode=True ) refFile = Path( referenceQuery( node, filename=True, withoutCopyNumber=True ) ) if refFile in refFileDict: refNodeDict = refFileDict[ refFile ] else: refNodeDict = refFileDict[ refFile ] = {} refNodeDict.setdefault( refNode, [] ) refNodeDict[ refNode ].append( node ) return refFileDict def ensureCurrentFileIsCheckedOut(): curFile = Path( file( q=True, sn=True ) ) if not curFile.getWritable(): curFile.edit() def storeWeightsById( mesh, namespaceToStrip=None ): weightData = [] skinCluster = mel.findRelatedSkinCluster( mesh ) verts = ls( polyListComponentConversion( mesh, toVertex=True ), fl=True ) for vert in verts: jointList = skinPercent( skinCluster, vert, ib=1e-4, q=True, transform=None ) weightList = skinPercent( skinCluster, vert, ib=1e-4, q=True, value=True ) #if there is a namespace to strip, we need to strip it from the vertex and the joint name... if namespaceToStrip is not None: vert = stripNamespaceFromNamePath( vert, namespaceToStrip ) jointList = [ stripNamespaceFromNamePath( j, namespaceToStrip ) for j in jointList ] weightData.append( (vert, zip( jointList, weightList )) ) return weightData def propagateWeightChangesToModel( meshes ): ''' Given a list of meshes to act on, this function will store the skin weights, remove any edits from the skin clusters that affect them, open the scene file the meshes come from and apply the weights to the geometry in that scene. This makes it possible to fix skinning problems while animating with minimal workflow changes ''' curFile = Path( file( q=True, sn=True ) ) referencedMeshes = getRefFilepathDictForNodes( meshes ) if not curFile.name(): printWarningStr( "The current scene isn't saved - please save the current scene first before proceeding!" ) return for refFilepath, refNodeMeshDict in referencedMeshes.iteritems(): referencesToUnload = [] #make sure we don't visit any of the meshes more than once meshesToUpdateWeightsOn = [] meshesToUpdateWeightsOn_withNS = [] for refNode, refMeshes in refNodeMeshDict.iteritems(): #get the maya filepath for the reference (with the "copy number") mayaFilepathForRef = referenceQuery( refNode, f=True ) #get the namespace for this reference refNodeNamespace = file( mayaFilepathForRef, q=True, namespace=True ) #check to see if there are any meshes in this reference that we need to store weights for for mesh_withNS in refMeshes: mesh = stripNamespaceFromNamePath( mesh_withNS, refNodeNamespace ) if mesh in meshesToUpdateWeightsOn: continue meshesToUpdateWeightsOn.append( mesh ) meshesToUpdateWeightsOn_withNS.append( (mesh_withNS, refNodeNamespace) ) #append the file to the list of reference files that we need to unload referencesToUnload.append( mayaFilepathForRef ) #get a list of skin cluster nodes - its actually the skin cluster nodes we want to remove edits from... nodesToCleanRefEditsFrom = [] for m, ns in meshesToUpdateWeightsOn_withNS: nodesToCleanRefEditsFrom.append( mel.findRelatedSkinCluster( m ) ) #now we want to store out the weighting from the referenced meshes weights = [] for mesh, meshNamespace in meshesToUpdateWeightsOn_withNS: weights.append( storeWeightsById( mesh, meshNamespace ) ) #also lets remove any ref edits from the mesh and all of its shape nodes - this isn't strictly nessecary, but I can't think of a reason to make edits to these nodes outside of their native file nodesToCleanRefEditsFrom.append( mesh ) nodesToCleanRefEditsFrom += listRelatives( mesh, s=True, pa=True ) or [] #remove the skinweights reference edits from the meshes in the current scene for f in referencesToUnload: file( f, unloadReference=True ) #remove ref edits from the shape node as well - this isn't strictly nessecary but there probably shouldn't be changes to the shape node anyway for node in nodesToCleanRefEditsFrom: referenceEdit( node, removeEdits=True, successfulEdits=True, failedEdits=True ) #re-load references for f in referencesToUnload: file( f, loadReference=True ) #save this scene now that we've removed ref edits ensureCurrentFileIsCheckedOut() file( save=True, f=True ) #load up the referenced file and apply the weighting to the meshes in that scene file( refFilepath, open=True, f=True ) for mesh, weightData in zip( meshesToUpdateWeightsOn, weights ): #if there is no weight data to store - keep loopin... if not weightData: continue skinCluster = mel.findRelatedSkinCluster( mesh ) if not skinCluster: printWarningStr( "Couldn't find a skin cluster driving %s - skipping this mesh" % mesh ) continue skinWeights.setSkinWeights( skinCluster, weightData ) #save the referenced scene now that we've applied the weights to it ensureCurrentFileIsCheckedOut() file( save=True, f=True ) #reload the original file file( curFile, o=True, f=True ) def propagateWeightChangesToModel_confirm(): ''' simply wraps the propagateWeightChangesToModel function with a confirmation dialog ''' allMeshNodes = ls( type='mesh' ) allSkinnedMeshes = [ mesh for mesh in allMeshNodes if mel.findRelatedSkinCluster( mesh ) ] if not allSkinnedMeshes: printWarningStr( "No skinned meshes can be found in the scene! Aborting!" ) return BUTTONS = OK, CANCEL = 'Ok', 'Cancel' ret = confirmDialog( m='Are you sure you want to push skinning changes to the model?', t='Are you sure?', b=BUTTONS, db=CANCEL ) if ret == OK: propagateWeightChangesToModel( allSkinnedMeshes ) #end
Python
from baseSkeletonBuilder import * class Head(SkeletonPart): HAS_PARITY = False @property def head( self ): return self[ -1 ] @classmethod def _build( cls, parent=None, neckCount=1, **kw ): idx = kw[ 'idx' ] partScale = kw[ 'partScale' ] parent = getParent( parent ) posInc = partScale / 25.0 head = createJoint( 'head' ) if not neckCount: cmd.parent( head, parent, relative=True ) return [ head ] allJoints = [] prevJoint = parent for n in range( neckCount ): j = createJoint( 'neck%d' % (n+1) ) cmd.parent( j, prevJoint, relative=True ) move( 0, posInc, posInc, j, r=True, ws=True ) allJoints.append( j ) prevJoint = j #move the first neck joint up a bunch move( 0, partScale / 10.0, 0, allJoints[ 0 ], r=True, ws=True ) #parent the head appropriately cmd.parent( head, allJoints[ -1 ], relative=True ) move( 0, posInc, posInc, head, r=True, ws=True ) allJoints.append( head ) jointSize( head, 2 ) return allJoints def _align( self, _initialAlign=False ): #aim all neck joints at the next neck joint for n, item in enumerate( self[ :-1 ] ): alignAimAtItem( item, self[ n+1 ] ) if _initialAlign: alignItemToWorld( self.head ) else: alignPreserve( self.head ) def visualize( self ): scale = self.getBuildScale() / 10.0 plane = polyCreateFacet( ch=False, tx=True, s=1, p=((0, -scale, 0), (0, scale, 0), (self.getParityMultiplier() * 2 * scale, 0, 0)) ) cmd.parent( plane, self.head, relative=True ) cmd.parent( listRelatives( plane, shapes=True, pa=True ), self.head, add=True, shape=True ) delete( plane ) def buildItemVolume( self, item, size, centre ): chainLength = rigUtils.chainLength( self.base, self.end ) height = float( size[0] ) width = chainLength / 2.0 #denominator is arbitrary - tune it to whatever... if rigUtils.apiExtensions.cmpNodes( item, self.end ): #if the item is the head (ie the last joint in the part's chain) handle it differently w, h, d = width, width*1.2, width*1.3 geo = polySphere( r=0.1, ax=BONE_AIM_VECTOR, sx=8, sy=4, ch=True )[0] setAttr( '%s.t' % geo, w, 0, d ) else: geo = polyCylinder( h=height * 0.95, r=0.01, ax=BONE_AIM_VECTOR, sx=self.AUTO_VOLUME_SIDES, sy=round( height/width ), ch=True )[0] setAttr( '%s.t' % geo, *centre ) #finally remove the top and bottom cylinder caps - they're always the last 2 faces numFaces = meshUtils.numFaces( geo ) delete( '%s.f[ %d:%d ]' % (geo, numFaces-2, numFaces-1) ) parent( geo, item, r=True ) return [geo] #end
Python
from baseRigPrimitive import * class StretchRig(RigSubPart): ''' creates stretch attribs on the given control, and makes all given joints stretchy ------- control the character prefix used to identify the character parity which side is the arm on? l (left) or r (right) axis the stretch axis used by the joints in the limb. default: x parity the parts node is simply an object that miscellanous dag nodes are parented under - if not specified, miscellanous objects are simply left in worldspace ''' __version__ = 0 NAMED_NODE_NAMES = 'autoLengthBlender', 'ikfkBlender', 'lengthMods', 'lengthClamp' ADD_CONTROLS_TO_QSS = False def _build( self, skeletonPart, control, joints, ikFkBlendAttrpath=None, axis=BONE_AIM_AXIS, parity=Parity.LEFT, elbowPos=1, connectEndJoint=False, **kw ): ''' ikFkBlendAttrpath this should be the attribute that turns ik on when its value is 1, and off when its value is 0 ''' #do some sanity checking if not joints: raise RigPartError( "No joints supplied - you must supply a list of joints to stretch!" ) if ikFkBlendAttrpath is None: ikFkBlendAttrpath = '%s.ikBlend' % control if axis is None: raise NotImplemented( 'auto axis support not written yet - complain loudly!' ) #setup some current unit variables, and take parity into account stretchAuto = "autoStretch" stretchName = "stretch" parityFactor = parity.asMultiplier() addAttr( control, ln=stretchAuto, at='double', min=0, max=1, dv=1 ) addAttr( control, ln=stretchName, at='double', min=-10, max=10, dv=0 ) attrState( control, (stretchAuto, stretchName), keyable=True ) #build the network for distributing stretch from the fk controls to the actual joints plusNodes = [] initialNodes = [] fractionNodes = [] allNodes = [] for c in joints: md = shadingNode( 'multiplyDivide', asUtility=True, name='%s_fraction_pos' % str( c ) ) fractionNodes.append( md ) startObj = joints[0] endObj = control clientLengths = [ 0 ] totalLength = 0 for n, c in enumerate( joints[ :-1 ] ): thisPos = Vector( xform( c, q=True, ws=True, rp=True ) ) nextPos = Vector( xform( joints[ n+1 ], q=True, ws=True, rp=True ) ) l = (thisPos - nextPos).length() clientLengths.append( l ) totalLength += l #build the network to measure limb length loc_a = group( empty=True ) loc_b = group( empty=True ) measure = loc_b parent( loc_b, loc_a ) parent( loc_a, self.getPartsNode() ) constraint_a = pointConstraint( startObj, loc_a )[ 0 ] aim = aimConstraint( endObj, loc_a, aimVector=(1,0,0) )[ 0 ] setAttr( '%s.tx' % loc_b, totalLength ) constraint_b = pointConstraint( endObj, loc_b )[ 0 ] attrState( [ loc_a, loc_b ], ('t', 'r'), *LOCK_HIDE ) #create the stretch network autoLengthBlender = shadingNode( 'blendColors', asUtility=True, n='auto_length_blender' ) fkikBlender = shadingNode( 'blendColors', asUtility=True, n='fkik_blender' ) #turns auto length off when using fk lengthMods = shadingNode( 'plusMinusAverage', asUtility=True, n='length_mods' ) #adds all lengths together lengthClamp = shadingNode( 'clamp', asUtility=True, n='length_clamp' ) #clamps the min/max length for the limb manualStretchMult = shadingNode( 'multiplyDivide', asUtility=True, n='manualStretch_range_multiplier' ) #multiplys manual stretch to a sensible range #NOTE: the second term attribute of the length condition node holds the initial length for the limb, and is thus connected to the false attribute of all condition nodes setAttr( '%s.input2X' % manualStretchMult, totalLength / 10 ) setAttr( '%s.minR' % lengthClamp, totalLength ) setAttr( '%s.color2R' % autoLengthBlender, totalLength ) setAttr( '%s.color2R' % fkikBlender, totalLength ) setAttr( '%s.maxR' % lengthClamp, totalLength * 5 ) connectAttr( '%s.tx' % measure, '%s.inputR' % lengthClamp, f=True ) connectAttr( ikFkBlendAttrpath, '%s.blender' % fkikBlender, f=True ) connectAttr( '%s.outputR' % lengthClamp, '%s.color1R' % fkikBlender, f=True ) connectAttr( '%s.outputR' % fkikBlender, '%s.color1R' % autoLengthBlender, f=True ) connectAttr( '%s.%s' % (control, stretchAuto), '%s.blender' % autoLengthBlender, f=True ) connectAttr( '%s.outputR' % autoLengthBlender, '%s.input1D[ 0 ]' % lengthMods, f=True ) connectAttr( '%s.%s' % (control, stretchName), '%s.input1X' % manualStretchMult, f=True ) connectAttr( '%s.outputX' % manualStretchMult, '%s.input1D[ 1 ]' % lengthMods, f=True ) #connect the stretch distribution network up - NOTE this loop starts at 1 because we don't need to connect the #start of the limb chain (ie the bicep or the thigh) as it doesn't move if connectEndJoint: jIter = enumerate( joints ) else: jIter = enumerate( joints[ :-1 ] ) for n, c in enumerate( joints ): if n == 0: continue setAttr( '%s.input2X' % fractionNodes[ n ], clientLengths[ n ] / totalLength * parityFactor ) #now connect the inital coords to the plus node - then connect the connectAttr( '%s.output1D' % lengthMods, '%s.input1X' % fractionNodes[ n ], f=True ) #try to unlock the tx attr if getAttr( '%s.tx' % joints[ n ], lock=True ): if referenceQuery( joints[ n ], inr=True ): raise TypeError( "The tx attribute is locked, and the %s node is referenced - maya doesn't let you unlock attributes on referenced nodes!" % joints[n] ) setAttr( '%s.tx' % joints[ n ], lock=False ) #then connect the result of the plus node to the t(axis) pos of the limb joints connectAttr( '%s.outputX' % fractionNodes[ n ], '%s.tx' % joints[ n ], f=True ) #now if we have only 3 joints, that means we have a simple limb structure #in which case, lets build an elbow pos network if len( joints ) == 3 and elbowPos: default = clientLengths[ 1 ] / totalLength * parityFactor isNeg = default < 0 default = abs( default ) addAttr( control, ln='elbowPos', at='double', min=0, max=1, dv=default ) setAttr( '%s.elbowPos' % control, keyable=True ) elbowPos = shadingNode( 'reverse', asUtility=True, n='%s_elbowPos' % joints[ 1 ] ) if isNeg: mult = shadingNode( 'multiplyDivide', asUtility=True ) setAttr( '%s.input2' % mult, -1, -1, -1 ) connectAttr( '%s.elbowPos' % control, '%s.inputX' % elbowPos, f=True ) connectAttr( '%s.elbowPos' % control, '%s.input1X' % mult, f=True ) connectAttr( '%s.outputX' % elbowPos, '%s.input1Y' % mult, f=True ) connectAttr( '%s.outputY' % mult, '%s.input2X' % fractionNodes[2], f=True ) connectAttr( '%s.outputX' % mult, '%s.input2X' % fractionNodes[1], f=True ) else: connectAttr( '%s.elbowPos' % control, '%s.inputX' % elbowPos, f=True ) connectAttr( '%s.outputX' % elbowPos, '%s.input2X' % fractionNodes[2], f=True ) connectAttr( '%s.elbowPos' % control, '%s.input2X' % fractionNodes[1], f=True ) controls = () namedNodes = autoLengthBlender, fkikBlender, lengthMods, lengthClamp return controls, namedNodes #end
Python
from filesystem import Path, PresetManager, Preset, savePreset, readPreset, LOCAL, GLOBAL import skeletonBuilder from maya.cmds import * from baseSkeletonBuilder import SkeletonPart, setupAutoMirror, TOOL_NAME, buildSkeletonPartContainer from names import camelCaseToNice import maya.cmds as cmd import apiExtensions import filesystem import inspect XTN = 'skeleton' PRESET_MANAGER = PresetManager( TOOL_NAME, XTN ) VERSION = 0 buildSkeletonPartContainer = skeletonBuilder.buildSkeletonPartContainer SkeletonPart = skeletonBuilder.SkeletonPart setupAutoMirror = skeletonBuilder.setupAutoMirror eval = __builtins__[ 'eval' ] #restore python's eval... class NoPartsError(Exception): pass def generatePresetContents(): lines = [ 'version=%d' % VERSION ] #always store some sort of versioning variable hasParts = False for part in SkeletonPart.IterAllPartsInOrder(): hasParts = True lines.append( '<part>' ) lines.append( '%s=%s' % (part.__class__.__name__, part.getBuildKwargs()) ) for item in part: itemParent = listRelatives( item, p=True, pa=True ) if itemParent: itemParent = itemParent[0] else: itemParent = '' rad = getAttr( '%s.radius' % item ) tx, ty, tz = xform( item, q=True, ws=True, rp=True ) rx, ry, rz = xform( item, q=True, ws=True, ro=True ) #store out the line of attributes to save for the item - NOTE: attributes are currently stored in a way that makes it possible to add/modify the attributes we need serialized reasonably easily... lines.append( '%s,%s=radius:%s;t:%s,%s,%s;r:%s,%s,%s;' % (item, itemParent, rad, tx, ty, tz, rx, ry, rz) ) lines.append( '</part>' ) if not hasParts: raise NoPartsError( "No parts found in scene!" ) return '\n'.join( lines ) def writePreset( presetName ): ''' deals with serializing a skeleton to disk ''' try: contents = generatePresetContents() except NoPartsError: print "No parts found in the scene!" return None return savePreset( LOCAL, skeletonBuilder.TOOL_NAME, presetName, XTN, contents ) def writePresetToFile( presetFilepath ): try: contents = generatePresetContents() except NoPartsError: print "No parts found in the scene!" return Path( presetFilepath ).write( contents ) def loadPreset( presetName ): p = Preset( LOCAL, skeletonBuilder.TOOL_NAME, presetName, XTN ) if not p.exists(): p = Preset( GLOBAL, skeletonBuilder.TOOL_NAME, presetName, XTN ) assert p.exists(), "Cannot find a %s preset called %s" % (XTN, presetName) return loadPresetFile( p ) def loadPresetFile( presetFilepath ): ''' deals with unserializing a skeleton preset definition into the scene ''' assert presetFilepath.exists(), "No preset file found! %" % presetFilepath itemRemapDict = {} partList = [] def cleanUp(): #removes all items built should an exception occur for partType, partItems in partList: if partItems: delete( partItems[0] ) lines = presetFilepath.read() linesIter = iter( lines ) version = linesIter.next().strip() try: for line in linesIter: line = line.strip() #blank line? skip... if not line: continue if line == '<part>': partTypeAndBuildKwargLine = linesIter.next().strip() toks = partTypeAndBuildKwargLine.split( '=' ) numToks = len( toks ) if numToks == 1: partType, partBuildKwargs = toks[0], {} elif numToks == 2: partType, partBuildKwargs = toks partBuildKwargs = eval( partBuildKwargs ) partItems = [] partList.append( (partType, partBuildKwargs, partItems) ) while True: line = linesIter.next().strip() #blank line? skip... if not line: continue #are we done with the part? if line == '</part>': break itemAndParent, attrInfo = line.split( '=' ) item, parent = itemAndParent.split( ',' ) attrBlocks = attrInfo.split( ';' ) #construct the attr dict attrDict = {} for block in attrBlocks: if not block: continue attrName, attrData = block.split( ':' ) attrData = [ d for d in attrData.split( ',' ) if d ] attrDict[ attrName ] = attrData #build the actual joint actualItem = apiExtensions.asMObject( createNode( 'joint', n=item ) ) #insert the item and what it actually maps to in the scene into the itemRemapDict itemRemapDict[ item ] = actualItem #finally append to the list of items in this part partItems.append( (actualItem, parent, attrDict) ) except StopIteration: cleanUp() raise IOError( "File is incomplete!" ) except: cleanUp() raise parts = [] for partType, partBuildKwargs, partItems in partList: items = [] for (actualItem, parent, attrDict) in partItems: actualParent = itemRemapDict.get( parent, None ) #do parenting if appropriate if actualParent is not None: cmd.parent( actualItem, actualParent ) #set the joint size if 'radius' in attrDict: size = attrDict[ 'radius' ][0] setAttr( '%s.radius' % actualItem, float( size ) ) #move to the appropriate position if 't' in attrDict: tx, ty, tz = map( float, attrDict[ 't' ] ) move( tx, ty, tz, actualItem, a=True, ws=True, rpr=True ) #rotate appropriately if 'r' in attrDict: rx, ry, rz = map( float, attrDict[ 'r' ] ) rotate( rx, ry, rz, actualItem, a=True, ws=True ) #append to the items list - so we can instantiate the part once we've finished building the items items.append( actualItem ) #instantiate the part and append it to the list of parts created partClass = SkeletonPart.GetNamedSubclass( partType ) partContainer = buildSkeletonPartContainer( partClass, partBuildKwargs, items ) part = partClass( partContainer ) part.convert( partBuildKwargs ) parts.append( part ) setupAutoMirror() for part in SkeletonPart.IterAllParts(): part.visualize() return parts def listPresets(): return PRESET_MANAGER.listAllPresets( True ) #end
Python
from rigPrim_ikFkBase import * from rigPrim_stretchy import StretchRig class QuadrupedIkFkLeg(IkFkBase): __version__ = 0 SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'QuadrupedFrontLeg' ), SkeletonPart.GetNamedSubclass( 'QuadrupedBackLeg' ) ) CONTROL_NAMES = 'control', 'poleControl', 'clavicle' DISPLAY_NAME = 'Quadruped Leg' def _build( self, skeletonPart, **kw ): #this bit of zaniness is so we don't have to call the items by name, which makes it work with Arm or Leg skeleton primitives items = list( skeletonPart )[ :3 ] if len( skeletonPart ) == 4: items = list( skeletonPart )[ 1:4 ] items.append( skeletonPart[ 0 ] ) return self.doBuild( *items, **kw ) def doBuild( self, thigh, knee, ankle, clavicle, **kw ): idx = kw[ 'idx' ] scale = kw[ 'scale' ] parity = Parity( idx ) parityMult = parity.asMultiplier() nameMod = kw.get( 'nameMod', 'front' ) nameSuffix = '%s%s' % (nameMod.capitalize(), parity.asName()) colour = self.getParityColour() #determine the root partParent, rootControl = getParentAndRootControl( clavicle ) #build out the control for the clavicle clavCtrl = buildControl( 'quadClavicle%s' % nameSuffix, PlaceDesc( clavicle ), PivotModeDesc.BASE, ShapeDesc( 'cylinder', axis=-AIM_AXIS if parity else AIM_AXIS ), colour, scale=scale ) clavCtrlSpace = getNodeParent( clavCtrl ) setAttr( '%s.rotateOrder' % clavCtrl, 1 ) cmd.parent( clavCtrlSpace, partParent ) #build the leg rig primitive self.buildBase( LEG_NAMING_SCHEME ) legCtrl = self.control legFkSpace = self.fkSpace parent( legFkSpace, clavCtrl ) poleSpace = getNodeParent( self.poleControl ) pointConstraint( legFkSpace, legCtrl, poleSpace ) ### SETUP CLAVICLE AIM ### dummyGrp = group( em=True ) delete( pointConstraint( clavicle, dummyGrp ) ) parent( dummyGrp, rootControl ) aimVector = BONE_AIM_VECTOR * parityMult sideClavAxis = getObjectAxisInDirection( clavCtrlSpace, BONE_AIM_VECTOR ).asVector() sideCtrlAxis = getObjectAxisInDirection( legCtrl, BONE_AIM_VECTOR ).asVector() aim = aimConstraint( legCtrl, clavCtrlSpace, aimVector=BONE_AIM_VECTOR, upVector=sideClavAxis, worldUpVector=sideCtrlAxis, worldUpObject=legCtrl, worldUpType='objectrotation', mo=True )[ 0 ] aimNode = aimConstraint( dummyGrp, clavCtrlSpace, weight=0, aimVector=BONE_AIM_VECTOR )[ 0 ] revNode = createNode( 'reverse' ) addAttr( clavCtrl, ln='autoMotion', at='float', min=0, max=1, dv=1 ) setAttr( '%s.autoMotion' % clavCtrl, keyable=True ) connectAttr( '%s.autoMotion' % clavCtrl, '%s.target[0].targetWeight' % aimNode, f=True ) connectAttr( '%s.autoMotion' % clavCtrl, '%s.inputX' % revNode, f=True ) connectAttr( '%s.outputX' % revNode, '%s.target[1].targetWeight' % aimNode, f=True ) ### HOOK UP A FADE FOR THE AIM OFFSET mt, measure, la, lb = buildMeasure( str( clavCtrlSpace ), str( legCtrl ) ) maxLen = chainLength( clavicle, ankle ) curLen = getAttr( '%s.distance' % measure ) cmd.parent( la, rootControl ) cmd.parent( mt, rootControl ) for c in [ mt, la, lb ]: setAttr( '%s.v' % c, False ) setAttr( '%s.v' % c, lock=True ) controls = legCtrl, self.poleControl, clavCtrl return controls, () def duplicateChain( start, end ): chainNodes = getChain( start, end ) dupeJoints = [] for j in chainNodes: dupe = duplicate( j, rr=True )[0] children = listRelatives( dupe, pa=True ) if children: delete( children ) if dupeJoints: parent( dupe, dupeJoints[-1] ) dupeJoints.append( dupe ) return dupeJoints class SatyrLeg(PrimaryRigPart, SwitchableMixin): __version__ = 0 SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'SatyrLeg' ), ) CONTROL_NAMES = 'control', 'poleControl', 'anklePoleControl' NAMED_NODE_NAMES = 'ikSpace', 'fkSpace', 'ikHandle', 'poleTrigger' DISPLAY_NAME = 'Satyr Leg Rig' def getFkJoints( self ): part = self.getSkeletonPart() return part[ :4 ] def getFkControls( self ): allControls = list( self ) return allControls[ -4: ] @d_unifyUndo def switchToFk( self ): fkJoints = self.getFkJoints() fkControls = self.getFkControls() for j, c in zip( fkJoints, fkControls ): alignFast( c, j ) control = self.getControl( 'control' ) setAttr( '%s.ikBlend' % control, 0 ) select( fkControls[-1] ) @d_unifyUndo def switchToIk( self ): fkJoints = self.getFkJoints() control = self.getControl( 'control' ) poleControl = self.getControl( 'poleControl' ) anklePoleControl = self.getControl( 'anklePoleControl' ) polePos = findPolePosition( fkJoints[2], fkJoints[1], fkJoints[0] ) move( polePos[0], polePos[1], polePos[2], poleControl, ws=True, a=True, rpr=True ) alignFast( control, fkJoints[-1] ) alignFast( anklePoleControl, fkJoints[-2] ) setAttr( '%s.ikBlend' % control, 1 ) select( control ) def _build( self, skeletonPart, stretchy=True, **kw ): scale = kw[ 'scale' ] parity = self.getParity() parityMult = parity.asMultiplier() nameMod = kw.get( 'nameMod', 'front' ) nameSuffix = '_%s%s' % (nameMod.capitalize(), parity.asName()) colour = self.getParityColour() originalJoints = originalThighJoint, originalKneeJoint, originalAnkleJoint, originalToeJoint = skeletonPart[:4] getWristToWorldRotation( originalToeJoint, True ) #create a duplicate chain for the ik leg - later we create another chain for fk and constrain the original joints between them for ik/fk switching ikJoints = ikThighJoint, ikKneeJoint, ikAnkleJoint, ikToeJoint = duplicateChain( originalThighJoint, originalToeJoint ) ### IK CHAIN SETUP #determine the root partParent, rootControl = getParentAndRootControl( ikThighJoint ) parent( ikThighJoint, partParent ) setAttr( '%s.v' % ikThighJoint, 0 ) ikHandle = cmd.ikHandle( fs=1, sj=ikThighJoint, ee=ikAnkleJoint, solver='ikRPsolver' )[ 0 ] footCtrl = buildControl( 'Foot%s' % nameSuffix, #PlaceDesc( ikToeJoint, PlaceDesc.WORLD ), ikToeJoint, PivotModeDesc.MID, ShapeDesc( 'cube', axis=-AIM_AXIS if parity else AIM_AXIS ), colour, scale=scale ) footCtrlSpace = getNodeParent( footCtrl ) setAttr( '%s.rotateOrder' % footCtrl, 1 ) setAttr( '%s.v' % ikHandle, 0 ) attrState( ikHandle, 'v', *LOCK_HIDE ) #build the pivots for the foot roll/rock attributes placers = skeletonPart.getPlacers() if placers: footRock_fwd = buildNullControl( 'footRock_forward_null', placers[0], parent=footCtrl ) footRock_back = buildNullControl( 'footRock_backward_null', placers[1], parent=footRock_fwd ) footRoll_inner = buildNullControl( 'footRoll_inner_null', placers[2], parent=footRock_back ) footRoll_outer = buildNullControl( 'footRoll_outer_null', placers[3], parent=footRoll_inner ) else: footRock_fwd = buildNullControl( 'footRock_forward_null', ikToeJoint, parent=footCtrlSpace ) footRock_back = buildNullControl( 'footRock_backward_null', ikToeJoint, parent=footCtrlSpace ) footRoll_inner = buildNullControl( 'footRoll_inner_null', ikToeJoint, parent=footCtrlSpace ) footRoll_outer = buildNullControl( 'footRoll_outer_null', ikToeJoint, parent=footCtrlSpace ) toePos = xform( ikToeJoint, q=True, ws=True, rp=True ) moveIncrement = scale / 2 move( 0, -toePos[1], moveIncrement, footRock_fwd, r=True, ws=True ) move( 0, -toePos[1], -moveIncrement, footRock_back, r=True, ws=True ) move( -moveIncrement * parityMult, -toePos[1], 0, footRoll_inner, r=True, ws=True ) move( moveIncrement * parityMult, -toePos[1], 0, footRoll_outer, r=True, ws=True ) cmd.parent( footRock_back, footRock_fwd ) cmd.parent( footRoll_inner, footRock_back ) cmd.parent( footRoll_outer, footRoll_inner ) cmd.parent( footCtrl, footRoll_outer ) makeIdentity( footCtrl, a=True, t=True ) addAttr( footCtrl, ln='footRock', at='double', dv=0, min=-10, max=10 ) attrState( footCtrl, 'footRock', *NORMAL ) setDrivenKeyframe( '%s.rx' % footRock_fwd, cd='%s.footRock' % footCtrl, dv=0, v=0 ) setDrivenKeyframe( '%s.rx' % footRock_fwd, cd='%s.footRock' % footCtrl, dv=10, v=90 ) setDrivenKeyframe( '%s.rx' % footRock_back, cd='%s.footRock' % footCtrl, dv=0, v=0 ) setDrivenKeyframe( '%s.rx' % footRock_back, cd='%s.footRock' % footCtrl, dv=-10, v=-90 ) addAttr( footCtrl, ln='bank', at='double', dv=0, min=-10, max=10 ) attrState( footCtrl, 'bank', *NORMAL ) setDrivenKeyframe( '%s.rz' % footRoll_inner, cd='%s.bank' % footCtrl, dv=0, v=0 ) setDrivenKeyframe( '%s.rz' % footRoll_inner, cd='%s.bank' % footCtrl, dv=10, v=90 ) setDrivenKeyframe( '%s.rz' % footRoll_outer, cd='%s.bank' % footCtrl, dv=0, v=0 ) setDrivenKeyframe( '%s.rz' % footRoll_outer, cd='%s.bank' % footCtrl, dv=-10, v=-90 ) #setup the auto ankle grpA = buildControl( 'ankle_auto_null', PlaceDesc( ikToeJoint, ikAnkleJoint ), shapeDesc=SHAPE_NULL, constrain=False, parent=footCtrl ) grpB = buildAlignedNull( ikAnkleJoint, 'ankle_orientation_null', parent=grpA ) orientConstraint( grpB, ikAnkleJoint ) for ax in AXES: delete( '%s.t%s' % (ikToeJoint, ax), icn=True ) cmd.parent( ikHandle, grpA ) cmd.parent( footCtrlSpace, self.getWorldControl() ) grpASpace = getNodeParent( grpA ) grpAAutoNull = buildAlignedNull( PlaceDesc( ikToeJoint, ikAnkleJoint ), '%sauto_on_ankle_null%s' % (nameMod, nameSuffix), parent=footCtrl ) grpAAutoOffNull = buildAlignedNull( PlaceDesc( ikToeJoint, ikAnkleJoint ), '%sauto_off_ankle_null%s' % (nameMod, nameSuffix), parent=footCtrl ) grpA_knee_aimVector = betweenVector( grpAAutoNull, ikKneeJoint ) grpA_knee_aimAxis = getObjectAxisInDirection( grpAAutoNull, grpA_knee_aimVector ) grpA_knee_upAxis = getObjectAxisInDirection( grpAAutoNull, (1, 0, 0) ) grpA_knee_worldAxis = getObjectAxisInDirection( footCtrl, (1, 0, 0) ) aimConstraint( ikThighJoint, grpAAutoNull, mo=True, aim=grpA_knee_aimAxis.asVector(), u=grpA_knee_upAxis.asVector(), wu=grpA_knee_worldAxis.asVector(), wuo=footCtrl, wut='objectrotation' ) autoAimConstraint = orientConstraint( grpAAutoNull, grpAAutoOffNull, grpASpace )[0] addAttr( footCtrl, ln='autoAnkle', at='double', dv=1, min=0, max=1 ) attrState( footCtrl, 'autoAnkle', *NORMAL ) cAttrs = listAttr( autoAimConstraint, ud=True ) connectAttr( '%s.autoAnkle' % footCtrl, '%s.%s' % (autoAimConstraint, cAttrs[0]), f=True ) connectAttrReverse( '%s.autoAnkle' % footCtrl, '%s.%s' % (autoAimConstraint, cAttrs[1]), f=True ) poleCtrl = buildControl( 'Pole%s' % nameSuffix, PlaceDesc( ikKneeJoint, PlaceDesc.WORLD ), PivotModeDesc.MID, shapeDesc=ShapeDesc( 'sphere', axis=-AIM_AXIS if parity else AIM_AXIS ), colour=colour, constrain=False, scale=scale, parent=self.getPartsNode() ) poleCtrlSpace = getNodeParent( poleCtrl ) polePos = findPolePosition( ikAnkleJoint ) move( polePos[0], polePos[1], polePos[2], poleCtrlSpace, ws=True, rpr=True, a=True ) pointConstraint( ikThighJoint, footCtrl, poleCtrlSpace, mo=True ) poleVectorConstraint( poleCtrl, ikHandle ) #build the ankle aim control - its acts kinda like a secondary pole vector anklePoleControl = buildControl( 'Ankle%s' % nameSuffix, ikAnkleJoint, shapeDesc=ShapeDesc( 'sphere' ), colour=colour, scale=scale, constrain=False, parent=grpASpace ) ankleAimVector = betweenVector( grpA, anklePoleControl ) ankleAimAxis = getObjectAxisInDirection( grpA, ankleAimVector ) ankleUpAxis = getObjectAxisInDirection( grpA, (1, 0, 0) ) ankleWorldUpAxis = getObjectAxisInDirection( anklePoleControl, (1, 0, 0) ) aimConstraint( anklePoleControl, grpA, aim=ankleAimAxis.asVector(), u=ankleUpAxis.asVector(), wu=ankleWorldUpAxis.asVector(), wuo=anklePoleControl, wut='objectrotation' ) ### FK CHAIN SETUP fkThighControl = buildControl( 'fkThigh%s' % nameSuffix, originalThighJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=partParent ) fkKneeControl = buildControl( 'fkKnee%s' % nameSuffix, originalKneeJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=fkThighControl ) fkAnkleControl = buildControl( 'fkAnkle%s' % nameSuffix, originalAnkleJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=fkKneeControl ) fkToeControl = buildControl( 'fkToe%s' % nameSuffix, originalToeJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=fkAnkleControl ) fkControls = fkThighControl, fkKneeControl, fkAnkleControl, fkToeControl setItemRigControl( originalThighJoint, fkThighControl ) setItemRigControl( originalKneeJoint, fkKneeControl ) setItemRigControl( originalAnkleJoint, fkAnkleControl ) addAttr( footCtrl, ln='ikBlend', at='float', min=0, max=1, dv=1, keyable=True ) for ikJ, fkC, orgJ in zip( ikJoints, fkControls, originalJoints ): constraintNode = parentConstraint( ikJ, orgJ, w=1, mo=True )[0] constraintNode = parentConstraint( fkC, orgJ, w=0, mo=True )[0] ikAttr, fkAttr = listAttr( constraintNode, ud=True ) connectAttr( '%s.ikBlend' % footCtrl, '%s.%s' % (constraintNode, ikAttr) ) connectAttrReverse( '%s.ikBlend' % footCtrl, '%s.%s' % (constraintNode, fkAttr) ) ikControls = footCtrl, poleCtrl, anklePoleControl setupIkFkVisibilityConditions( '%s.ikBlend' % footCtrl, ikControls, fkControls ) #now we need to setup right mouse button menus for ik/fk switching footTrigger = Trigger( footCtrl ) footTrigger.createMenu( 'switch to FK', '''python( "import rigPrimitives; rigPrimitives.RigPart.InitFromItem('#').switchToFk()" )''' ) for c in fkControls: t = Trigger( c ) t.createMenu( 'switch to IK', '''python( "import rigPrimitives; rigPrimitives.RigPart.InitFromItem('#').switchToIk()" )''' ) #setup stretch as appropriate if stretchy: StretchRig.Create( self._skeletonPart, footCtrl, (ikThighJoint, ikKneeJoint, ikAnkleJoint, ikToeJoint), '%s.ikBlend' % ikHandle, parity=parity, connectEndJoint=True ) for ax in CHANNELS: delete( '%s.t%s' % (ikToeJoint, ax), icn=True ) pointConstraint( footCtrl, ikToeJoint ) buildDefaultSpaceSwitching( originalThighJoint, footCtrl, reverseHierarchy=True, space=footCtrlSpace ) buildDefaultSpaceSwitching( originalThighJoint, fkThighControl ) buildDefaultSpaceSwitching( originalToeJoint, fkToeControl, **spaceSwitching.NO_ROTATION ) controls = ikControls + fkControls namedNodes = None, None, ikHandle, None return controls, namedNodes #end
Python
from skinWeightsBase import * from filesystem import removeDupes from maya.cmds import * from binarySearchTree import BinarySearchTree from mayaDecorators import d_unifyUndo import maya.cmds as cmd import api import apiExtensions mel = api.mel iterParents = api.iterParents VertSkinWeight = MayaVertSkinWeight def getAllParents( obj ): allParents = [] parent = [ obj ] while parent is not None: allParents.append( parent[ 0 ] ) parent = cmd.listRelatives( parent, p=True, pa=True ) return allParents[ 1: ] def getDefaultPath(): scenePath = cmd.file(q=True, sn=True) if not scenePath: return DEFAULT_PATH scenePath = Path( scenePath ) scenePath = scenePath.setExtension( EXTENSION ) return scenePath kAPPEND = 0 kREPLACE = 1 @api.d_showWaitCursor def saveWeights( geos, filepath=None ): start = time.clock() miscData = api.writeExportDict(TOOL_NAME, TOOL_VERSION) #if filepath is None, then generate a default filepath based on the location of the file if filepath is None: filepath = getDefaultPath() else: filepath = Path(filepath) geoAndData = {} skinPercent = cmd.skinPercent xform = cmd.xform #define teh data we're gathering masterJointList = [] weightData = [] #data gathering time! rigidBindObjects = [] for geo in geos: skinClusters = cmd.ls( cmd.listHistory( geo ), type='skinCluster' ) if len( skinClusters ) > 1: api.melWarning("more than one skinCluster found on %s" % geo) continue #so the geo isn't skinned in the traditional way - check to see if it is parented to a joint. if so, #stuff it into the rigid bind list to be dealt with outside this loop, and continue if not skinClusters: dealtWith = False for p in iterParents( geo ): if cmd.nodeType( p ) == 'joint': rigidBindObjects.append( (geo, p) ) masterJointList.append( p ) masterJointList = removeDupes( masterJointList ) dealtWith = True break if not dealtWith: msg = "cannot find a skinCluster for %s" % geo api.melWarning(msg) continue skinCluster = skinClusters[ 0 ] masterJointList += cmd.skinCluster( skinCluster, q=True, inf=True ) masterJointList = removeDupes( masterJointList ) verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True) for idx, vert in enumerate(verts): jointList = skinPercent(skinCluster, vert, ib=1e-4, q=True, transform=None) weightList = skinPercent(skinCluster, vert, ib=1e-4, q=True, value=True) if jointList is None: raise SkinWeightException("I can't find any joints - sorry. do you have any post skin cluster history???") pos = xform(vert, q=True, ws=True, t=True) vertData = VertSkinWeight( pos ) vertData.populate( geo, idx, [ masterJointList.index( j ) for j in jointList ], weightList ) weightData.append( vertData ) #deal with rigid bind objects for geo, j in rigidBindObjects: verts = cmd.ls( cmd.polyListComponentConversion(geo, toVertex=True), fl=True ) for idx, vert in enumerate( verts ): jIdx = masterJointList.index( j ) pos = xform( vert, q=True, ws=True, t=True ) vertData = VertSkinWeight( pos ) vertData.populate( geo, idx, [jIdx], [1] ) weightData.append( vertData ) #sort the weightData by ascending x values so we can search faster weightData.sort() #turn the masterJointList into a dict keyed by index joints = {} for n, j in enumerate( masterJointList ): joints[ n ] = j #generate joint hierarchy data - so if joints are missing on load we can find the best match jointHierarchies = {} for n, j in joints.iteritems(): jointHierarchies[ n ] = getAllParents( j ) toWrite = miscData, joints, jointHierarchies, weightData filepath = Path( filepath ) filepath.pickle( toWrite, False ) print 'Weights Successfully Saved to %s: time taken %.02f seconds' % (filepath, time.clock()-start) return filepath @api.d_progress(t='initializing...', status='initializing...', isInterruptable=True) @d_unifyUndo def loadWeights( objects, filepath=None, usePosition=True, tolerance=TOL, axisMult=None, swapParity=True, averageVerts=True, doPreview=False, meshNameRemapDict=None, jointNameRemapDict=None ): ''' loads weights back on to a model given a file ''' #nothing to do... if not objects: print 'No objects given...' return if filepath is None: filepath = getDefaultPath() if not filepath.exists(): print 'File does not exist %s' % filepath return start = time.clock() #setup the mappings VertSkinWeight.MESH_NAME_REMAP_DICT = meshNameRemapDict VertSkinWeight.JOINT_NAME_REMAP_DICT = jointNameRemapDict #cache heavily access method objects as locals... skinPercent = cmd.skinPercent progressWindow = cmd.progressWindow xform = cmd.xform #now get a list of all weight files that are listed on the given objects - and #then load them one by one and apply them to the appropriate objects objItemsDict = {} for obj in objects: items = [] #this holds the vert list passed in IF any if obj.find('.') != -1: items = [obj] obj = obj.split('.')[0] try: objItemsDict[obj].extend( items ) except KeyError: objItemsDict[obj] = items numItems = len(objItemsDict) curItem = 1 progressWindow(e=True, title='loading weights from file %d items' % numItems) #load the data from the file miscData, joints, jointHierarchies, weightData = Path( filepath ).unpickle() #build the search tree tree = BinarySearchTree( weightData ) findMethod = tree.getWithin findMethodKw = { 'tolerance': tolerance } if averageVerts: findMethod = tree.getWithinRatio findMethodKw = { 'ratio': tolerance } #see if the file versions match if miscData[ api.kEXPORT_DICT_TOOL_VER ] != TOOL_VERSION: api.melWarning( "WARNING: the file being loaded was stored from an older version (%d) of the tool - please re-generate the file. Current version is %d." % (miscData[ api.kEXPORT_DICT_TOOL_VER ], TOOL_VERSION) ) #the miscData contains a dictionary with a bunch of data stored from when the weights was saved - do some #sanity checking to make sure we're not loading weights from some completely different source curFile = cmd.file(q=True, sn=True) origFile = miscData['scene'] if curFile != origFile: api.melWarning('the file these weights were saved in a different file from the current: "%s"' % origFile) #remap joint names in the saved file to joint names that are in the scene - they may be namespace differences... missingJoints = set() for n, j in joints.iteritems(): if not cmd.objExists(j): #see if the joint with the same leaf name exists in the scene idxA = j.rfind(':') idxB = j.rfind('|') idx = max(idxA, idxB) if idx != -1: leafName = j[idx + 1:] if objExists( leafName ): joints[n] = leafName else: search = cmd.ls('%s*' % leafName, r=True, type='joint') if search: joints[n] = search[0] print '%s remapped to %s' % (j, search[0]) #now that we've remapped joint names, we go through the joints again and remap missing joints to their nearest parent #joint in the scene - NOTE: this needs to be done after the name remap so that parent joint names have also been remapped for n, j in joints.iteritems(): if not cmd.objExists(j): dealtWith = False for jp in jointHierarchies[n]: if cmd.objExists( jp ): joints[n] = jp dealtWith = True break if dealtWith: print '%s remapped to %s' % (j, jp) continue missingJoints.add(n) #now remove them from the list [ joints.pop(n) for n in missingJoints ] #axisMults can be used to alter the positions of verts saved in the weightData array - this is mainly useful for applying #weights to a mirrored version of a mesh - so weights can be stored on meshA, meshA duplicated to meshB, and then the #saved weights can be applied to meshB by specifying an axisMult=(-1,1,1) OR axisMult=(-1,) if axisMult is not None: for data in weightData: for n, mult in enumerate(axisMult): data[n] *= mult #we need to re-sort the weightData as the multiplication could have potentially reversed things... i could probably #be a bit smarter about when to re-order, but its not a huge hit... so, meh weightData = sortByIdx(weightData) #using axisMult for mirroring also often means you want to swap parity tokens on joint names - if so, do that now. #parity needs to be swapped in both joints and jointHierarchies if swapParity: for joint, target in joints.iteritems(): joints[joint] = str( names.Name(target).swap_parity() ) for joint, parents in jointHierarchies.iteritems(): jointHierarchies[joint] = [str( names.Name(p).swap_parity() ) for p in parents] for geo, items in objItemsDict.iteritems(): #if the geo is None, then check for data in the verts arg - the user may just want weights #loaded on a specific list of verts - we can get the geo name from those verts skinCluster = '' verts = cmd.ls(cmd.polyListComponentConversion(items if items else geo, toVertex=True), fl=True) #do we have a skinCluster on the geo already? if not, build one skinCluster = cmd.ls(cmd.listHistory(geo), type='skinCluster') if not skinCluster: skinCluster = cmd.skinCluster(geo,joints.values())[0] verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True) else: skinCluster = skinCluster[0] #if we're using position, the restore weights path is quite different vertJointWeightData = [] if usePosition: progressWindow( e=True, status='searching by position: %s (%d/%d)' % (geo, curItem, numItems), maxValue=len( verts ) ) vCount = -1 for vert in verts: vCount += 1 pos = Vector( xform(vert, q=True, ws=True, t=True) ) foundVerts = findMethod( pos, **findMethodKw ) #accumulate found verts jointWeightDict = {} for v in foundVerts: for joint, weight in zip( v.joints, v.weights ): actualJoint = joints[ joint ] weight += jointWeightDict.get( actualJoint, 0 ) jointWeightDict[ actualJoint ] = weight #normalize the weights weightSum = float( sum( jointWeightDict.values() ) ) if weightSum != 1: for joint, weight in jointWeightDict.iteritems(): jointWeightDict[ joint ] = weight / weightSum #append the data vertJointWeightData.append( (vert, jointWeightDict.items()) ) #deal with the progress window - this isn't done EVERY vert because its kinda slow... if vCount % 50 == 0: progressWindow( e=True, progress=vCount ) #bail if we've been asked to cancel if progressWindow( q=True, isCancelled=True ): progressWindow( ep=True ) return progressWindow( e=True, status='maya is setting skin weights...' ) setSkinWeights( skinCluster, vertJointWeightData ) #otherwise simply restore by id else: progressWindow( e=True, status='searching by vert name: %s (%d/%d)' % (geo, curItem, numItems), maxValue=len( verts ) ) #rearrange the weightData structure so its ordered by vertex name weightDataById = {} [ weightDataById.setdefault(i.getVertName(), (i.joints, i.weights)) for i in weightData ] for vert in verts: #progressWindow(edit=True, progress=cur / num * 100.0) #if progressWindow(q=True, isCancelled=True): #progressWindow(ep=True) #return #cur += 1 try: jointList, weightList = weightDataById[vert] except KeyError: #in this case, the vert doesn't exist in teh file... print '### no point found for %s' % vert continue else: jointList = [ joints[ j ] for j in jointList ] jointsAndWeights = zip(jointList, weightList) skinPercent(skinCluster, vert, tv=jointsAndWeights) #remove unused influences from the skin cluster cmd.skinCluster( skinCluster, edit=True, removeUnusedInfluence=True ) curItem += 1 end = time.clock() print 'time for weight load %.02f secs' % (end-start) import profileDecorators from maya.OpenMayaAnim import MFnSkinCluster from maya.OpenMaya import MIntArray, MDagPathArray #@profileDecorators.d_profile @d_unifyUndo def setSkinWeights( skinCluster, vertJointWeightData ): ''' vertJointWeightData is a list of 2-tuples containing the vertex component name, and a list of 2-tuples containing the joint name and weight. ie it looks like this: [ ('someMesh.vtx[0]', [('joint1', 0.25), 'joint2', 0.75)]), ('someMesh.vtx[1]', [('joint1', 0.2), 'joint2', 0.7, 'joint3', 0.1)]), ... ] ''' #convert the vertex component names into vertex indices idxJointWeight = [] for vert, jointsAndWeights in vertJointWeightData: idx = int( vert[ vert.rindex( '[' )+1:-1 ] ) idxJointWeight.append( (idx, jointsAndWeights) ) #get an MObject for the skin cluster node skinCluster = apiExtensions.asMObject( skinCluster ) skinFn = MFnSkinCluster( skinCluster ) #construct a dict mapping joint names to joint indices jApiIndices = {} _tmp = MDagPathArray() skinFn.influenceObjects( _tmp ) for n in range( _tmp.length() ): jApiIndices[ str( _tmp[n].node() ) ] = skinFn.indexForInfluenceObject( _tmp[n] ) weightListP = skinFn.findPlug( "weightList" ) weightListObj = weightListP.attribute() weightsP = skinFn.findPlug( "weights" ) tmpIntArray = MIntArray() baseFmtStr = str( skinCluster ) +'.weightList[%d]' #pre build this string: fewer string ops == faster-ness! for vertIdx, jointsAndWeights in idxJointWeight: #we need to use the api to query the physical indices used weightsP.selectAncestorLogicalIndex( vertIdx, weightListObj ) weightsP.getExistingArrayAttributeIndices( tmpIntArray ) weightFmtStr = baseFmtStr % vertIdx +'.weights[%d]' #clear out any existing skin data - and awesomely we cannot do this with the api - so we need to use a weird ass mel command for n in range( tmpIntArray.length() ): removeMultiInstance( weightFmtStr % tmpIntArray[n] ) #at this point using the api or mel to set the data is a moot point... we have the strings already so just use mel for joint, weight in jointsAndWeights: if weight: try: infIdx = jApiIndices[ joint ] except KeyError: try: infIdx = jApiIndices[ joint.split( '|' )[0] ] except KeyError: continue setAttr( weightFmtStr % infIdx, weight ) def mirrorWeightsOnSelected( tolerance=TOL ): selObjs = cmd.ls(sl=True, o=True) #so first we need to grab the geo to save weights for - we save geo for all objects which have #verts selected saveWeights( selObjs, Path('%TEMP%/tmp.weights'), mode=kREPLACE ) loadWeights( cmd.ls(sl=True), Path( '%TEMP%/tmp.weights' ), True, 2, (-1,), True ) def autoSkinToVolumeMesh( mesh, skeletonMeshRoot ): ''' given a mesh and the root node for a hierarchy mesh volumes, this function will create a skeleton with the same hierarchy and skin the mesh to this skeleton using the mesh volumes to determine skin weights ''' #grab a list of meshes under the hierarchy - we need to grab this geo, parent it to a skeleton and transfer defacto weighting to the given mesh volumes = listRelatives( skeletonMeshRoot, ad=True, type='mesh', pa=True ) #now generate the skeleton transforms = removeDupes( listRelatives( volumes, p=True, type='transform', pa=True ) or [] ) jointRemap = {} for t in transforms: select( cl=True ) jName = '%s_joint' % t if objExists( jName ): jName += '#' j = joint( n=jName ) jointRemap[ t ] = j #now do parenting for t, j in jointRemap.iteritems(): tParent = listRelatives( t, p=True, pa=True ) if tParent: tParent = tParent[0] jParent = jointRemap.get( tParent, None ) else: jParent = None if jParent is not None: parent( j, jParent ) #now do positioning for t in api.sortByHierarchy( transforms ): j = jointRemap[ t ] pos = xform( t, q=True, ws=True, rp=True ) move( pos[0], pos[1], pos[2], j, ws=True, rpr=True ) #duplicate the geometry and parent the geo to the joints in the skeleton we just created - store the duplicates so we can delete them later dupes = [] for t, j in jointRemap.iteritems(): dupe = apiExtensions.asMObject( duplicate( t, returnRootsOnly=True, renameChildren=True )[0] ) children = listRelatives( dupe, type='transform', pa=True ) or [] if children: delete( children ) parent( dupe, j ) dupes.append( dupe ) f = saveWeights( map( str, dupes ) ) loadWeights( [mesh], f, usePosition=True, tolerance=0.5, averageVerts=True, jointNameRemapDict=jointRemap ) delete( dupes ) return jointRemap def transferSkinning( sourceMesh, targetMesh ): sourceSkinCluster = api.mel.findRelatedSkinCluster( sourceMesh ) if not sourceSkinCluster: raise SkeletonError( "Cannot find a skin cluster on %s" % sourceMesh ) #if there isn't a skin cluster already, create one targetSkinCluster = api.mel.findRelatedSkinCluster( targetMesh ) if not targetSkinCluster: influences = skinCluster( sourceSkinCluster, q=True, inf=True ) targetSkinCluster = skinCluster( targetMesh, influences, toSelectedBones=True )[0] copySkinWeights( sourceSkin=sourceSkinCluster, destinationSkin=targetSkinCluster, noMirror=True, surfaceAssociation='closestPoint', smooth=True ) return targetSkinCluster #end
Python
from maya.cmds import * from baseMelUI import * from common import printWarningStr from control import attrState, LOCK_HIDE, Axis from mayaDecorators import d_unifyUndo from names import camelCaseToNice from apiExtensions import getNodesCreatedBy class DynamicChain(object): ''' provides a high level interface to interact with existing dynamic chain setups in the current scene to create a new dynamic chain instance, use DynamicChain.Create to instantiate a previously created chain use DynamicChain( dynamicChainNode ) the dynamic chain node simply describes what nodes to create the dynamic chain on, and provide a place to store persistent properties. To build the dynamic chain setup you need to call dynChain.construct() on a DynamicChain instance. Similarly you can turn a dynamic chain "off" by calling dynChain.mute() ''' #used to identify the sets used by this tool to describe the dynamic chain setups SET_NODE_IDENTIFIER = 'zooDynamicChain' @classmethod @d_unifyUndo def Create( cls, objs ): ''' constructs a new DynamicChain instance NOTE: this only creates the description of the dynamic chain - if you want the dynamic chain to be "turned on", you'll need to call construct() on the instance returned ''' if not objs: raise ValueError( "Must provide a list of objects to construct the DynamicChain on" ) node = sets( empty=True, text=cls.SET_NODE_IDENTIFIER ) node = rename( node, '%s_dynChain#' % objs[0].split( '|' )[-1].split( ':' )[-1] ) addAttr( node, ln='transforms', at='message', indexMatters=True, multi=True ) for n, obj in enumerate( objs ): connectAttr( '%s.message' % obj, '%s.transforms[%d]' % (node, n) ) #add attributes to the set node - adding them to the set means user set attributes are preserved across muting and unmuting of the chain addAttr( node, ln='stiffness', at='double', min=0, max=1, dv=0.15, keyable=True ) addAttr( node, ln='lengthFlex', at='double', min=0, max=1, dv=0, keyable=True ) addAttr( node, ln='damping', at='double', min=0, max=25, dv=0, keyable=True ) addAttr( node, ln='drag', at='double', min=0, max=1, dv=0.1, keyable=True ) addAttr( node, ln='friction', at='double', min=0, max=1, dv=0.5, keyable=True ) addAttr( node, ln='gravity', at='double', min=0, max=10, dv=1, keyable=True ) addAttr( node, ln='turbStrength', at='double', min=0, max=1, dv=0, keyable=True ) addAttr( node, ln='turbFreq', at='double', min=0, max=2, dv=0.2, keyable=True ) addAttr( node, ln='turbSpeed', at='double', min=0, max=2, dv=0.2, keyable=True ) addAttr( node, ln='proxyRoot', at='message' ) self = cls( node ) return self @classmethod def Iter( cls ): ''' iterates over all dynamic chains in the current scene ''' for node in ls( type='objectSet' ): if sets( node, q=True, text=True ) == cls.SET_NODE_IDENTIFIER: yield cls( node ) def __init__( self, container ): self._node = container def getNode( self ): return self._node def getObjs( self ): ''' returns the objects involved in the dynamic chain ''' objs = [] nControls = getAttr( '%s.transforms' % self._node, size=True ) for n in range( nControls ): cons = listConnections( '%s.transforms[%d]' % (self._node, n), d=False ) if cons: objs.append( cons[0] ) return objs def getProxyRoot( self ): ''' returns the ''' cons = listConnections( '%s.proxyRoot' % self._node, d=False ) if cons: return cons[0] return None @d_unifyUndo def construct( self ): ''' builds the actual dynamic hair network ''' setNode = self._node objs = self.getObjs() #before we do anything, check to see whether the selected objects have any incoming connections warnAboutDisconnections = False for obj in objs: #check the object for incoming connections - if it has any, remove them for chan in ('t', 'r'): for ax in Axis.BASE_AXES: cons = listConnections( '%s.%s%s' % (obj, chan, ax), d=False ) if cons: warnAboutDisconnections = True if objectType( cons[0], isAType='animCurve' ): delete( cons[0] ) else: raise TypeError( "The object %s has non anim curve incoming connections - aborting! Please remove connections manually before proceeding" % obj ) if warnAboutDisconnections: printWarningStr( "Some of the objects had incoming connections (probably from animation). These connections have been broken! undo if you want them back" ) #wrap the creation of the nodes in a function - below this we execute this function via a wrapper which returns a list of new nodes created #this is done so we can easily capture the nodes created and store them in the set that describes this dynamic chain def doCreate(): positions = [] for obj in objs: positions.append( xform( obj, q=True, ws=True, rp=True ) ) #the objs may not be in the same hierarchy, so create a proxy chain that IS in a heirarchy proxyJoints = [] for obj in objs: select( cl=True ) j = createNode( 'joint' ) j = rename( j, '%s_dynChainProxy#' % obj.split( ':' )[-1].split( '|' )[-1] ) if proxyJoints: parent( j, proxyJoints[-1] ) delete( parentConstraint( obj, j ) ) proxyJoints.append( j ) #constrain the original to the proxy parentConstraint( j, obj ) #hook up the proxy root to a special message attribute so we can easily find the proxy chain again for things like baking etc... connectAttr( '%s.message' % proxyJoints[0], '%s.proxyRoot' % setNode ) #build a linear curve linearCurve = curve( d=1, p=positions ) linearCurveShape = listRelatives( linearCurve, s=True, pa=True )[0] select( linearCurve ) maya.mel.eval( 'makeCurvesDynamicHairs 1 0 1;' ) #find the dynamic curve shape cons = listConnections( '%s.worldSpace' % linearCurveShape, s=False ) if not cons: printWarningStr( "Cannot find follicle" ) return follicleShape = cons[0] cons = listConnections( '%s.outHair' % follicleShape, s=False ) if not cons: printWarningStr( "Cannot find hair system!" ) return hairSystemNode = cons[0] setAttr( '%s.startFrame' % hairSystemNode, playbackOptions( q=True, min=True ) ) cons = listConnections( '%s.outCurve' % follicleShape, s=False ) if not cons: printWarningStr( "Cannot find out curve!" ) return dynamicCurve = cons[0] dynamicCurveParent = listRelatives( dynamicCurve, p=True, pa=True ) #grab the dynamic curve's shape select( dynamicCurve ) maya.mel.eval( 'displayHairCurves "current" 1;' ) follicle = listRelatives( linearCurve, p=True, pa=True )[0] objParent = listRelatives( objs[0], p=True, pa=True ) if objParent: objParent = objParent[0] parent( follicle, objParent ) parent( proxyJoints[0], objParent ) setAttr( '%s.overrideDynamics' % follicle, 1 ) setAttr( '%s.pointLock' % follicle, 1 ) #hook up all the attributes connectAttr( '%s.stiffness' % setNode, '%s.stiffness' % follicle ) connectAttr( '%s.lengthFlex' % setNode, '%s.lengthFlex' % follicle ) connectAttr( '%s.damping' % setNode, '%s.damp' % follicle ) connectAttr( '%s.drag' % setNode, '%s.drag' % hairSystemNode ) connectAttr( '%s.friction' % setNode, '%s.friction' % hairSystemNode ) connectAttr( '%s.gravity' % setNode, '%s.gravity' % hairSystemNode ) connectAttr( '%s.turbStrength' % setNode, '%s.turbulenceStrength' % hairSystemNode ) connectAttr( '%s.turbFreq' % setNode, '%s.turbulenceFrequency' % hairSystemNode ) connectAttr( '%s.turbSpeed' % setNode, '%s.turbulenceSpeed' % hairSystemNode ) splineIkHandle = ikHandle( sj=proxyJoints[0], ee=proxyJoints[-1], curve=dynamicCurve, sol='ikSplineSolver', ccv=False )[0] #for some reason the dynamic curve gets re-parented by the ikHandle command (weird) so set the parent back to what it was originally parent( dynamicCurve, dynamicCurveParent ) newNodes, returnValue = getNodesCreatedBy( doCreate ) #stuff the nodes created into the set that describes this dynamic chain - just add transform nodes... for aNode in newNodes: if objectType( aNode, isAType='transform' ): sets( aNode, e=True, add=setNode ) @d_unifyUndo def mute( self ): ''' deletes the hair nodes but retains the settings and objects involved in the hair ''' #we need to lock the set node before deleting its contents otherwise maya will delete the set lockNode( self._node, lock=True ) #now delete the set contents delete( sets( self._node, q=True ) ) #finally unlock the node again lockNode( self._node, lock=False ) def getMuted( self ): ''' returns whether this dynamic chain is muted or not ''' return not bool( sets( self._node, q=True ) ) def setMuted( self, state ): if state: self.mute() else: self.construct() @d_unifyUndo def bake( self, keyEveryNthFrame=4 ): ''' if this dynamic chain isn't muted, this will bake the motion to keyframes and mute the dynamic hair keyEveryNthFrame describes how often keys are baked - set to 1 to bake every frame ''' #grab the range timeRange = playbackOptions( q=True, min=True ), playbackOptions( q=True, max=True ) #bake the simulation - NOTE: we DON'T use the keyEveryNthFrame value for the sampleBy arg here because otherwise maya only samples every nth frame which doesn't perform teh simulation properly. yay maya! bakeSimulation( self.getObjs(), t=timeRange, sampleBy=1, preserveOutsideKeys=True, simulation=True, disableImplicitControl=True, sparseAnimCurveBake=True ) #because of the sampling problem above, we now need to respect the user value specified for keyEveryNthFrame manually if keyEveryNthFrame > 1: pass #finally turn this chain off... self.mute() @d_unifyUndo def delete( self ): ''' deletes the dynamic chain ''' nodesInSet = sets( self._node, q=True ) or [] for node in nodesInSet: if objExists( node ): delete( node ) #the node shouldn't actually exist anymore - maya should have deleted it automatically after the last object in it was deleted. but #in the interests of thoroughness, lets make sure. who knows what sort of crazy corner cases exist if objExists( self._node ): #check to see if the set node is referenced - if it is, it will be un-deletable if not referenceQuery( self._node, inr=True ): delete( self._node ) class DynamicChainScrollList(MelObjectScrollList): def itemAsStr( self, item ): isMuted = item.getMuted() if isMuted: return '[ muted ] %s' % item.getNode() return item.getNode() class DynamicChainEditor(MelColumnLayout): def __init__( self, parent ): self._chain = None MelColumnLayout.__init__( self, parent ) def setChain( self, dynamicChain ): self.clear() self._chain = dynamicChain if dynamicChain is None: return dynChainNode = dynamicChain.getNode() MelLabel( self, l='Editing Dynamic Chain: %s' % dynChainNode ) MelSeparator( self, h=15 ) attrs = listAttr( dynChainNode, k=True ) or [] for attr in attrs: attrpath = '%s.%s' % (dynChainNode, attr) niceAttrName = camelCaseToNice( attr ) #query the attribute type and build UI for the types we care about presenting to the user attrType = getAttr( attrpath, type=True ) ui = None if attrType == 'bool': ui = MelCheckBox( self, l=niceAttrName ) elif attrType == 'double': min, max = addAttr( attrpath, q=True, min=True ), addAttr( attrpath, q=True, max=True ) ui = LabelledFloatSlider( self, min, max, ll=niceAttrName, llw=65 ).getWidget() if ui is None: continue connectControl( ui, attrpath ) MelSeparator( self, h=15 ) hLayout = MelHSingleStretchLayout( self ) lbl = MelLabel( hLayout, l='Key Every N Frames' ) self.UI_nFrame = MelIntField( hLayout, v=4, min=1, max=10, step=1 ) self.UI_bake = MelButton( hLayout, l='Bake To Keys', c=self.on_bake ) hLayout( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) ) hLayout.padding = 10 hLayout.setStretchWidget( self.UI_bake ) hLayout.layout() ### EVENT HANDLERS ### def on_bake( self, *a ): if self._chain: self._chain.bake( self.UI_nFrame.getValue() ) self.sendEvent( 'on_mute' ) class DynamicChainLayout(MelHSingleStretchLayout): def __init__( self, parent ): vLayout = MelVSingleStretchLayout( self ) self.UI_dynamicChains = DynamicChainScrollList( vLayout ) self.UI_dynamicChains.setWidth( 175 ) self.UI_dynamicChains.setChangeCB( self.on_chainListSelectionChange ) self.UI_create = MelButton( vLayout, l='Create Chain From Selection', c=self.on_create ) self.UI_mute = MelButton( vLayout, l='Toggle Mute On Highlighted', c=self.on_mute ) MelSeparator( vLayout, h=15 ) self.UI_delete = MelButton( vLayout, l='Delete Highlighted', c=self.on_delete ) vLayout.padding = 0 vLayout.setStretchWidget( self.UI_dynamicChains ) vLayout.layout() self.UI_editor = DynamicChainEditor( self ) self.padding = 10 self.expand = True self.setStretchWidget( self.UI_editor ) self.layout() self.populate() #hook up callbacks self.setSelectionChangeCB( self.on_sceneSelectionChange ) self.setSceneChangeCB( self.on_sceneChange ) #run the selection callback to update the UI self.on_sceneSelectionChange() def populate( self ): initialSelection = self.UI_dynamicChains.getSelectedItems() self.UI_dynamicChains.clear() chains = list( DynamicChain.Iter() ) for dynamicChain in chains: self.UI_dynamicChains.append( dynamicChain ) if initialSelection: if initialSelection[0] in self.UI_dynamicChains: self.UI_dynamicChains.selectByValue( initialSelection[0], False ) elif chains: self.UI_dynamicChains.selectByValue( chains[0], False ) #run the highlight callback to update the UI self.on_chainListSelectionChange() ### EVENT HANDLERS ### def on_sceneSelectionChange( self, *a ): areNodesSelected = bool( ls( sl=True, type='transform' ) ) self.UI_create.setEnabled( areNodesSelected ) def on_sceneChange( self, *a ): self.populate() def on_chainListSelectionChange( self, *a ): sel = self.UI_dynamicChains.getSelectedItems() areItemsSelected = bool( sel ) if areItemsSelected: self.UI_editor.setChain( sel[0] ) else: self.UI_editor.setChain( None ) #set enable state on UI that is sensitive to whether we have highlighted items in the dynamic chain list self.UI_mute.setEnabled( areItemsSelected ) self.UI_delete.setEnabled( areItemsSelected ) def on_create( self, *a ): selection = ls( sl=True, type='transform' ) dynamicChain = DynamicChain.Create( selection ) dynamicChain.setMuted( False ) self.populate() self.UI_dynamicChains.selectByValue( dynamicChain, True ) def on_mute( self, *a ): sel = self.UI_dynamicChains.getSelectedItems() if sel: muteStateToSet = not sel[0].getMuted() for s in sel: s.setMuted( muteStateToSet ) self.populate() def on_delete( self, *a ): sel = self.UI_dynamicChains.getSelectedItems() if sel: for s in sel: s.delete() self.populate() class DynamicChainWindow(BaseMelWindow): WINDOW_NAME = 'zooDynamicChainMaker' WINDOW_TITLE = 'Dynamic Chain Maker' DEFAULT_MENU = None DEFAULT_SIZE = 500, 325 FORCE_DEFAULT_SIZE = True def __init__( self ): DynamicChainLayout( self ) self.show() #end
Python
import vectors, cPickle, names, math, time, datetime, mayaVectors, api import exportManagerCore import maya.cmds as cmd import maya.OpenMaya as OpenMaya import maya.OpenMayaAnim as OpenMayaAnim import bisect, os g_defaultKeyUtilsPickle = 'd:/temp.pickle' g_validWorldAttrs = ('translateX','translateY','translateZ','rotateX','rotateY','rotateZ') mel = api.mel PRIMARY_NAMES = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'] PRIMARY_ROTATIONS = [-45, -90, -135, 180, 135, 90, 45] PRIMARY_SPEEDS = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] PRIMARY_START_FRAMES = [60, 120, 180, 240, 300, 360, 420] #SECONDARY_ROTATIONS = [-45, -90, -135, -180, 135, 90, 45] #SECONDARY_SPEEDS = [0.85, 0.68, 0.85, 0.6, 0.85, 0.68, 0.85] #SECONDARY_STARTS = [ 60, 120, 180, 240, 300, 360, 420 ] #SECONDARY_NAMES = [ 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'] class MatrixAtTime(mayaVectors.MayaMatrix): #simply stores time along with a matrix... def __init__( self, values=(), size=4, time=None ): if isinstance(values,MatrixAtTime): time = values.time values = values.as_list() mayaVectors.MayaMatrix.__init__(self,values,4) self.time = time #this decorator turns off all the "slow things" when doing time change operations... def noUpdate(f): def actualFunc(*args): start = time.clock() initialAutoKeyState = cmd.autoKeyframe(q=True,state=True) cmd.autoKeyframe(state=False) api.mel.zooAllViews(0) retVal = f(*args) api.mel.zooAllViews(1) cmd.autoKeyframe(state=initialAutoKeyState) print 'time taken',time.clock()-start,'secs' return retVal return actualFunc class Key(object): '''this is simply a convenient abstraction of a key object in maya - which doesn't really exist... working with key data is a pain in the ass. you can specify either a key time or a key index when creating an instance. if both are specifed, index is used. if time is specified, and there is no key at that time, a phantom key is created using the curve value at that point - the index is set to -1 in this case, and tangent data is guessed''' def __init__( self, obj=None, attr=None, time=None, value=None, idx=None, populateTangents=True ): #if the attrpath doesn't exist, then just create an empty key instance self.idx = idx self.obj, self.attr, self.time, self.value = obj, attr, time, value self.iw, self.ow, self.ia, self.oa = 1.0, 1.0, 0, 0 self.itt, self.ott, self.lock = 'linear', 'linear', True if obj is None or attr is None: return #make sure the attr name is the long version of the name, its too annoying to have to deal with shortnames AND long names... #self.attr = cmd.attributeQuery(self.attr,longName=True,node=self.obj) #self.attrShort = cmd.attributeQuery(self.attr,shortName=True,node=self.obj) #populating tangents is slow - so only do it when required if populateTangents: self.populateTangents() def copy( self ): new = self.__class__() new.idx = self.idx new.obj, new.attr, new.time, new.value = self.obj, self.attr, self.time, self.value new.iw, new.ow, new.ia, new.oa = self.iw, self.ow, self.ia, self.oa new.itt, new.ott, new.lock = self.itt, self.ott, self.lock return new def get_attrpath( self ): return '%s.%s'%(self.obj,self.attr) attrpath = property(get_attrpath) def populateTangents( self ): #is there a key at the time? attrpath = self.attrpath if cmd.keyframe(attrpath,time=(keyTime,),query=True,keyframeCount=True): self.value = cmd.keyframe(attrpath,time=(keyTime,),query=True,valueChange=True)[0] self.iw,self.ow,self.ia,self.oa = cmd.keyTangent(attrpath,time=(keyTime,),query=True,inWeight=True,outWeight=True,inAngle=True,outAngle=True) self.itt,self.ott = cmd.keyTangent(attrpath,time=(keyTime,),query=True,inTangentType=True,outTangentType=True) self.lock = cmd.keyTangent(attrpath,time=(keyTime,),query=True,lock=True)[0] #this is purely 'clean up after maya' code. for whatever reason maya will return a tangent type of "fixed" even though its a completely invalid tangent type... not sure what its supposed to map to, so I'm just assuming spline if self.itt == 'fixed': self.itt = 'spline' if self.ott == 'fixed': self.ott = 'spline' else: self.idx = self.get_index() self.value = cmd.keyframe(attrpath,time=(self.time,),query=True,eval=True,valueChange=True) index = self.idx previousOutTT = None previousOutTW = None nextInTT = None nextInTW = None if index > 1: previousOutTT = cmd.keyTangent(attrpath,index=(index-1,),query=True,outTangentType=True) previousOutTW = cmd.keyTangent(attrpath,index=(index-1,),query=True,outWeight=True) else: previousOutTT = cmd.keyTangent(attrpath,index=(index,),query=True,outTangentType=True) previousOutTW = cmd.keyTangent(attrpath,index=(index,),query=True,outWeight=True) if index < cmd.keyframe(self.attr,query=True,keyframeCount=True): nextInTT = cmd.keyTangent(attrpath,index=(index+1,),query=True,inTangentType=True) nextInTW = cmd.keyTangent(attrpath,index=(index+1,),query=True,inWeight=True) else: nextInTT = cmd.keyTangent(attrpath,index=(index,),query=True,inTangentType=True) nextInTW = cmd.keyTangent(attrpath,index=(index,),query=True,inWeight=True) #now average the tangents self.iw = self.ow = (previousOutTW + nextInTW )/2 def __str__( self ): return '%.2f'% (self.time,) def __repr__( self ): return self.__str__() def __cmp__( self, other, tolerance=1e-4 ): if isinstance(other,Key): other = other.time if abs(self.time-other) <= tolerance : return 0 if self.time - other < 0: return -1 return 1 def offset( self, amount ): #time offsets the channel by a given time delta self.time += amount def get_index( self ): '''returns the key object's index''' return cmd.keyframe(self.attr,time=(":%f"+self.time,),query=True,keyframeCount=True)-1 class Channel(object): '''a channel is simply a list of key objects with some convenience methods attached''' def __init__( self, obj=None, attr=None, start=None, end=None, populateTangents=True ): self.obj = obj self.attr = attr self.weighted = True self.keys = [] #unless an attrpath has been specified, we're done... if obj is None or attr is None: return attrpath = '.'.join((obj,attr)) if start is None: #get the timecount of the first key start = cmd.keyframe(attrpath,index=(0,),query=True)[0] if end is None: #get the timecount of the first key lastKeyIdx = cmd.keyframe(attrpath,keyframeCount=True,query=True)-1 end = cmd.keyframe(attrpath,index=(lastKeyIdx,),query=True)[0] self.attr = str( cmd.attributeQuery(self.attr,longName=True,node=self.obj) ) self.attrShort = str( cmd.attributeQuery(self.attr,shortName=True,node=self.obj) ) self.weighted = cmd.keyTangent(attrpath,query=True,weightedTangents=True) if self.weighted == 1: self.weighted = True else: self.weighted = False if cmd.objExists(attrpath): times = cmd.keyframe(attrpath,time=(start,end),query=True) values = cmd.keyframe(attrpath,time=(start,end),query=True,vc=True) #if there are no keys - bail if times is None: return self.keys = [Key(obj,attr,time=k,value=v,populateTangents=False) for k,v in zip(times,values)] if populateTangents: #querying heaps of tangent data at once is much more efficient than throwing a query for #each key created - so although uglier, its quite significantly faster... iws = cmd.keyTangent(attrpath,time=(start,end),query=True,iw=True) ows = cmd.keyTangent(attrpath,time=(start,end),query=True,ow=True) ias = cmd.keyTangent(attrpath,time=(start,end),query=True,ia=True) oas = cmd.keyTangent(attrpath,time=(start,end),query=True,oa=True) itts = cmd.keyTangent(attrpath,time=(start,end),query=True,itt=True) otts = cmd.keyTangent(attrpath,time=(start,end),query=True,ott=True) locks = cmd.keyTangent(attrpath,time=(start,end),query=True,lock=True) #remove all instances of 'fixed' tangent types. maya will return a type of fixed, but it throws an exception if #you try to set a tangent type of fixed... nice... try: while True: itts.remove('fixed') except ValueError: pass try: while True: otts.remove('fixed') except ValueError: pass # for key,iw,ow,ia,oa,itt,ott,lock in zip(self.keys,iws,ows,ias,oas,itts,otts,locks): key.iw,key.ow,key.ia,key.oa,key.itt,key.ott,key.lock = iw,ow,ia,oa,itt,ott,lock self.keys.sort() @classmethod def FromChannel( cls, channel, keys=None ): new = cls() new.obj = channel.obj new.attr = channel.attr new.attrShort = channel.attrShort new.weighted = channel.weighted if keys is None: new.keys = [key.copy() for key in channel.keys] else: new.keys = [key.copy() for key in keys] return new def copy( self ): return Channel.FromChannel(self) def get_attrpath( self ): return '%s.%s'%(self.obj,self.attr) attrpath = property(get_attrpath) def get_start( self ): keyTimes = [key.time for key in self.keys] if len(keyTimes): return min(keyTimes) start = property(get_start) def get_end( self ): keyTimes = [key.time for key in self.keys] if len(keyTimes): return max(keyTimes) end = property(get_end) def get_values( self ): values = [] for key in self.keys: values.append(key.value) return values values = property(get_values) def __str__( self ): return '%s %s'%(self.attrpath, str(self.keys)) def __repr__( self ): return self.__str__() def __nonzero__( self ): return bool(self.keys) def __add__( self, other ): assert isinstance(other,Channel) newChannel = self.copy() #so when adding channels, if there are two keys on the same frame, their values get added together #TODO: if not, then find surrounding keys (if any) and do a value lerp to add to the key value for key in other.keys: keyAtTime = self[key.time] if keyAtTime: keyAtTime.keys[0].value += key.value else: newChannel.keys.append(key) newChannel.keys.sort() return newChannel def __getitem__( self, timeValue ): '''so this returns a slice based on a time value NOT and index. NOTE: the slice step is ignored - it doesn't really make any sense''' if isinstance(timeValue,slice): start_idx = bisect.bisect_left(self.keys,timeValue.start) end_idx = bisect.bisect(self.keys,timeValue.stop) keys = self.keys[start_idx:end_idx] newChannel = Channel.FromChannel(self,keys) return newChannel try: idx = bisect.bisect_left(self.keys,timeValue) key = self.keys[idx] if abs(timeValue-key.time)<=1e-4: return Channel.FromChannel(self,[key]) except IndexError: return Channel.FromChannel(self,[]) def __len__( self ): return len(self.keys) def offset( self, amount ): #time offsets the channel by a given time delta [key.offset(amount) for key in self.keys] def transform( self, transformFunction ): #transforms all key values by the given transform function. the first arg passed to the transform function is the key #the return value should also be a key object self.keys = [transformFunction(key) for key in self.keys] def applyToObj( self, obj, applyAsWorld=False, clearFirst=False ): '''applies the current channel to a given attrpath''' tgtAttrpath = '.'.join((obj,self.attr)) if not cmd.objExists(tgtAttrpath): return if clearFirst: if self.start is not None: cmd.cutKey(tgtAttrpath,t=(self.start,self.end),cl=True) if applyAsWorld and self.hasWorld: #apply as world - NOT DONE YET for key in self.keys: cmd.setKeyframe(tgtAttrpath,time=(key.time,),value=key.value,inTangentType=key.itt,outTangentType=key.ott) cmd.keyTangent(tgtAttrpath,time=(key.time,),edit=True,inWeight=key.iw,outWeight=key.ow,inAngle=self.ia,outAngle=self.oa) else: #set this initial dummy keyframe so we can set the curve's (whcih may not exist) weightedness if len( self.keys ): cmd.setKeyframe(tgtAttrpath,time=(self.keys[0].time,)) cmd.keyTangent(tgtAttrpath,edit=True,weightedTangents=self.weighted) #if self.weighted: print "hi i'm weighting ur tangents..." for key in self.keys: cmd.setKeyframe(tgtAttrpath,time=(key.time,),value=key.value,inTangentType=key.itt,outTangentType=key.ott) #cmd.keyTangent(tgtAttrpath,time=(key.time,),edit=True,lock=key.lock,inWeight=key.iw,outWeight=key.ow,inAngle=key.ia,outAngle=key.oa) def getTurningPoints( self ): '''returns a list of keys that are turning points''' if len(self.keys) < 3: return [] turningPoints = [] keyIter = iter(self.keys) prevKey = keyIter.next() curKey = keyIter.next() nextKey = keyIter.next() while True: try: prevValue = prevKey.value - curKey.value nextValue = nextKey.value - curKey.value if ( prevValue<0 and nextValue<0 ) or ( prevValue>0 and nextValue>0 ): #in this case nextKey is a turning point turningPoints.append(curKey) prevKey = curKey curKey = nextKey nextKey = keyIter.next() except StopIteration: break return turningPoints def keyReduce( self ): #get the nodeType of the animCurve driving this channel animCurve = cmd.listConnections('%s.%s'%(self.obj,self.attr),type='animCurve',destination=False)[0] nodeType = cmd.nodeType(animCurve) #create an array to hold the "reduced" set of keys to create - start/end and turning points are mandatory newKeys = [self.keys[0]] + self.getTurningPoints() + [self.keys[-1]] #create the new animCurve - we do this because asking maya to query the interpolation between keys is way easier than doing it via script reduce = cmd.createNode(nodeType) for key in newKeys: cmd.setKeyframe(reduce,time=(key.time,),value=key.value,inTangentType='linear',outTangentType='linear') # return reduce class Clip(object): '''creates a convenient abstraction of a collection of animation data on multiple channels. supports adding, removing etc... if start and end aren't specified, it uses the entire range. if channels isn't specified, assumes all keyable channels''' def __init__( self, obj=None, start=None, end=None, channels=None, populateTangents=True ): #create object attrs self.obj = obj self.channels = {} self.world = [] if obj is None: return #if channels is the default value, assume all keyable channels on the node if channels == None: attributes = cmd.listAttr(obj,keyable=True,multi=True,scalar=True) channels = [str(a) for a in attributes if cmd.keyframe(obj+'.'+a,query=True,keyframeCount=True)] for channel in channels: newChannel = Channel(obj,channel,start,end,populateTangents) self.channels[channel] = newChannel @classmethod def FromClip( cls, clip, channels=None, world=None ): new = cls() new.obj = clip.obj if channels is None: for name,channel in clip.channels.iteritems(): new.channels[name] = channel.copy() else: for name,channel in channels.iteritems(): new.channels[name] = chan.copy() if world is None: new.world = [mat.copy() for mat in clip.world] else: new.world = [mat.copy() for mat in world] return new def copy( self ): return Clip.FromClip(self) def __str__( self ): asStr = '\n'.join( map(str,self.channels.values()) ) return asStr def __getattr__( self, attr ): return self.channels[attr] def __contains__( self, item ): return item in self.channels def get_start( self ): starts = [] for channel in self.channels: starts.append(channel.start) return min(starts) start = property(get_start) def get_end( self ): ends = [] for channel in self.channels: ends.append(channel.end) return max(ends) end = property(get_end) def _hasWorld( self ): return not( not self.world ) hasWorld = property(_hasWorld) def __add__( self, other ): assert isinstance(other,Clip) newClip = self.copy() for name,channel in newClip.channels.iteritems(): if name in other.channels: newClip.channels[name] = newClip[name]+other[name] #deal with world matricies - so if two matricies exist on the same frame, then we need to merge them if other.world: newWorld = [] for matB in other.world: matA = None for m in newClip.world: if m.time == matB.time: matA = m if matA is not None: #in this case, we need to merge the two matricies together... posA = matA.pos posB = matB.pos newPos = (posA+posB)/2 quatA = vectors.Quaternion(matA) quatB = vectors.Quaternion(matB) newQuat = (quatA/2)*(quatB/2) mergedMat = MatrixAtTime(newQuat,time=matB.time) mergedMat.pos = newPos newWorld.append( mergedMat ) else: newWorld.append(matB) newClip.world = newWorld return newClip def __getitem__( self, item ): #so this returns a slice based on a time value NOT and index. NOTE: the slice step is ignored - it #doesn't really make any sense if isinstance(item,basestring): return self.channels[item] newChannels = {} for name,channel in self.channels.iteritems(): newChannels[name] = channel[item] worldTimes = [mat.time for mat in self.world] if isinstance(item,slice): start_idx = bisect.bisect_left(worldTimes,item.start) end_idx = bisect.bisect(worldTimes,item.stop) newWorld = worldTimes[start_idx:end_idx] newClip = Clip.FromClip(self,newChannels,newWorld) return newClip newWorld = [] if self.hasWorld: idx = bisect.bisect_left(worldTimes,item) newWorld.append(self.world[idx]) abs(item-newWorld[0])<=1e-4 return Clip.FromClip(self,newChannels,newWorld) def __len__( self ): return len(self.keys) def offset( self, amount ): #time offsets the channel by a given time delta [channel.offset(amount) for channel in self.channels.values()] for mat in self.world: mat.time += amount def transform( self, transformFunction ): #transforms all key values by the given transform function. the first arg passed to the transform function is the key [channel.transform(transformFunction) for channel in self.channels.values()] def get_channels( self, channelListToGet ): resultingChannels = [] for name in channelListToGet: resultingChannels.append(getattr(self,name)) return resultingChannels def listKeysInOrder( self, channels=None ): '''returns a list of the clip's keys in ascending temporal order''' if not channels: channels = self.channels #do a DSU sort... keys = [(key.time,key) for key in self.keys] keys.sort() keys = [x[1] for x in keys] return keys keys = property(listKeysInOrder) def as_frames( self, channels=None ): '''bundles the keys in this channel into groups of unique times - we call these frames. ie: each frame has one or more keys at that time and ONLY that time return value is a list of lists (a list of frames). each frame contains all the keys at that time''' keys = self.listKeysInOrder(channels) prevTime = keys[0].time frames = [(prevTime,[keys[0]])] curList = frames[0][1] for key in keys: if prevTime != key.time: prevTime = key.time nextFrame = (prevTime,[]) frames.append(nextFrame) curList = nextFrame[1] curList.append(key) return frames frames = property(as_frames) def as_keys( self ): keys = [] for channel in self.channels.values(): keys += channel.keys return keys keys = property(as_keys) def get_times( self, channelStrs=None ): #returns a set of time values for all keys in this clip - optionally only on a given list of channels if channelStrs is None: channelStrs = self.channels.keys() #NOTE: channels is a dict times = set() for channelStr in channelStrs: if channelStr not in self: continue for key in self[channelStr].keys: times.add( key.time ) return times def applyToObj( self, obj=None, applyAsWorld=False, clearFirst=False ): '''applies the current clip to an object - if the animation is being applied as world space, first check to make sure the world space animation for the clip exists. then separate the transform channels out of the channels list and apply them as world space data. then we need to apply the rest of the channels as per normal''' if obj is None: obj = self.obj if applyAsWorld and self.hasWorld: for matrix in self.world: cmd.currentTime(matrix.time) tfn = OpenMaya.MFnTransform( api.getMDagPath(obj) ) tfn.set( OpenMaya.MTransformationMatrix( key[0] ) ) '''nonTransformChannels = [] for channel in self.channels: if channel.attr not in g_validWorldAttrs: nonTransformChannels.append(channel) frames = self.as_frames(transformChannels) for channel in self.world: tgtAttrpath = obj +'.'+ channel.attr channel.applyToObj(obj,applyAsWorld) #run a euler filter over the resulting rotation animation - converting to world space #rotations often causes all sorts of nasty euler flips maya.mel.eval('filterCurve %s.rx %s.ry %s.rz;'%(obj,obj,obj)) for channel in transformChannels: channel.applyToObj(obj)''' else: for channel in self.channels.values(): channel.applyToObj(obj,clearFirst=clearFirst) def populateWorld( self, time=None ): if time is None: time = cmd.currentTime(q=True) mat = MatrixAtTime.FromObject(self.obj,True) mat.time = time self.world.append(mat) @noUpdate def getWorld( self ): '''saves world space matricies for each animation frame in the clip - ie for each transform key a world space matrix is saved in the self.world list''' orgTime = cmd.currentTime(q=True) for time,keys in self.frames: cmd.currentTime(time) self.populateWorld(time) cmd.currentTime(orgTime) #restore time class Animation(object): def __init__( self, objs=None, start=None, end=None, channels=None ): self.clips = {} #we need to store objs in a list so we can preserve ordering - when re-applying an animation clip back to a collection of objects, we don't want to have to worry about a mapping - hence ordering is important self.objs = objs if objs is not None: for obj in objs: self.clips[obj] = Clip(obj,start,end,channels) @classmethod def FromAnimation( cls, animation, clips=None ): new = cls() if clips is None: for name,clip in animation.clips.iteritems(): new.clips[name] = clip.copy() else: for name,clip in clips.iteritems(): new.clips[name] = clip.copy() return new def copy( self ): return Animation.FromAnimation(self) def __str__( self ): asStr = '\n'.join( map(str,self.clips.values()) ) return asStr def __getattr__( self, attr ): return self.clips[attr] def __getitem__( self, item ): if isinstance(item,basestring): return self.clips[item] newClips = {} for name,clip in self.clips.iteritems(): newClips[name] = clip[item] return Animation.FromAnimation(self,newClips) def __add__( self, other ): assert isinstance(other,Animation) newAnim = self.copy() for obj,clip in self.clips.iteritems(): if obj in other.clips: newAnim.clips[obj] = newAnim[obj] + other[obj] return newAnim def __contains__( self, item ): return item in self.clips def get_start( self ): starts = [] for clip in self.clips: starts.append(clip.start) return min(starts) start = property(get_start) def get_end( self ): ends = [] for clip in self.clips: ends.append(channel.end) return max(ends) end = property(get_end) def _hasWorld( self ): return not( not self.world ) hasWorld = property(_hasWorld) def offset( self, amount ): [clip.offset(amount) for clip in self.clips.values()] def transform( self, transformFunction ): #transforms all key values by the given transform function. the first arg passed to the transform function is the key [clip.transform(transformFunction) for clip in self.clips] def get_times( self, channels=None ): transformTimes = set() for clip in self.clips.values(): times = clip.get_times(channels) transformTimes = transformTimes.union( times ) transformTimes = list(transformTimes) transformTimes.sort() return transformTimes @noUpdate def getWorld( self, objs=None, channels=None ): clips = self.clips.values() if objs is None else [self.clips[obj] for obj in objs] transformTimes = set() clipTimeSets = [] for clip in clips: times = set( clip.get_times(channels) ) transformTimes = transformTimes.union( times ) clipTimeSets.append( times ) transformTimes = list(transformTimes) transformTimes.sort() orgTime = cmd.currentTime(q=True) for time in transformTimes: cmd.currentTime(time) for clip,clipTimeSet in zip(clips,clipTimeSets): if time not in clipTimeSet: continue clip.populateWorld(time) cmd.currentTime(orgTime) #restore time def applyToObjs( self, objs=None, applyAsWorld=False, clearFirst=False ): if objs is None: for obj,clip in self.clips.iteritems(): clip.applyToObj(obj,applyAsWorld,clearFirst) else: for n,obj in enumerate(objs): self.clips[ self.objs[n] ].applyToObj(obj,applyAsWorld,clearFirst) def write( object, filepath ): sourceSceneData = {} sourceSceneData['file'] = cmd.file(q=True,sn=True) sourceSceneData['mayaVersion'] = cmd.about(version=True) sourceSceneData['datetime'] = datetime.datetime.today() sourceSceneData['env'] = os.environ fileobj = file(filepath,'wb') cPickle.dump( (sourceSceneData, object), fileobj, True ) fileobj.close() def load( filepath ): fileobj = file(filepath,'rb') new = cPickle.load(fileobj) fileobj.close() return new def createCompassRun(): namespace = '' worldSpaceObjs = ['leg_L','leg_R','root','arm_L','arm_R'] def propagateChanges(): pass def generatePrimary( baseStart, baseEnd ): generate( baseStart, baseEnd, PRIMARY_ROTATIONS, PRIMARY_SPEEDS, PRIMARY_START_FRAMES, PRIMARY_NAMES ) def generate( baseStart, baseEnd,\ rotations = PRIMARY_ROTATIONS,\ strideLengthMultipliers = PRIMARY_SPEEDS,\ starts = PRIMARY_START_FRAMES,\ directions = PRIMARY_NAMES ): #determine which ctrl set to use ctrlSet = names.matchNames(['body_ctrls'],cmd.ls(type='objectSet'),threshold=1) if not ctrlSet: raise Exception('control set not found') ctrlSet = ctrlSet[0] ctrls = cmd.sets(ctrlSet,q=True) length = baseEnd-baseStart num = len(rotations) #does the base locomote have an asset? vx = exportManagerCore.ExportManager() baseAsset = vx.exists(start=baseStart,end=baseEnd) infoNode = '' exportSet = '' if len(baseAsset): baseAsset = baseAsset[0] exportSet = baseAsset.obj else: #if it doesn't exist, try and create one infoNodes = cmd.ls(type='vstInfo') candidates = [] for node in infoNodes: if not cmd.referenceQuery(node,inr=True): continue if not cmd.listRelatives(node): continue candidates.append(node) infoNode = candidates[0] exportSet = exportManagerCore.ExportManager.CreateExportSet( [infoNode] ) #now build the actual asset asset = vx.createAsset(exportSet) asset.setAttr('start', baseStart) asset.setAttr('end', baseEnd) asset.setAttr('name', 'N') asset.setAttr('type', exportManagerCore.ExportComponent.kANIM) #grab the list of ctrls we need to actually transform toFind = [ 'upperBodyControl', 'legControl_L', 'legControl_R' ]#, 'armControl_L', 'armControl_R' ] xformCtrls = [ name for name in names.matchNames( toFind, ctrls, parity=True, threshold=0.8 ) if name != '' ] animation = Animation( ctrls, baseStart, baseEnd ) animation.getWorld(xformCtrls,['translateX','translateZ']) #save the animation out - useful for doing deltas later on #write(animation,g_defaultKeyUtilsPickle) #build the rotation axis axis = vectors.Vector([0, 1, 0]) for n in xrange(num): offset = starts[n]-baseStart tmpAnim = animation.copy() tmpAnim.offset( offset ) #convert angles to radians, and do other static calcs angle = rotations[n] angle = math.radians(angle) quat = vectors.Quaternion.AxisAngle( axis, angle ) for ctrl in xformCtrls: clip = tmpAnim[ctrl] #do the actual rotation around Y mats = clip.world translateX = clip.translateX.keys = [] translateZ = clip.translateZ.keys = [] for mat in mats: pos = mat.get_position() pos = pos.rotate(quat) mat[3][:3] = pos translateX.append( Key( time=mat.time, value=pos.x ) ) translateZ.append( Key( time=mat.time, value=pos.z ) ) #now do stride length multiplication strideMult = strideLengthMultipliers[n] if strideMult is not None: def makeShorter( key ): key.value *= strideMult return key clip.translateX.transform(makeShorter) clip.translateZ.transform(makeShorter) tmpAnim.applyToObjs(clearFirst=True) #finally create an asset for the new anim existing = vx.exists( start=starts[n], end=starts[n]+length, name=directions[n] ) if not len(existing): asset = vx.createAsset( exportSet ) asset.setAttr('start', starts[n]) asset.setAttr('end', starts[n]+length) asset.setAttr('name', directions[n]) asset.setAttr('type', exportManagerCore.ExportComponent.kANIM) def motionList( obj, start, end ): #creates a list of positions at each frames over a given time range motion = [] for n in xrange(start,end+1): #add one because this is an inclusive range curX = cmd.keyframe(obj +'.tx',t=(n,),q=True,ev=True)[0] curY = cmd.keyframe(obj +'.ty',t=(n,),q=True,ev=True)[0] curZ = cmd.keyframe(obj +'.tz',t=(n,),q=True,ev=True)[0] motion.append( (curX,curY,curZ) ) return motion def merge( directionAstart, directionAend, directionBstart, newStart ): '''merges two different locomotes together - for example N and E to give a NE locomote''' #determine which ctrl set to use length = directionAend-directionAstart ctrlSet = names.matchNames(['body_ctrls'],cmd.ls(type='objectSet')) if not ctrlSet: raise Exception('control set not found') ctrlSet = ctrlSet[0] ctrls = cmd.sets(ctrlSet,q=True) #deal with the assets for the new animation vx = exportManagerCore.ExportManager() assetA = vx.exists(start=directionAstart,end=directionAend)[0] assetB = vx.exists(start=directionBstart,end=directionBstart+length)[0] exportSet = assetA.obj assetC = vx.exists(start=newStart,end=newStart+length) if not assetC: assetC = vx.createAsset(exportSet) assetC.setAttr('start', newStart) assetC.setAttr('end', newStart+length) assetC.setAttr('name', assetA.name + assetB.name) assetC.setAttr('type', exportManagerCore.ExportComponent.kANIM) #now start building the animations animationA = Animation(ctrls,directionAstart,directionAend) animationB = Animation(ctrls,directionBstart,directionBstart+length) animationB.offset(-directionBstart+directionAstart) animationC = animationA+animationB animationC.offset(newStart) #grab the list of ctrls we need to actually transform toFind = ['upperBodyControl','legControl_L','legControl_R'] xformCtrls = [name for name in names.matchNames(toFind,ctrls,parity=True,threshold=0.8) if name != ''] for ctrl in xformCtrls: motionA = motionList(ctrl,directionAstart,directionAend) motionB = motionList(ctrl,directionBstart,directionBstart+length) #make the time zero based times = [int(time)-newStart for time in animationC[ctrl].get_times(channels=['translateX','translateZ'])] times.sort() print times,len(motionA),len(motionB) for time in times: print motionA[time],motionB[time] newPos = vectors.Vector(motionA[time]) + vectors.Vector(motionB[time]) newPos *= 0.70710678118654757 #= math.cos(45degrees) tx = animationC[ctrl].translateX[time] tz = animationC[ctrl].translateZ[time] if tx: tx.keys[0] = newPos.x if tz: tz.keys[0] = newPos.z animationC.applyToObjs() #end
Python
from baseSkeletonBuilder import * class Hand(SkeletonPart): HAS_PARITY = True AUTO_NAME = False #this part will handle its own naming... #odd indices are left sided, even are right sided FINGER_IDX_NAMES = ( 'Thumb', 'Index', 'Mid', 'Ring', 'Pinky', 'Sixth' 'Seventh', 'Eighth', 'Ninth', 'Tenth' ) PLACER_NAMES = FINGER_IDX_NAMES def getParity( self ): ''' the parity of a hand comes from the limb its parented to, not the idx of the finger part itself... ''' parent = self.getParent() try: #if the parent has parity use it parentPart = SkeletonPart.InitFromItem( parent ) except SkeletonError: #otherwise use the instance's index for parity... return super( self, Hand ).getParity() return Parity( parentPart.getParity() ) def iterFingerChains( self ): ''' iterates over each finger chain in the hand - a chain is simply a list of joint names ordered hierarchically ''' for base in self.bases: children = listRelatives( base, ad=True, path=True, type='joint' ) or [] children = [ base ] + sortByHierarchy( children ) yield children @classmethod def _build( cls, parent=None, fingerCount=5, fingerJointCount=3, **kw ): idx = Parity( kw[ 'idx' ] ) partScale = kw[ 'partScale' ] parent = getParent( parent ) parentPart = SkeletonPart.InitFromItem( parent ) #try to determine a "parity index" based on the parent part. Ideally we want to inherit the parity of the parent part #instead of from this part's index limbIdx = 0 if parentPart.hasParity(): limbIdx = parentPart.getParity() #if the parent part has no parity, then use the instance's index for parity... else: limbIdx = self.getParity() #for the first two hands this is an empty string - but for each additional hand pair, this is incremented. ie the #second two hands are called Hand1, the next two hands are called Hand2 etc... typePairCountStr = str( idx/2 ) if idx > 1 else '' minPos, maxPos = -cls.PART_SCALE / 25.0, cls.PART_SCALE / 25.0 posRange = float( maxPos - minPos ) allJoints = [] length = partScale / 3 / fingerJointCount lengthInc = cls.ParityMultiplier( limbIdx ) * (length / fingerJointCount) limbName = Parity.NAMES[ limbIdx ] for nameIdx in range( fingerCount ): fingerName = cls.FINGER_IDX_NAMES[ nameIdx ] prevParent = parent for n in range( fingerJointCount ): j = createJoint( '%s%s_%d%s' % (fingerName, typePairCountStr, n, limbName) ) cmd.parent( j, prevParent, r=True ) move( lengthInc, 0, 0, j, r=True, os=True ) if n == 0: move( lengthInc, 0, -maxPos + (posRange * nameIdx / (fingerCount - 1)), j, r=True, os=True ) else: setAttr( '%s.ty' % j, lock=True ) allJoints.append( j ) prevParent = j return allJoints def visualize( self ): scale = self.getActualScale() / 1.5 for base in self.bases: plane = polyPlane( w=scale, h=scale / 2.0, sx=1, sy=1, ax=(0, 1, 0), cuv=2, ch=False )[ 0 ] cmd.parent( plane, base, relative=True ) setAttr( '%s.tx' % plane, self.getParityMultiplier() * scale / 2 ) makeIdentity( plane, a=True, t=True ) cmd.parent( listRelatives( plane, shapes=True, pa=True ), base, add=True, shape=True ) delete( plane ) def _align( self, _initialAlign=False ): parity = self.getParity() wrist = self.getParent() parityMult = self.getParityMultiplier() defactoUpVector = rigUtils.getObjectBasisVectors( wrist )[ 2 ] for chain in self.iterFingerChains(): upVector = defactoUpVector #if there are three joints or more in teh chain, try to determine the normal to the plane they live on if len( chain ) >= 3: midJoint = chain[ len( chain ) / 2 ] upVector = getPlaneNormalForObjects( chain[ 0 ], midJoint, chain[ -1 ], defactoUpVector ) #otherwise assume the user has aligned the base joint properly else: upVector = rigUtils.getObjectBasisVectors( chain[ 0 ] )[ BONE_ROTATE_AXIS ] upVector = upVector * parityMult for n, item in enumerate( chain[ :-1 ] ): alignAimAtItem( item, chain[ n+1 ], parity, worldUpVector=upVector ) autoAlignItem( chain[ -1 ], parity, worldUpVector=upVector ) #end
Python
import sys import baseSkeletonBuilder from filesystem import Path from baseSkeletonBuilder import * __author__ = 'mel@macaronikazoo.com' SKELETON_PART_SCRIPT_PREFIX = 'skeletonPart_' _LOAD_ORDER = 'spine', 'head', 'arm', 'hand', 'leg' def _iterSkeletonPartScripts(): for p in sys.path: p = Path( p ) if 'maya' in p: for f in p.files(): if f.hasExtension( 'py' ): if f.name().startswith( SKELETON_PART_SCRIPT_PREFIX ): yield f partModuleNames = [ f.name() for f in _iterSkeletonPartScripts() ] for name in reversed( _LOAD_ORDER ): name = SKELETON_PART_SCRIPT_PREFIX + name if name in partModuleNames: partModuleNames.remove( name ) partModuleNames.insert( 0, name ) for modName in partModuleNames: __import__( modName ) #import skeletonBuilderConversion #skeletonBuilderConversion.convertOldParts() #end
Python
import os from consoleChroma import Good from filesystem import Path, removeDupes from dependencies import generateDepTree, makeScriptPathRelative _THIS_FILE = Path( os.path.abspath( __file__ ) ) _PYTHON_TOOLS_TO_PACKAGE = _THIS_FILE.up() / 'pythonToolsToPackage.txt' _PACKAGE_DIR_NAME = 'zooToolboxPy' _PACKAGE_DIR = _THIS_FILE.up( 2 ) / _PACKAGE_DIR_NAME def cleanPackageDir(): if _PACKAGE_DIR.exists(): _PACKAGE_DIR.delete() _PACKAGE_DIR.create() def buildPackage( dependencyTree=None ): if not _PYTHON_TOOLS_TO_PACKAGE.exists(): raise ValueError( "Cannot find %s file!" % _PYTHON_TOOLS_TO_PACKAGE.name() ) modulesToPackage = [] for toolName in _PYTHON_TOOLS_TO_PACKAGE.read(): if toolName: if toolName.startswith( '#' ): continue elif toolName.startswith( '//' ): continue modulesToPackage.append( toolName ) cleanPackageDir() if dependencyTree is None: dependencyTree = generateDepTree() filesToPackage = [] for moduleName in modulesToPackage: moduleScriptPath = dependencyTree.moduleNameToScript( moduleName ) filesToPackage += dependencyTree.findDependencies( moduleScriptPath, None, False ) if not filesToPackage: return None #remove any duplicate files... filesToPackage = removeDupes( filesToPackage ) #this is a little hacky - but we don't want to re-distribute wingdbstub so lets check to see if its in the list of files for f in filesToPackage: if f.name() == 'wingdbstub': filesToPackage.remove( f ) break print >> Good, "Found dependencies - %d files" % len( filesToPackage ) for f in filesToPackage: relativePath = makeScriptPathRelative( f ) packagedPath = _PACKAGE_DIR / relativePath if len( relativePath ) > 1: packagedPath.up().create() f.copy( packagedPath ) print 'copying ----> %s' % f #now zip up the files into a package cmdStr = '7z a -r ..\\%s\\zooToolBoxPy.7z ..\\%s\\' % (_PACKAGE_DIR_NAME, _PACKAGE_DIR_NAME) os.system( cmdStr ) #now write a simple mel script to load the toolbox UI cmdStr = """global proc zooToolBox() { return; }""" bootstrapMelScript = _PACKAGE_DIR / 'zooToolBox.mel' bootstrapMelScript.write( cmdStr ) if __name__ == '__main__': buildPackage() #end
Python
try: import wingdbstub except ImportError: pass from filesystem import Path from unittest import TestCase, TestResult from maya import cmds as cmd import sys import inspect ### POPULATE THE LIST OF TEST SCRIPTS ### TEST_SCRIPTS = {} def populateTestScripts(): global TEST_SCRIPTS thisScriptDir = Path( __file__ ).up() pathsToSearch = sys.path[:] + [ thisScriptDir ] for pyPath in pathsToSearch: pyPath = Path( pyPath ) if pyPath.isDir(): for f in pyPath.files(): if f.hasExtension( 'py' ): if f.name().startswith( 'devTest_' ): TEST_SCRIPTS[ f ] = [] populateTestScripts() ### POPULATE TEST_CASES ### TEST_CASES = [] def populateTestCases(): global TEST_CASES for script in TEST_SCRIPTS: testModule = __import__( script.name() ) scriptTestCases = TEST_SCRIPTS[ script ] = [] for name, obj in testModule.__dict__.iteritems(): if obj is TestCase: continue if isinstance( obj, type ): if issubclass( obj, TestCase ): if obj.__name__.startswith( '_' ): continue TEST_CASES.append( obj ) scriptTestCases.append( obj ) populateTestCases() def runTestCases( testCases=TEST_CASES ): thisPath = Path( __file__ ).up() testResults = TestResult() reloadedTestCases = [] for test in testCases: #find the module the test comes from module = inspect.getmodule( test ) performReload = getattr( module, 'PERFORM_RELOAD', True ) #reload the module the test comes from if performReload: module = reload( module ) #find the test object inside the newly re-loaded module and append it to the reloaded tests list reloadedTestCases.append( getattr( module, test.__name__ ) ) for ATestCase in reloadedTestCases: testCase = ATestCase() testCase.run( testResults ) #force a new scene cmd.file( new=True, f=True ) OK = 'Ok' BUTTONS = (OK,) if testResults.errors: print '------------- THE FOLLOWING ERRORS OCCURRED -------------' for error in testResults.errors: print error[0] print error[1] print '--------------------------' cmd.confirmDialog( t='TEST ERRORS OCCURRED!', m='Errors occurred running the tests - see the script editor for details!', b=BUTTONS, db=OK ) else: print '------------- %d TESTS WERE RUN SUCCESSFULLY -------------' % len( testCases ) cmd.confirmDialog( t='SUCCESS!', m='All tests were successful!', b=BUTTONS, db=OK ) return testResults #end
Python
from triggered import * import spaceSwitching def removeDupes( iterable ): unique = set() newIterable = iterable.__class__() for item in iterable: if item not in unique: newIterable.append( item ) unique.add( item ) return newIterable def buildMenuItems( parent, obj ): ''' build the menuItems in the dagProcMenu - it is possible to set a "kill menu" attribute on an object now that will stop the dagMenu building after the objMenu items have been added ''' defaultCmdName = "<empty cmd>" menusFromConnects = False killState = False objs = [ obj ] + (listRelatives( obj, pa=True, s=True ) or []) #the showMenusFromConnects attribute determines whether the object in question should show right click menus from any items connected to this one via triggered connects if objExists( '%s.showMenusFromConnects' % obj ): menusFromConnects = getAttr( '%s.showMenusFromConnects' % obj ) if menusFromConnects: connects = Trigger( obj ).connects() for connectObj, connectIdx in connects: objs.append( connectObj ) objs = removeDupes( objs ) #now get a list of objs that have menus - if there are more than one, build section labels, otherwise skip labels objsWithMenus = [] for obj in objs: obj = Trigger( obj ) if obj.menus(): objsWithMenus.append( obj ) doLabels = len( objsWithMenus ) > 1 setParent( parent, m=True ) for obj in objsWithMenus: #if ANY of the objs have the kill state set, turn it on if getKillState( obj ): killState = True tgts, names = spaceSwitching.getSpaceTargetsNames( obj ) names = [ 'parent to %s' % name for name in names ] if objExists( '%s.parent' % obj ): curIdx = getAttr( '%s.parent' % obj ) else: curIdx = None if doLabels: menuItem( l='---%s Menus---' % str( obj ).split( '|' )[-1].split( ':' )[-1], en=False ) for idx, cmdName, cmdStr in obj.menus( True ): #we need to construct the menu item using mel - because the tool was originally mel and all existing obj menu commands are written in mel #so you have to construct the menu item in mel otherwise its assumed the command is python... menuCmdToks = [ 'menuItem -l "%s"' % (cmdName or defaultCmdName) ] #so if the menu name starts with "parent to " then it assumed to be a menu item built by zooSpaceSwitching if cmdStr.startswith( "^parent to " ): if curIdx is not None: if idx == curIdx: menuCmdToks( '-cb 1' ) if cmdStr: menuCmdToks.append( '-c "%s"' % encodeString(cmdStr) ) mel.eval( ' '.join( menuCmdToks ) ) #should we die after menu build? if not killState: menuItem( d=True ) menuItem( d=True ) return killState #end
Python
import __future__ from filesystem import * from vectors import * import maya.OpenMaya as OpenMaya import maya.cmds as cmd import maya.mel import maya.utils import names def getFps(): ''' returns the current fps as a number ''' timebases = {'ntsc': 30, 'pal': 25, 'film': 24, 'game': 15, 'show': 48, 'palf': 50, 'ntscf': 60} base = cmd.currentUnit(q=True, time=True) return timebases[base] class CmdQueue(list): ''' the cmdQueue is generally used as a bucket to store a list of maya commands to execute. for whatever reason executing individual maya commands through python causes each command to get put into the undo queue - making tool writing a pain. so for scripts that have to execute maya commands one at a time, consider putting them into a CmdQueue object and executing the object once you're done generating commands... to execute a CmdQueue instance, simply call it ''' def __init__( self ): list.__init__(self) def __call__( self, echo=False ): m = mel if echo: m = melecho fp = Path( "%TEMP%/cmdQueue.mel" ) f = open( fp, 'w' ) f.writelines( '%s;\n' % l for l in self ) f.close() print fp m.source( fp ) ui_BUTTONS = OK, CANCEL = 'OK', 'Cancel' ui_QUESTION = YES, NO = 'Yes', 'No' def doPrompt( **kwargs ): ''' does a prompt dialog (all args are passed directly to the dial creation method) and returns a 2 tuple of the dial dismiss string and the actual input value ''' kwargs.setdefault('t', 'enter name') kwargs.setdefault('m', 'enter name') kwargs.setdefault('b', ui_BUTTONS) #set the default button - buttons is always an iterable, so use the first item kwargs.setdefault('db', kwargs['b'][0]) #throw up the dial ans = cmd.promptDialog(**kwargs) return ans, cmd.promptDialog(q=True, tx=True) #there are here to follow the convention specified in the filesystem writeExportDict method kEXPORT_DICT_SCENE = 'scene' kEXPORT_DICT_APP_VERSION = 'app_version' def writeExportDict( toolName=None, toolVersion=None, **kwargs ): ''' wraps the filesystem method of the same name - and populates the dict with maya specific data ''' d = writeExportDict( toolName, toolVersion, **kwargs ) d[ kEXPORT_DICT_SCENE ] = cmd.file( q=True, sn=True ) d[ kEXPORT_DICT_APP_VERSION ] = cmd.about( version=True ) return d def referenceFile( filepath, namespace, silent=False ): filepath = Path( filepath ) cmd.file( filepath, r=True, prompt=silent, namespace=namespace ) def openFile( filepath, silent=False ): filepath = Path( filepath ) ext = filepath.getExtension().lower() if ext == 'ma' or ext == 'mb': mel.saveChanges( 'file -f -prompt %d -o "%s"' % (silent, filepath) ) mel.addRecentFile( filepath, 'mayaAscii' if Path( filepath ).hasExtension( 'ma' ) else 'mayaBinary' ) def importFile( filepath, silent=False ): filepath = Path( filepath ) ext = filepath.getExtension().lower() if ext == 'ma' or ext == 'mb': cmd.file( filepath, i=True, prompt=silent, rpr='__', type='mayaAscii', pr=True, loadReferenceDepth='all' ) def addExploreToMenuItems( filepath ): if filepath is None: return filepath = Path( filepath ) if not filepath.exists(): filepath = filepath.getClosestExisting() if filepath is None: return cmd.menuItem(l="Explore to location...", c=lambda x: mel.zooExploreTo( filepath ), ann='open an explorer window to the location of this file/directory') cmd.menuItem(l="CMD prompt to location...", c=lambda x: mel.zooCmdTo( filepath ), ann='open a command prompt to the location of this directory') #end
Python
from maya.OpenMaya import MGlobal from exceptionHandlers import generateTraceableStrFactory generateInfoStr, printInfoStr = generateTraceableStrFactory( '*** INFO ***', MGlobal.displayInfo ) generateWarningStr, printWarningStr = generateTraceableStrFactory( '', MGlobal.displayWarning ) generateErrorStr, printErrorStr = generateTraceableStrFactory( '', MGlobal.displayError ) #end
Python
from maya.cmds import * from baseMelUI import * from mayaDecorators import d_disableViews, d_noAutoKey, d_unifyUndo from common import printWarningStr @d_unifyUndo @d_disableViews @d_noAutoKey def changeParent( parent=0, objs=None ): if objs is None: objs = ls( sl=True, type='transform' ) or [] #only bother with objects that have a "parent" attribute and whose parent attribute value is not the same as the one we've been passed objsToActOn = [] for obj in objs: if objExists( '%s.parent' % obj ): objsToActOn.append( obj ) objs = objsToActOn #if there are no objects, bail if not objs: printWarningStr( "There are no objects to work on - aborting!" ) return #store the initial time so we can restore it at the end initialTime = currentTime( q=True ) #first we need to make sure that any frame with a rotation key needs to have a key on ALL rotation axes - so make this happen keyTimes = keyframe( objs, q=True, at=('t', 'r'), tc=True ) if not keyTimes: printWarningStr( "No keys found on the objects - nothing to do!" ) return #remove duplicate key times and sort them keyTimes = removeDupes( keyTimes ) keyTimes.sort() #store the objects that each have keys at each key time in a dict so we don't have to query maya again. maya queries are slower than accessing python data structures timeObjs = {} for time in keyTimes: currentTime( time, e=True ) timeObjs[ time ] = objsWithKeysAtThisTime = [] for obj in objs: keyOnCurrentTime = keyframe( obj, q=True, t=(time,), at=('parent', 't', 'r'), kc=True ) if keyOnCurrentTime: setKeyframe( obj, at=('parent', 't', 'r') ) objsWithKeysAtThisTime.append( obj ) #now that we've secured the translation/rotation poses with keys on all axes, change the parent on each keyframe for time, objsWithKeysAtThisTime in timeObjs.iteritems(): currentTime( time, e=True ) for obj in objsWithKeysAtThisTime: pos = xform( obj, q=True, rp=True, ws=True ) rot = xform( obj, q=True, ro=True, ws=True ) #change the parent and move/rotate back to the original world space pose setAttr( '%s.parent' % obj, parent ) move( pos[0], pos[1], pos[2], obj, ws=True, rpr=True ) rotate( rot[0], rot[1], rot[2], obj, ws=True ) #lock in the pose setKeyframe( obj, at=('parent', 't', 'r') ) #finally restore the initial time currentTime( initialTime, e=True ) class ChangeParentLayout(MelColumnLayout): def __init__( self, parent ): hLayout = MelHSingleStretchLayout( self ) lbl = MelLabel( hLayout, l='New Parent' ) self.UI_parent = MelOptionMenu( hLayout ) hLayout.setStretchWidget( self.UI_parent ) hLayout.layout() hLayout( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) ) self.UI_go = MelButton( self, l='Change Parent', c=self.on_go ) self.on_selectionChange() self.setSelectionChangeCB( self.on_selectionChange ) ### EVENT HANDLERS ### def on_selectionChange( self, *a ): self.UI_parent.clear() #populate the parent list - just use the parents from the first object found with a parent attribute for obj in ls( sl=True, type='transform' ) or []: if objExists( '%s.parent' % obj ): curValue = getAttr( '%s.parent' % obj ) enumStr = addAttr( '%s.parent' % obj, q=True, enumName=True ) enums = enumStr.split( ':' ) for enum in enums: self.UI_parent.append( enum ) if enums: self.UI_parent.selectByIdx( curValue ) self.UI_go.enable( True ) return #if we've made it here, there are no objects with a parent attribute, or no objects with parents - either way disable the go button self.UI_go.enable( False ) def on_go( self, *a ): changeParent( self.UI_parent.getSelectedIdx() ) class ChangeParentWindow(BaseMelWindow): WINDOW_NAME = 'changeParent' WINDOW_TITLE = 'Change Parent Tool' DEFAULT_MENU = None DEFAULT_SIZE = 245, 85 FORCE_DEFAULT_SIZE = True def __init__( self ): self.UI_editor = ChangeParentLayout( self ) self.show() #end
Python
from filesystem import * from common import printInfoStr, printErrorStr from mayaDecorators import d_unifyUndo import maya.cmds as cmd import names import api import apiExtensions __author__ = 'mel@macaronikazoo.com' TOOL_NAME = 'animLib' kEXT = 'clip' VER = 3 #version ### clip types kPOSE = 0 kANIM = 1 kDELTA = 2 kDEFAULT_MAPPING_THRESHOLD = 1 kICON_W_H = 60, 60 mel = api.mel Mapping = names.Mapping class AnimLibException(Exception): def __init__( self, *args ): Exception.__init__(self, *args) def getMostLikelyModelView(): ''' returns the panel name for the most likely active panel - the currently active panel can be ambiguous if the user has been using the outliner, or graph editor or something after viewport usage... this method simply looks at the currently active panel and if its not a modelPanel, then it returns the first visible model panel. if no panels are found, returns None ''' cur = cmd.getPanel(wf=True) curType = cmd.getPanel(to=cur) if curType == "modelPanel": return cur visPanels = cmd.getPanel(vis=True) for p in visPanels: if cmd.getPanel(to=p) == "modelPanel": return p return None def generateIcon( preset ): ''' given a preset object, this method will generate an icon using the currently active viewport. the path to the icon is returned ''' sel = cmd.ls(sl=True) cmd.select(cl=True) panel = getMostLikelyModelView() if panel is None: raise AnimLibException('cannot determine which panel to use for icon generation') #store some initial settings, change them to what is required, and then restored at the very end settings = ["-df", "-cv", "-ca", "-nurbsCurves", "-nurbsSurfaces", "-lt", "-ha", "-dim", "-pv", "-ikh", "-j", "-dy"] imgFormat = cmd.getAttr("defaultRenderGlobals.imageFormat") states = [] cmd.setAttr("defaultRenderGlobals.imageFormat", 20) for setting in settings: states.append( mel.eval("modelEditor -q %s %s;" % (setting, panel)) ) for setting in settings: mel.eval("modelEditor -e %s 0 %s;" % (setting, panel)) time = cmd.currentTime(q=True) #make sure the icon is open for edit if its a global clip if preset.locale == GLOBAL and preset.icon.exists(): preset.edit() icon = cmd.playblast(st=time, et=time, w=kICON_W_H[0], h=kICON_W_H[1], fo=True, fmt="image", v=0, p=100, orn=0, cf=str(preset.icon.resolve())) icon = Path(icon) if icon.exists(): icon = icon.setExtension('bmp', True) cmd.setAttr("defaultRenderGlobals.imageFormat", imgFormat) #restore viewport settings try: cmd.select(sel) except TypeError: pass for setting, initialState in zip(settings, states): mel.eval("modelEditor -e %s %s %s;" % (setting, initialState, panel)) return icon class BaseBlender(object): ''' a blender object is simply a callable object that when called with a percentage arg (0-1) will apply said percentage of the given clips to the given mapping ''' def __init__( self, clipA, clipB, mapping=None, attributes=None ): self.clipA = clipA self.clipB = clipB self.__mapping = mapping if attributes: attributes = set( attributes ) self.attributes = attributes def setMapping( self, mapping ): self.__mapping = mapping def getMapping( self ): return self.__mapping def __call__( self, pct, mapping=None ): if mapping is not None: self.setMapping( mapping ) assert self.getMapping() is not None class PoseBlender(BaseBlender): def __call__( self, pct, mapping=None, attributes=None ): BaseBlender.__call__(self, pct, mapping) cmdQueue = api.CmdQueue() if mapping is None: mapping = self.getMapping() if attributes is None: attributes = self.attributes mappingDict = mapping.asDict() for clipAObj, attrDictA in self.clipA.iteritems(): #if the object isn't in the mapping dict, skip it if clipAObj not in mappingDict: continue clipBObjs = mapping[ clipAObj ] for a, valueA in attrDictA.iteritems(): if attributes: if a not in attributes: continue if not clipAObj: continue attrpath = '%s.%s' % (clipAObj, a) if not cmd.getAttr( attrpath, settable=True ): continue for clipBObj in clipBObjs: try: attrDictB = self.clipB[ clipBObj ] except KeyError: continue try: valueB = attrDictB[ a ] blendedValue = (valueA * (1-pct)) + (valueB * pct) cmdQueue.append( 'setAttr -clamp %s %f' % (attrpath, blendedValue) ) except KeyError: cmdQueue.append( 'setAttr -clamp %s %f' % (attrpath, valueA) ) except: pass cmdQueue() class AnimBlender(BaseBlender): def __init__( self, clipA, clipB, mapping=None ): BaseBlender.__init__(self, clipA, clipB, mapping) #so now we need to generate a dict to represent the curves for both of the clips animCurveDictA = self.animCurveDictA = {} animCurveDictB = self.animCurveDictB = {} #the curvePairs attribute contains a dict - indexed by attrpath - containing a tuple of (curveA, curveB) self.curvePairs = {} for clip, curveDict in zip([self.clipA, self.clipB], [animCurveDictA, animCurveDictB]): for o, attrDict in clip.iteritems(): curveDict[o] = {} for a, keyData in attrDict.iteritems(): curve = curveDict[o][a] = animCurve.AnimCurve() #unpack the key data weightedTangents, keyList = keyData #generate the curves for time, value, itt, ott, ix, iy, ox, oy, isLocked, isWeighted in keyList: curve.m_bWeighted = weightedTangents curve.AddKey( time, value, ix, iy, ox, oy ) attrPath = '%s.%s' % (o, a) try: self.curvePairs[attrPath].append( curve ) except KeyError: self.curvePairs[attrPath] = [ curve ] #now iterate over each curve pair and make sure they both have keys on the same frames... for attrPath, curves in self.curvePairs.iteritems(): try: curveA, curveB = curves except ValueError: continue curveTimes = set( curveA.m_keys.keys() + curveB.m_keys.keys() ) for t in curveTimes: curveA.InsertKey( t ) curveB.InsertKey( t ) print 'keys on', attrPath, 'at times', curveTimes def __call__( self, pct, mapping=None ): BaseBlender.__call__(self, pct, mapping) cmdQueue = api.CmdQueue() if pct == 0: self.clipA.apply( self.getMapping() ) elif pct == 1: self.clipB.apply( self.getMapping() ) else: for attrPath, curves in self.curvePairs.iteritems(): try: curveA, curveB = curves except ValueError: continue #because we know both curves have the same timings (ie if curveA has a key at time x, curveB is guaranteed to also have a key #at time x) then we just need to iterate over the keys of one curve, and blend them with the values of the other for time, keyA in curveA.m_keys.iteritems(): keyB = curveB.m_keys[ time ] blendedValue = (keyA.m_flValue * (1-pct)) + (keyB.m_flValue * pct) blendedIX = (keyA.m_flInTanX * (1-pct)) + (keyB.m_flInTanX * pct) blendedIY = (keyA.m_flInTanY * (1-pct)) + (keyB.m_flInTanY * pct) blendedOX = (keyA.m_flOutTanX * (1-pct)) + (keyB.m_flOutTanX * pct) blendedOY = (keyA.m_flOutTanY * (1-pct)) + (keyB.m_flOutTanY * pct) cmdQueue.append( 'setKeyframe -t %s -v %s %s' % (time, blendedValue, attrPath) ) cmdQueue.append( 'keyTangent -e -t %s -ix %s -iy %s -ox %s -oy %s %s' % (time, blendedIX, blendedIY, blendedOX, blendedOY, attrPath) ) class BaseClip(dict): ''' baseclass for clips ''' blender = None OPTIONS =\ kOPT_ADDITIVE, kOPT_ADDITIVE_WORLD, kOPT_OFFSET, kOPT_CLEAR, kMULT, kOPT_ATTRSELECTION =\ 'additive', 'additiveWorld', 'offset', 'clear', 'mult', 'attrSelection' kOPT_DEFAULTS = { kOPT_ADDITIVE: False, kOPT_ADDITIVE_WORLD: False, kOPT_OFFSET: 0, kOPT_CLEAR: True, kMULT: 1, kOPT_ATTRSELECTION: False } def __init__( self, objects=None ): if objects is not None: self.generate( objects ) def generate( self, objects ): pass def apply( self, mapping, attributes=None, **kwargs ): ''' valid kwargs are additive [False] applys the animation additively ''' pass def getObjects( self ): return self.keys() def generatePreArgs( self ): return tuple() def getObjAttrNames( obj, attrNamesToSkip=() ): #grab attributes objAttrs = cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) or [] #also grab alias' - its possible to pass in an alias name, so we need to test against them as well aliass = cmd.aliasAttr( obj, q=True ) or [] #because the aliasAttr cmd returns a list with the alias, attr pairs in a flat list, we need to iterate over the list, skipping every second entry itAliass = iter( aliass ) for attr in itAliass: objAttrs.append( attr ) itAliass.next() filteredAttrs = [] for attr in objAttrs: skipAttr = False for skipName in attrNamesToSkip: if attr == skipName: skipAttr = True elif attr.startswith( skipName +'[' ) or attr.startswith( skipName +'.' ): skipAttr = True if skipAttr: continue filteredAttrs.append( attr ) return filteredAttrs #defines a mapping between node type, and the function used to get a list of attributes from that node to save to the clip. by default getObjAttrNames( obj ) is called GET_ATTR_BY_NODE_TYPE = { 'blendShape': lambda obj: getObjAttrNames( obj, ['envelope', 'weight', 'inputTarget'] ) } class PoseClip(BaseClip): blender = PoseBlender @classmethod def FromObjects( cls, objects ): new = cls() cls.generate(new, objects) return new def __add__( self, other ): ''' for adding multiple pose clips together - returns a new PoseClip instance ''' pass def __mult__( self, other ): ''' for multiplying a clip by a scalar value ''' assert isinstance(other, (int, long, float)) new = PoseClip for obj, attrDict in self.iteritems(): for attr, value in attrDict.iteritems(): attrDict[attr] = value * other def generate( self, objects, attrs=None ): ''' generates a pose dictionary - its basically just dict with node names for keys. key values are dictionaries with attribute name keys and attribute value keys ''' self.clear() if attrs: attrs = set( attrs ) for obj in objects: objType = cmd.nodeType( obj ) attrGetFunction = GET_ATTR_BY_NODE_TYPE.get( objType, getObjAttrNames ) objAttrs = set( attrGetFunction( obj ) ) if attrs: objAttrs = objAttrs.intersection( attrs ) if objAttrs is None: continue self[ obj ] = objDict = {} for attr in objAttrs: objDict[ attr ] = cmd.getAttr( '%s.%s' % (obj, attr) ) return True @d_unifyUndo def apply( self, mapping, attributes=None, **kwargs ): ''' construct a mel string to pass to eval - so it can be contained in a single undo... ''' cmdQueue = api.CmdQueue() #gather options... additive = kwargs.get( self.kOPT_ADDITIVE, self.kOPT_DEFAULTS[ self.kOPT_ADDITIVE ] ) #convert the attribute list to a set for fast lookup if attributes: attributes = set( attributes ) for clipObj, tgtObj in mapping.iteritems(): try: attrDict = self[ clipObj ] except KeyError: continue for attr, value in attrDict.iteritems(): if attributes: if attr not in attributes: continue if not tgtObj: continue attrpath = '%s.%s' % (tgtObj, attr) try: if not cmd.getAttr( attrpath, settable=True ): continue except TypeError: continue if additive: value += cmd.getAttr( attrpath ) cmdQueue.append( 'setAttr -clamp %s %f;' % (attrpath, value) ) cmdQueue() class AnimClip(BaseClip): blender = AnimBlender def __init__( self, objects=None ): self.offset = 0 BaseClip.__init__(self, objects) def __add__( self, other ): pass def __mult__( self, other ): assert isinstance(other, (int, long, float)) for obj, attrDict in self.iteritems(): for attr, value in attrDict.iteritems(): value *= other def generate( self, objects, attrs=None, startFrame=None, endFrame=None ): ''' generates an anim dictionary - its basically just dict with node names for keys. key values are lists of tuples with the form: (keyTime, attrDict) where attrDict is a dictionary with attribute name keys and attribute value keys ''' defaultWeightedTangentOpt = bool(cmd.keyTangent(q=True, g=True, wt=True)) self.clear() if attrs: attrs = set( attrs ) if startFrame is None: startFrame = cmd.playbackOptions( q=True, min=True ) if endFrame is None: endFrame = cmd.playbackOptions( q=True, max=True ) startFrame, endFrame = list( sorted( [startFrame, endFrame] ) ) self.offset = startFrame #list all keys on the objects - so we can determine the start frame, and range. all times are stored relative to this time allKeys = cmd.keyframe( objects, q=True ) or [] allKeys.sort() allKeys = [ k for k in allKeys if startFrame <= k <= endFrame ] if not allKeys: return False self.offset = offset = allKeys[ 0 ] self.__range = allKeys[ -1 ] - offset for obj in objects: objAttrs = set( cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) or [] ) if attrs: objAttrs = objAttrs.intersection( attrs ) if not objAttrs: continue objDict = {} self[ obj ] = objDict for attr in objAttrs: timeTuple = startFrame, endFrame #so the attr value dict contains a big fat list containing tuples of the form: #(time, value, itt, ott, ita, ota, iw, ow, isLockedTangents, isWeightLock) attrpath = '%s.%s' % (obj, attr) times = cmd.keyframe( attrpath, q=True, t=timeTuple ) weightedTangents = defaultWeightedTangentOpt #if there is an animCurve this will return its "weighted tangent" state - otherwise it will return None and a TypeError will be raised try: weightedTangents = bool(cmd.keyTangent(attrpath, q=True, weightedTangents=True)[0]) except TypeError: pass if times is None: #in this case the attr has no animation, so simply record the pose for this attr objDict[attr] = (False, [(None, cmd.getAttr(attrpath), None, None, None, None, None, None, None, None)]) continue else: times = [ t-offset for t in times ] values = cmd.keyframe(attrpath, q=True, t=timeTuple, vc=True) itts = cmd.keyTangent(attrpath, q=True, t=timeTuple, itt=True) otts = cmd.keyTangent(attrpath, q=True, t=timeTuple, ott=True) ixs = cmd.keyTangent(attrpath, q=True, t=timeTuple, ix=True) iys = cmd.keyTangent(attrpath, q=True, t=timeTuple, iy=True) oxs = cmd.keyTangent(attrpath, q=True, t=timeTuple, ox=True) oys = cmd.keyTangent(attrpath, q=True, t=timeTuple, oy=True) isLocked = cmd.keyTangent(attrpath, q=True, t=timeTuple, weightLock=True) isWeighted = cmd.keyTangent(attrpath, q=True, t=timeTuple, weightLock=True) objDict[ attr ] = weightedTangents, zip(times, values, itts, otts, ixs, iys, oxs, oys, isLocked, isWeighted) return True @d_unifyUndo def apply( self, mapping, attributes=None, **kwargs ): ''' valid kwargs are: mult [1.0] apply a mutiplier when applying curve values additive [False] clear [True] ''' beginningWeightedTanState = cmd.keyTangent( q=True, g=True, wt=True ) ### gather options... additive = kwargs.get( self.kOPT_ADDITIVE, self.kOPT_DEFAULTS[self.kOPT_ADDITIVE] ) worldAdditive = kwargs.get( self.kOPT_ADDITIVE_WORLD, self.kOPT_DEFAULTS[self.kOPT_ADDITIVE_WORLD] ) clear = kwargs.get( self.kOPT_CLEAR, self.kOPT_DEFAULTS[self.kOPT_CLEAR] ) mult = kwargs.get( self.kMULT, self.kOPT_DEFAULTS[self.kMULT] ) timeOffset = kwargs.get( self.kOPT_OFFSET, self.offset ) #if worldAdditive is turned on, then additive is implied if worldAdditive: additive = worldAdditive #determine the time range to clear clearStart = timeOffset clearEnd = clearStart + self.range #convert the attribute list to a set for fast lookup if attributes: attributes = set( attributes ) for obj, tgtObj in mapping.iteritems(): if not tgtObj: continue try: attrDict = self[ obj ] except KeyError: continue for attr, (weightedTangents, keyList) in attrDict.iteritems(): if attributes: if attr not in attributes: continue attrpath = '%s.%s' % (tgtObj, attr) try: if not cmd.getAttr(attrpath, settable=True): continue except TypeError: continue except RuntimeError: print obj, tgtObj, attrpath raise #do the clear... maya doesn't complain if we try to do a cutKey on an attrpath with no #animation - and this is good to do before we determine whether the attrpath has a curve or not... if clear: cmd.cutKey( attrpath, t=(clearStart, clearEnd), cl=True ) #is there an anim curve on the target attrpath already? curveExists = cmd.keyframe(attrpath, index=(0,), q=True) is not None preValue = 0 if additive: if worldAdditive: isWorld = True #if the control has space switching setup, see if its value is set to "world" - if its not, we're don't treat the control's animation as additive try: isWorld = cmd.getAttr('%s.parent' % obj, asString=True) == 'world' except TypeError: pass #only treat translation as additive if isWorld and attr.startswith('translate'): preValue = cmd.getAttr(attrpath) else: preValue = cmd.getAttr(attrpath) for time, value, itt, ott, ix, iy, ox, oy, isLocked, isWeighted in keyList: value *= mult value += preValue if time is None: #in this case the attr value was just a pose... cmd.setAttr( attrpath, value ) else: time += timeOffset cmd.setKeyframe( attrpath, t=(time,), v=value ) if weightedTangents: #this needs to be done as two separate commands - because setting the tangent types in the same cmd as setting tangent weights can result #in the tangent types being ignored (for the case of stepped mainly, but subtle weirdness with flat happens too) cmd.keyTangent( attrpath, t=(time,), ix=ix, iy=iy, ox=ox, oy=oy, l=isLocked, wl=isWeighted ) cmd.keyTangent( attrpath, t=(time,), itt=itt, ott=ott ) else: cmd.keyTangent( attrpath, t=(time,), ix=ix, iy=iy, ox=ox, oy=oy ) #cmd.keyTangent( e=True, g=True, wt=beginningWeightedTanState ) def getKeyTimes( self ): ''' returns an ordered list of key times ''' keyTimesSet = set() for obj, attrDict in self.iteritems(): for attr, (weightedTangents, keyList) in attrDict.iteritems(): if keyList[0][0] is None: continue for tup in keyList: keyTimesSet.add( tup[0] ) keyTimes = list( keyTimesSet ) keyTimes.sort() return keyTimes def getRange( self ): ''' returns a tuple of (start, end) ''' times = self.getKeyTimes() try: start, end = times[0], times[-1] self.offset = start except IndexError: start, end = 0, 0 self.__range = 0 return start, end def getRangeValue( self ): try: return self.__range except AttributeError: self.getRange() return self.__range range = property(getRangeValue) def generatePreArgs( self ): return tuple() kEXPORT_DICT_THE_CLIP = 'clip' kEXPORT_DICT_CLIP_TYPE = 'clip_type' kEXPORT_DICT_OBJECTS = 'objects' kEXPORT_DICT_WORLDSPACE = 'worldspace' class ClipPreset(Preset): ''' a clip preset is different from a normal preset because it is actually two separate files - a pickled animation data file, and an icon ''' TYPE_CLASSES = {kPOSE: PoseClip, kANIM: AnimClip, kDELTA: None} TYPE_LABELS = {kPOSE: 'pose', kANIM: 'anim', kDELTA: 'delta'} ### auto generate a label types LABEL_TYPES = {} for t, l in TYPE_LABELS.iteritems(): LABEL_TYPES[l] = t def __new__( cls, locale, library, name, type=kPOSE ): tool = '%s/%s' % (TOOL_NAME, library) typeLbl = cls.TYPE_LABELS[type] ext = '%s.%s' % (typeLbl, kEXT) self = Preset.__new__( cls, locale, tool, name, ext ) self.icon = Preset( locale, tool, name, '%s.bmp' % typeLbl ) return self def asClip( self ): presetDict = self.unpickle() return presetDict[ kEXPORT_DICT_THE_CLIP ] def niceName( self ): return self.name().split('.')[0] def getLibrary( self ): return self[-2] def setLibrary( self, library ): self[-2] = library def getTypeName( self ): return self.name().split('.')[ -1 ] def getType( self ): typeLbl = self.getTypeName() return self.LABEL_TYPES[typeLbl] def move( self, library=None ): if library is None: library = self.getLibrary() newLoc = ClipPreset(self.other(), library, self.niceName(), self.getType()) #perform the move... Path.move(self, newLoc) Path.move(self.icon, newLoc.icon) return newLoc def copy( self, library=None ): if library is None: library = self.library newLoc = ClipPreset(self.other(), library, self.niceName(), self.getType()) #perform the copy... Path.copy(self, newLoc) Path.copy(self.icon, newLoc.icon) return newLoc def rename( self, newName ): ''' newName should be the base name - sans any clip type id or extension... ''' newName = '%s.%s' % (scrubName(newName), self.getTypeName()) Preset.rename(self, newName) self.icon.rename(newName) def delete( self ): Path.delete(self) self.icon.delete() @api.d_noAutoKey def apply( self, objects, attributes=None, **kwargs ): presetDict = self.unpickle() srcObjs = presetDict[ kEXPORT_DICT_OBJECTS ] clip = presetDict[ kEXPORT_DICT_THE_CLIP ] #do a version check - if older version clip is being used - perhaps we can write conversion functionality? try: ver = presetDict[ kEXPORT_DICT_TOOL_VER ] if ver != VER: api.melWarning("the anim clip version don't match!") except KeyError: api.melWarning("this is an old VER 1 pose clip - I don't know how to load them anymore...") return #generate the name mapping slamApply = kwargs.get( 'slam', False ) if slamApply: objects = cmd.ls( typ='transform' ) tgts = names.matchNames( srcObjs, objects, threshold=kDEFAULT_MAPPING_THRESHOLD ) mapping = Mapping( srcObjs, tgts ) else: tgts = names.matchNames( srcObjs, objects, threshold=kDEFAULT_MAPPING_THRESHOLD ) mapping = Mapping( srcObjs, tgts ) #run the clip's apply method clip.apply( mapping, attributes, **kwargs ) def getClipObjects( self ): ''' returns a list of all the object names contained in the clip ''' presetDict = self.unpickle() srcObjs = presetDict[ kEXPORT_DICT_OBJECTS ] return srcObjs def write( self, objects, **kwargs ): type = self.getType() clipDict = api.writeExportDict( TOOL_NAME, VER ) clipDict[ kEXPORT_DICT_CLIP_TYPE ] = type clipDict[ kEXPORT_DICT_OBJECTS ] = objects clipDict[ kEXPORT_DICT_WORLDSPACE ] = False theClip = self.TYPE_CLASSES[ type ]() success = theClip.generate( objects, **kwargs ) if not success: printErrorStr( "Failed to generate clip!" ) return clipDict[ kEXPORT_DICT_THE_CLIP ] = theClip #write the preset file to disk self.pickle( clipDict ) #generate the icon for the clip and add it to perforce if appropriate icon = generateIcon( self ) #icon.asP4().add() printInfoStr( "Generated clip!" ) class ClipManager(PresetManager): ''' an abstraction for listing libraries and library clips for clip presets - there are two main differences between clip presets and other presets - clips have a library which is a subdir of the main preset dir, and there are also multiple types of clips both with the same extension. ''' def __init__( self ): PresetManager.__init__(self, TOOL_NAME, kEXT) def getLibraryNames( self ): ''' returns the names of all libraries under the current mod ''' libraries = set() for locale, paths in self.getLibraryPaths().iteritems(): for p in paths: libName = p.name() libraries.add(libName) libraries = list(libraries) libraries.sort() return libraries def getLibraryPaths( self ): ''' returns a dictionary of library paths keyed using locale. ie: {LOCAL: [path1, path2, ...], GLOBAL: etc...} ''' localeDict = {} for locale in LOCAL, GLOBAL: localeDict[locale] = libraries = [] dirs = self.getPresetDirs(locale) libraryNames = set() for d in dirs: dLibs = d.dirs() for dLib in dLibs: dLibName = dLib[-1] if dLibName not in libraryNames: libraries.append(dLib) libraryNames.add(dLibName) return localeDict def createLibrary( self, name ): newLibraryPath = Preset(LOCAL, TOOL_NAME, name, '') newLibraryPath.create() def getLibraryClips( self, library ): global kEXT clips = {LOCAL: [], GLOBAL: []} for locale in LOCAL, GLOBAL: localeClips = clips[locale] for dir in getPresetDirs(locale, TOOL_NAME): dir += library if not dir.exists(): continue for f in dir.files(): if f.hasExtension( kEXT ): f = f.setExtension() name, type = f[ -1 ].split('.') f = f[ :-1 ] type = ClipPreset.LABEL_TYPES[ type ] localeClips.append( ClipPreset(locale, library, name, type) ) return clips def getPathToLibrary( self, library, locale=LOCAL ): return getPresetDirs(locale, TOOL_NAME)[0] / library def reload( self ): pass #end
Python
parityTestsL = ["l", "left", "lft", "lf", "lik"] parityTestsR = ["r", "right", "rgt", "rt", "rik"] DEFAULT_THRESHOLD = 1 class Parity(int): PARITIES = NONE, LEFT, RIGHT = None, 0, 1 #odd indices are left sided, even are right sided NAMES = [ '_L', '_R', '_A_L', '_A_R', '_B_L', '_B_R', '_C_L', '_C_R', '_D_L', '_D_R' ] def __new__( cls, idx ): return int.__new__( cls, idx ) def __eq__( self, other ): if other is None: return False return self % 2 == int( other ) % 2 def __nonzero__( self ): return self % 2 def __ne__( self, other ): return not self.__eq__( other ) def asMultiplier( self ): return (-1) ** self def asName( self ): return self.NAMES[ self ] def isOpposite( self, other ): return (self % 2) != (other % 2) Parity.LEFT, Parity.RIGHT = Parity( Parity.LEFT ), Parity( Parity.RIGHT ) class Name(object): ''' Name objects are strings that are used to identify something such as an object or a filepath. this class creates some useful ways of comparing and manipulating Name objects ''' PREFIX_DELIMETERS = ':|' PUNCTUATION = '_. ' def __init__( self, nameItem='' ): #NOTE: this value should never be set directly... instead use the set method or the string property self._string = str( nameItem ) self.item = nameItem self.prefix = None #determines what characters denote a prefix boundary - so if it were set to ':' then apples:bananas would have the string 'apples:' as its prefix self.prefixDelimeters = self.PREFIX_DELIMETERS self.punctuation = self.PUNCTUATION def __str__( self ): return self._string __repr__ = __str__ def __eq__( self, other ): return int( self.likeness( other ) ) def __ne__( self, other ): return not self.__eq__( other ) def __getitem__( self, item ): return self.split()[item] def __setitem__( self, item, newItem ): token = self[ item ] nameStr = str( self ) startIdx = nameStr.find( token ) endIdx = startIdx + len( token ) #splice together a new string and we're done... self._string = '%s%s%s' % ( nameStr[:startIdx], newItem, nameStr[endIdx:] ) def pop( self, item, stripSurroundingPunctuation=True ): PUNCTUATION = self.PUNCTUATION token = self[ item ] nameStr = str( self ) startIdx = nameStr.find( token ) endIdx = startIdx + len( token ) ''' #now strip surrounding whitespace or punctuation if stripSurroundingPunctuation: puncEndOffset = 0 hasEndPunc = False for char in nameStr[ endIdx: ]: if char in PUNCTUATION: puncEndOffset += 1 hasEndPunc = True else: break reversedStartChunk = ''.join( reversed( list( nameStr[ :startIdx ] ) ) ) puncStartOffset = 0 hasStartPunc = False for char in reversedStartChunk: if char in PUNCTUATION: puncStartOffset -= 1 hasStartPunc = True else: break if hasStartPunc and hasEndPunc: startIdx -= max( 0, puncStartOffset ) endIdx += puncEndOffset ''' newNameStr = '%s%s' % ( nameStr[:startIdx], nameStr[endIdx:] ) removeStart = startIdx #for n, char in enumerate( newNameStr[ startIdx: ] ): #splice together a new string and we're done... self._string = '%s%s' % ( nameStr[:startIdx], nameStr[endIdx:] ) def __nonzero__( self ): try: self._string[0] return True except IndexError: return False def set( self, newString ): self._string = newString string = property(__str__, set) def get_parity( self ): ''' doing this comparison is a little faster than using the cache lookup - and parity gets hammered on in likeness determination ''' try: return self._parity except AttributeError: self._parity, self._parityStr = hasParity( self.split() ) return self._parity parity = property( get_parity ) def strip_parity( self ): return str( stripParity( self ) ) def swap_parity( self ): return self.__class__( swapParity(self) ) def cache_prefix( self, delimeters=None ): '''strips any namespace or path data from the name string - by default the stripping is done "in place", but if the inPlace variable is set to true, then a new Name object is returned''' self.prefix = '' string = self._string.strip() lastMatch = -1 if delimeters is None: delimeters = self.prefixDelimeters for char in delimeters: matchPos = string.rfind(char) if matchPos > lastMatch: lastMatch = matchPos #store the prefix string if lastMatch != -1: self.prefix = string[:lastMatch+1] self._string = string[lastMatch+1:] return self.prefix def uncache_prefix( self ): if self.prefix != None: self._string = self.prefix + self._string return self._string def get_prefix( self, delimeters=None ): '''strips any namespace or path data from the name string - by default the stripping is done "in place", but if the inPlace variable is set to true, then a new Name object is returned''' if self.prefix is None: return self.cache_prefix( delimeters ) else: return self.prefix def likeness( self, other, parityMatters=False, stripFirst=True ): ''' given two Name objects this method will return a "likeness" factor based on how similar the two name strings are. it compares name tokens - tokens are defined by either camel case or any character defined in the self.punctuation variable. so for example: thisStringHas_a_fewTokens has the tokens: this, String, Has, a, few, Tokens given two names, the more tokens that match, the higher the likeness. the tokens don't have to match exactly - a few tests are done such as case difference, subset test and numeric comparison ''' #do stripping if required #if stripFirst: self.cache_prefix() #if the names match exactly, return the highest likeness if str(self) == str(other): return 1 srcTokens = self.split()[:] tgtTokens = other.split()[:] if parityMatters: if self.parity != other.parity: return 0 #if the split result is exact, early out if srcTokens == tgtTokens: return 1 exactMatchWeight = 1.025 totalWeight = 0 numSrcToks, numTgtToks = len(srcTokens), len(tgtTokens) for srcTok in srcTokens: bestMatch,bestMatchIdx = 0,-1 isSrcDigit = srcTok.isdigit() for n,tgtTok in enumerate(tgtTokens): tokSize = len(tgtTok) isTgtDigit = tgtTok.isdigit() #if one is a number token and the other isn't - there is no point proceeding as they're not going to match #letter tokens should not match number tokens - i guess it would be possible to test whether the word token #was a number name, but this would be expensive, and would only help fringe cases if isSrcDigit != isTgtDigit: continue #first, check to see if the names are the same if srcTok == tgtTok: bestMatch = tokSize * exactMatchWeight bestMatchIdx = n break #are the tokens numeric tokens? if so, we need to figure out how similar they are numerically - numbers that are closer to one another should result in a better match elif isSrcDigit and isTgtDigit: srcInt,tgtInt = int(srcTok),int(tgtTok) largest = max( abs(srcInt), abs(tgtInt) ) closeness = 1 if srcInt != tgtInt: closeness = ( largest - abs( srcInt-tgtInt ) ) / float(largest) bestMatch = tokSize * closeness bestMatchIdx = n break #are the names the same bar case differences? elif srcTok.lower() == tgtTok.lower(): bestMatch = tokSize bestMatchIdx = n break #so now test to see if any of the tokens are "sub-words" of each other - ie if you have something_otherthing an_other #the second token, "otherthing" and "other", the second is a subset of the first, so this is a rough match else: srcTokSize = len(srcTok) lowSrcTok,lowTgtTok = srcTok.lower(),tgtTok.lower() smallestWordSize = min( srcTokSize, tokSize ) subWordWeight = 0 #the weight is calculated as a percentage of matched letters if srcTokSize > tokSize: subWordWeight = tokSize * tokSize / float(srcTokSize) else: subWordWeight = srcTokSize * srcTokSize / float(tokSize) if srcTokSize > 2 and tokSize > 2: #make sure the src and tgt tokens are non-trivial (ie at least 3 letters) if lowSrcTok.find(lowTgtTok) != -1 or lowTgtTok.find(lowSrcTok) != -1: bestMatch = subWordWeight bestMatchIdx = n #remove the best match from the list - so it doesn't get matched to any other tokens if bestMatchIdx != -1: tgtTokens.pop(bestMatchIdx) numTgtToks -= 1 totalWeight += bestMatch #get the total number of letters in the "words" of the longest name - we use this for a likeness baseline lenCleanSrc = len(self._string)-self._string.count('_') lenCleanTgt = len(other._string)-other._string.count('_') #lenCleanSrc = len(''.join(self.split())) #lenCleanTgt = len(''.join(other.split())) lenClean = max( lenCleanSrc, lenCleanTgt ) return totalWeight / ( lenClean*exactMatchWeight ) def strip( self, inPlace=True ): '''strips any namespace or path data from the name string - by default the stripping is done "in place", but if the inPlace variable is set to false, then a new Name object is returned''' string = self._string.strip() for char in self.prefixDelimeters: lastMatch = string.rfind(char) if lastMatch != -1: string = string[lastMatch+1:] #if we're to perform the operation in place, then modify the self._string variable and return if inPlace: self._string = string return self return self.__class__( string ) def split( self, aString=None ): ''' retuns a list of name tokens. tokens are delimited by either camel case separation, digit grouping, or any character present in the self.punctuation variable - the list of tokens is returned ''' if aString is None: aString = self._string try: tokens = [aString[0]] except IndexError: return [] prevCharCaseWasLower = aString[0].islower() prevCharWasDigit = aString[0].isdigit() #step through the string and look for token split cases for char in aString[1:]: isLower = char.islower() if char in self.punctuation: tokens.append('') prevCharCaseWasLower = True prevCharWasDigit = False continue if char.isdigit(): if prevCharWasDigit: tokens[-1] += char else: tokens.append(char) prevCharCaseWasLower = True prevCharWasDigit = True continue if prevCharWasDigit: tokens.append(char) prevCharWasDigit = False prevCharCaseWasLower = isLower continue elif prevCharCaseWasLower and not isLower: tokens.append(char) else: tokens[-1] += char prevCharWasDigit = False prevCharCaseWasLower = isLower #finally get rid of any empty/null array entries - this could be done above but is easier (maybe even faster?) to do as a post step return [tok for tok in tokens if tok ] def redo_split( self, aString=None ): #forces a rebuild of the token cache return self.split() def hasParity( nameToks, popParityToken=True ): ''' returns a parity number for a given name. parity is 0 for none, 1 for left, and 2 for right ''' lowerToks = [ tok.lower() for tok in nameToks ] lowerToksSet = set( lowerToks ) existingParityToksL = lowerToksSet.intersection( set( parityTestsL ) ) if len( existingParityToksL ): parityStr = existingParityToksL.pop() if popParityToken: idx = lowerToks.index( parityStr ) nameToks.pop( idx ) return Parity.LEFT, parityStr existingParityToksR = lowerToksSet.intersection( set( parityTestsR ) ) if len( existingParityToksR ): parityStr = existingParityToksR.pop() if popParityToken: idx = lowerToks.index( parityStr ) nameToks.pop( idx ) return Parity.RIGHT, parityStr return Parity.NONE, None def swapParity( name ): if not isinstance( name, Name ): name = Name( name ) nameToks = name.split() lowerToks = [tok.lower() for tok in nameToks] lowerToksSet = set(lowerToks) allParityTests = [ parityTestsL, parityTestsR ] for parityTests, otherTests in zip( allParityTests, reversed( allParityTests ) ): parityTokensPresent = lowerToksSet.intersection( set(parityTests) ) if parityTokensPresent: #this is the caseless parity token parityToken = parityTokensPresent.pop() idxInName = lowerToks.index( parityToken ) idxInTokens = parityTests.index( parityToken ) #this gets us the parity token with case - so we can make sure the swapped parity token has the same case... parityToken = nameToks[ idxInName ] name[ idxInName ] = matchCase( otherTests[ idxInTokens ], parityToken ) return name return name def stripParity( name ): if not isinstance( name, Name ): name = Name( name ) nameToks = name.split() lowerToks = [ tok.lower() for tok in nameToks ] lowerToksSet = set( lowerToks ) for parityTests in (parityTestsL, parityTestsR): parityTokensPresent = lowerToksSet.intersection( set( parityTests ) ) if parityTokensPresent: parityToken = parityTokensPresent.pop() idxInName = lowerToks.index( parityToken ) name[ idxInName ] = '' return name return name def getCommonPrefix( strs ): ''' returns the longest prefix common to all given strings ''' class PrefixDifference(Exception): pass prefix = '' first = strs[ 0 ] for n, s in enumerate( first ): try: for aStr in strs[ 1: ]: if s != aStr[ n ]: raise PrefixDifference prefix += s except PrefixDifference: return prefix def matchCase( theStr, caseToMatch ): matchedCase = [] lastCaseWasLower = True for charA,charB in zip(theStr,caseToMatch): lastCaseWasLower = charB.islower() a = (charA.upper(), charA.lower()) [ lastCaseWasLower ] matchedCase.append(a) lenA, lenB = len(theStr), len(caseToMatch) if lenA > lenB: remainder = theStr[lenB:] if lastCaseWasLower: remainder = remainder.lower() matchedCase.extend( remainder ) return ''.join( matchedCase ) def matchNames( srcList, tgtList, strip=True, parity=True, unique=False, opposite=False, threshold=DEFAULT_THRESHOLD, **kwargs ): ''' given two lists of strings, this method will return a list (the same size as the first - source list) with the most appropriate matches found in the second (target) list. the args are: strip: strips off any prefixes before doing the match - see the Name.__init__ method for details on prefixes parity: parity tokens are substrings which identify what side of a body a control might lie on. see the global defines at the start of this script for examples of parity tokens unique: performs unique matches - ie each tgt will only be matched at most to one src opposite: if parity is True, only items of the same parity will be matched. if opposite is on, then items with non-zero parity will be matched to items of the other non-zero parity - ie left is mapped to right threshold: determines the minimum likeness for two names to be matched. the likeness factor is described in Name.likeness nomatch: teh object used when no match occurs - defaults to Name() ''' if isinstance(srcList, basestring): srcList = [srcList] if isinstance(tgtList, basestring): tgtList = [tgtList] #build the Name objects for the strings srcNames = [ Name(name) for name in srcList ] tgtNames = [ Name(name) for name in tgtList ] numSrc, numTgt = len(srcList), len(tgtList) nomatch = kwargs.get('nomatch', Name()) #cache prefixes so they don't affect name matching - caching them stores them on the name instance so we can retrieve them later if strip: for a in srcNames: a.cache_prefix() for a in tgtNames: a.cache_prefix() matches = [] for name in srcNames: foundExactMatch = False likenessList = [] for n, tgt in enumerate(tgtNames): likeness = name.likeness(tgt, parity) if likeness >= 1: #the pop is safe here coz we're bailing matches.append(tgt) if unique: tgtNames.pop(n) foundExactMatch = True break likenessList.append(likeness) #early out if foundExactMatch: continue #find the idx of the highest likeness bestIdx = -1 for n, curLikeness in enumerate(likenessList): if curLikeness > likenessList[bestIdx]: bestIdx = n #for th,tn in zip(likenessList,tgtNames): print th,name.split(),tn.split() #print '%s -> %s'%(name,tgtNames[bestIdx]) #print '--------------\n' if bestIdx >= 0 and likenessList[bestIdx] > threshold: #are we performing unique matching? if so, remove the best target match from the target list if unique: matches.append(tgtNames.pop(bestIdx)) else: matches.append(tgtNames[bestIdx]) else: matches.append(nomatch) #re-apply any prefixes we stripped if strip: matches = [ a.item for a in matches ] return matches def matchNamesDict( srcList, tgtList, **kwargs ): matches = matchNames(srcList, tgtList, **kwargs) matchDict = {} for src, tgt in zip(srcList, matches): matchDict[src] = tgt return matchDict class Mapping(object): def __init__( self, srcList, tgtList ): self.srcs = srcList[:] self.tgts = tgtList[:] def __iter__( self ): return iter( self.srcs ) def __len__( self ): return len( self.srcs ) def __contains__( self, item ): return item in self.asDict() def __getitem__( self, item ): return self.asDict()[ item ] def __setitem__( self, item, value ): if isinstance( value, basestring ): value = [ value ] asDict = self.asDict() asDict[ item ] = value self.setFromDict( asDict, self.srcs ) def iteritems( self ): return iter( zip( self.srcs, self.tgts ) ) def iterkeys( self ): return self.asDict().iterkeys() def itervalues( self ): return self.asDict().itervalues() def keys( self ): return self.asDict().keys() def values( self ): return self.asDict().values() def swap( self ): ''' swaps sources and targets - this is done in place ''' self.srcs, self.tgts = self.tgts, self.srcs return self def copy( self ): ''' returns a copy of the mapping object ''' return self.__class__.FromMapping( self ) def pop( self, index=-1 ): src = self.srcs.pop( index ) tgt = self.tgts.pop( index ) return src, tgt def insert( self, index, src, tgt ): self.srcs.insert( index, src ) self.tgts.insert( index, tgt ) def append( self, src, tgt ): self.srcs.append( src ) self.tgts.append( tgt ) def moveItem( self, index, places=1 ): src, tgt = self.pop( index ) self.insert( index + places, src, tgt ) def moveItemUp( self, index, places=1 ): places = abs( places ) return self.moveItem( index, -places ) def moveItemDown( self, index, places=1 ): places = abs( places ) return self.moveItem( index, places ) def setFromDict( self, mappingDict, ordering=() ): ''' Sets the mapping from a mapping dictionary. If an ordering iterable is given then the ordering of those sources is preserved. ''' srcs = [] tgts = [] def appendTgt( src, tgt ): if isinstance( tgt, basestring ): srcs.append( src ) tgts.append( tgt ) elif isinstance( tgt, (list, tuple) ): for t in tgt: srcs.append( src ) tgts.append( t ) for src in ordering: tgt = mappingDict.pop( src ) appendTgt( src, tgt ) for src, tgt in mappingDict.iteritems(): appendTgt( src, tgt ) self.srcs = srcs self.tgts = tgts def asStr( self ): return '\n'.join( [ '%s -> %s' % m for m in self.iteritems() ] ) @classmethod def FromDict( cls, mappingDict, ordering=() ): new = Mapping( [], [] ) new.setFromDict( mappingDict, ordering ) return new @classmethod def FromMapping( cls, mapping ): return cls( mapping.srcs, mapping.tgts ) def asDict( self ): matchDict = {} for src, tgt in zip(self.srcs, self.tgts): try: matchDict[ src ].append( tgt ) except KeyError: matchDict[ src ] = [ tgt ] return matchDict def asFlatDict( self ): matchDict = {} for src, tgt in zip(self.srcs, self.tgts): matchDict[ src ] = tgt return matchDict ABBRVS_TO_EXPAND = {'max': 'maximum', 'min': 'minimum'} def camelCaseToNice( theString, abbreviationsToExpand=None, niceParityNames=True ): asName = Name( theString ) words = asName.split() if niceParityNames: #does the name have parity? if so use the "nice" version of the parity string parity = asName.get_parity() if parity is not Parity.NONE: niceParityStr = (parityTestsL, parityTestsR)[ parity ][ 1 ] if abbreviationsToExpand is None: abbreviationsToExpand = {} abbreviationsToExpand[ asName._parityStr ] = niceParityStr if abbreviationsToExpand is None: words = [ w.capitalize() for w in words ] else: words = [ abbreviationsToExpand.get(w.lower(), w).capitalize() for w in words ] return ' '.join( words ) INVALID_CHARS = """`~!@#$%^&*()-+=[]\\{}|;':"/?><., """ def stripInvalidChars( theString, cleanDoubles=True, stripTrailing=True ): ''' strips "invalid" characters from the given string, replacing them with an "_" character. if cleanDoubles is true, then any double "_" occurances are replaced with a single "_" ''' for char in INVALID_CHARS: theString = theString.replace( char, '_' ) if cleanDoubles: cleaned = theString while True: cleaned = theString.replace( '__', '_' ) if cleaned == theString: break theString = cleaned theString = cleaned if stripTrailing: while theString.endswith( '_' ): theString = theString[ :-1 ] return theString #end
Python
def range2( count, start=0 ): n = start while n < count: yield n def buildMPath( objs, squish=True ): #first we need to build a curve - we build an ep curve so that it goes exactly through the joint pivots numObjs = len( objs ) cmdKw = { 'd': 1 } cmdKw[ 'p' ] = tuple( xform( obj, q=True, ws=True, rp=True ) for obj in objs ) cmdKw[ 'k' ] = range( numObjs ) baseCurve = curve( **cmdKw ) curve = fitBspline( baseCurve, ch=True, tol=0.001 )[ 0 ] curveShape = curve.getShape() infoNode = createNode( 'curveInfo' ) connectAttr( curveShape.worldSpace[ 0 ], infoNode.inputCurve, f=True ) knots = infoNode.knots.get()[ 2:-2 ] #now build the actual motion path nodes that keep the joints attached to the curve #there is one proxy for each joint. the original joints get constrained to #the proxies, which in turn get stuck to the motion path and oriented properly #then three joints get created, which are used to deform the motion path mpaths = [] proxies = [] upVectors = [] aims = [] #holds the aim constraints unitComp = 1.0 if currentUnit( q=True, l=True ) == "m": unitComp = 100.0 for n, obj in enumerate( objs ): n += 1 mpath = createNode( 'pointOnCurveInfo' ) proxy = group( em=True ) #connect axes individually so they can be broken easily if we need to... connectAttr( curveShape.worldSpace, mpath.inputCurve ) connectAttr( mpath.px, proxy.tx ) connectAttr( mpath.py, proxy.ty ) connectAttr( mpath.pz, proxy.tz ) mpath.parameter.set( knots[ n ] ) #($n/$unitComp);//were using ($knots[$n]/$unitComp) but it seems this is buggy - invalid knot values are returned for a straight curve... so it seems assuming $n is valid works in all test cases I've tried... delete( orientConstraint( obj, proxy ) ) mpaths.append( mpath ) proxies.append( proxy ) #build a motionpath to get positions along the path - mainly useful for finding the half way mark halfWayPath = createNode( 'pointOnCurveInfo' ) halfWayPos = group( em=True, n="half" ) arcLength = curveShape.maxValue.get() - curveShape.minValue.get() connectAttr( curveShape.worldSpace, halfWayPath.inputCurve ) connectAttr( halfWayPath.p, halfWayPos.t ) halfWayPath.parameter.set( knots[ -1 ] / 2.0 ) #now build the control stucture and place then deformJoints = [] half = numObjs / 2 select( d=True ) deformJoints.append( joint() ); select( d=True ) deformJoints.append( joint() ); select( d=True ) deformJoints.append( joint() ); select( d=True ) delete( parentConstraint( objs[ 0 ], deformJoints[ 0 ] ) ) delete( parentConstraint( halfWayPos, deformJoints[ 1 ] ) ) delete( parentConstraint( objs[ -1 ], deformJoints[ 2 ] ) ) #orient the middle deform object - this is harder than in sounds because the object doesn't actually correspond to #any of the proxies so what we do is find the closest proxies and average their orientations based on their proximity #it looks pretty complicated, but thats all thats going on - proximity based orient constraint weighting midObjs = [] distancesToObjs = [] isOdd = numObjs % 2 def betweenVector( objA, objB ): posA = Vector( xform( objA, q=True, ws=True, rp=True ) ) posB = Vector( xform( objB, q=True, ws=True, rp=True ) ) return posB - posA #if there is an odd number of objs in the chain, we want the surrounding three - NOTE one is almost certain to be very close, whcih is why we #do the proximity based weighting - the closest one should have the greatest effect on orientation if isOdd: midObjs[ 0 ] = objs[ half - 1 ] midObjs[ 1 ] = objs[ half ] midObjs[ 2 ] = objs[ half + 1 ] distancesToObjs[ 0 ] = betweenVector( midObjs[ 0 ], deformJoints[ 1 ] ).magnitude() distancesToObjs[ 1 ] = betweenVector( midObjs[ 1 ], deformJoints[ 1 ] ).magnitude() distancesToObjs[ 2 ] = betweenVector( midObjs[ 2 ], deformJoints[ 1 ] ).magnitude() #but if there are an even number of objs in the chain, we only want the mid two else: n = (numObjs - 1) / 2 midObjs[ 0 ] = objs[ n ] midObjs[ 1 ] = objs[ n + 1 ] distancesToObjs[ 0 ] = betweenVector( midObjs[ 0 ], deformJoints[ 1 ] ).magnitude() distancesToObjs[ 1 ] = betweenVector( midObjs[ 1 ], deformJoints[ 1 ] ).magnitude() total = sum( distancesToObjs ) distancesToObjs = [ total / d for d in distancesToObjs ] tempConstraint = orientConstraint( midObjs + [ deformJoints[1] ] )[ 0 ] for obj, weight in enuzip( midObjs, distancesToObjs ): orientConstraint( tempConstraint, obj, e=True, w=weight ) delete( tempConstraint ) makeIdentity( deformJoints, a=True, r=True ) #now weight the curve to the controls - the weighting is just based on a linear #falloff from the start to mid joint, and then from the mid joint to the end skinCluster = skinCluster( deformJoints, baseCurve ) #set the weights to 1 for the bottom and mid joint for n in range2( half ): skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[ 0 ], 1) ) for n in range2( numObjs, half ): skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[ 1 ], 1) ) #now figure out the positional mid point midToStart = betweenVector( deformJoints[ 1 ], deformJoints[ 0 ] ) startPos = Vector( xform( deformJoints[ 0 ], q=True, ws=True, rp=True ) ) halfByPos = 0 for n in range( numObjs ): pointPos = Vector( pointPosition( baseCurve.cv[ n ] ) ) relToStart = pointPos - startPos distFromStart = relToStart.magnitude() if distFromStart > midToStart: halfByPos = n break #set the weights initially fully to the end deform joints - then figure out the of each point from the mid joint, and apply a weight falloff midPos = Vector( xform( deformJoints[1], q=True, ws=True, rp=True ) ) midToEnd = betweenVector( deformJoints[2], deformJoints[1] ).magnitude() for n in range2( halfByPos ): skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[0], 1) ) for n in range2( numObjs, halfByPos ): skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[2], 1) ) for n in range2( halfByPos, 1 ): pointPos = Vector( pointPosition( baseCurve.cv[ n ] ) ) pointToMid = pointPos - midPos weight = 1 - (pointToMid.magnitude() / midToStart) skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[1], weight) ) for range2( numObjs, halfByPos ): pointPos = Vector( pointPosition( baseCurve.cv[ n ] ) ) pointToMid = pointPos - midPos weight = 1 - (pointToMid.magnitude() / midToEnd) skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[1], weight) ) parentConstraint( deformJoints[0], objs[0] ) pointConstraint( proxies[ numObjs-1 ], objs[ numObjs-1 ] ) orientConstraint( deformJoints[2], objs[ numObjs-1 ] ) #build the aim constraints for the proxies third_1st = round( numObjs / 3.0 ) third_2nd = round( ( numObjs*2.0 ) / 3.0 ) for range2( numObjs-1, 1 ): #we're using z as the aim axis for the proxies, and y for the up axis upObj = deformJoints[0] aim_float = 0, 0, 1.0 up_float = 0, 1.0, 0 if n >= third_1st and n < third_2nd: upObj = deformJoints[1] elif n >= third_2nd: upObj = deformJoints[2] #now that we have an aim vector, build the aimconstraint, then we'll need to find the up vector - we need the #proxy to be aimed at its target first however, so we can get an accurate up axis to use on the deform obj #because all this is just a proxy rig that the real skeleton is constrained to, axes are all arbitrary... delete `aimConstraint -aim $aim_float[0] $aim_float[1] $aim_float[2] -u $up_float[0] $up_float[1] $up_float[2] -wu $up_float[0] $up_float[1] $up_float[2] -wuo $upObj -wut objectrotation $proxies[( $n+1 )] $proxies[$n]`; #now we have to figure out which axis on the deform obj to use as the up axis - we do this by using the x axis on #the proxy (an arbitrary choice - could just as easily have been y) then seeing what axis is closest to that vector on the deform obj proxyUpVector = pointMatrixMult($up_float,`xform -q -m $proxies[$n]`); #get aim axis relative to the proxy - we need this so we can figure out which axis on the up object points in that direction upObjUpAxis = `zooAxisInDirection $upObj $proxyUpVector`; upVectors[ n ] = `zooArrayToStr_float $up_float " "`; #now edit the constraint to use the up vector we've determined aims[ n ] = zooGetElement_str(0,`aimConstraint -mo -aim $aim_float[0] $aim_float[1] $aim_float[2] -u $up_float[0] $up_float[1] $up_float[2] -wu $upObjUpAxis[0] $upObjUpAxis[1] $upObjUpAxis[2] -wuo $upObj -wut objectrotation $proxies[( $n+1 )] $proxies[$n]`); parentConstraint -mo $proxies[$n] $objs[$n]; #scaling? create a network to dynamically scale the objects based on the length #of the segment. there are two curve segments - start to mid, mid to end. this #scaling is done via SDK so we get control over the in/out of the scaling squishNodes = [] if squish: curveInfo = createNode( 'curveInfo' ) scaleFac = shadingNode( n='squishCalculator', asUtility='multiplyDivide' ) adder = shadingNode( n='now_add_one', asUtility='plusMinusAverage' ) sdkScaler = createNode( 'animCurveUU', n='squish_sdk' ) initialLength = 0 maxScale = 2.0 minScale = 0.25 addAttr -k 1 -ln length -at double -min 0 -max 1 -dv 1 $deformJoints[0]; addAttr -k 1 -ln squishFactor -at double -min 0 -max 1 -dv 0 $deformJoints[0]; setAttr -k 1 ( $deformJoints[0] +".length" ); setAttr -k 1 ( $deformJoints[0] +".squishFactor" ); connectAttr -f ( $curveShape +".worldSpace[0]" ) ( $curveInfo +".inputCurve" ); initialLength = `getAttr ( $curveInfo +".arcLength" )`; setAttr ( $adder +".input1D[0]" ) 1; select -cl; setKeyframe -f $initialLength -v 0 $sdkScaler; setKeyframe -f( $initialLength/100 ) -v( $maxScale-1 ) $sdkScaler; setKeyframe -f( $initialLength*2 ) -v( $minScale-1 ) $sdkScaler; keyTangent -in 0 -itt flat -ott flat $sdkScaler; keyTangent -in 2 -itt flat -ott flat $sdkScaler; connectAttr -f ( $curveInfo +".arcLength" ) ( $sdkScaler +".input" ); connectAttr -f ( $scaleFac +".outputX" ) ( $adder +".input1D[1]" ); connectAttr -f ( $sdkScaler +".output" ) ( $scaleFac +".input1X" ); connectAttr -f ( $deformJoints[0] +".squishFactor" ) ( $scaleFac +".input2X" ); for( $n=0; $n<$numObjs; $n++ ) for( $ax in {"x","y","z"} ) connectAttr -f ( $adder +".output1D" ) ( $objs[$n] +".s"+ $ax ); lengthMults = [] for n in range( numObjs, 1 ): posOnCurve = mpaths[ n ].parameter.get() lengthMults[$n] = `shadingNode -n( "length_multiplier"+ $n ) -asUtility multiplyDivide`; setAttr ( $lengthMults[$n] +".input1X" ) $posOnCurve; connectAttr -f ( $deformJoints[0] +".length" ) ( $lengthMults[$n] +".input2X" ); connectAttr -f ( $lengthMults[$n] +".outputX" ) ( $mpaths[$n] +".parameter" ); $squishNodes = [ curveInfo, scaleFac, adder, sdkScaler} $lengthMults`; #rename the curves baseCurve.rename( "pointCurve" ) curve.rename( "mPath" ) #build the controllers array for returning controllers = deformJoints controllers += [ baseCurve, curve, skinCluster ] controllers += proxies controllers += mpaths controllers += aims controllers += squishNodes delete( halfWayPos ) select( deformJoints ) return controllers
Python
from baseMelUI import * from filesystem import * import maya.cmds as cmd import api ui = None class PresetOptionMenu(MelOptionMenu): def __init__( self, parent, tool, extension, *a, **kw ): MelOptionMenu.__init__( self, parent, *a, **kw ) self.setChangeCB( self.on_change ) self._manager = PresetManager( tool, extension ) self._presets = {} self.update() def update( self ): self.clear() for locale, presets in self._manager.listAllPresets( True ).iteritems(): for preset in presets: self.append( preset.name() ) self._presets[ preset.name() ] = preset def getValue( self ): valueStr = MelOptionMenu.getValue( self ) return self._presets.get( valueStr, None ) ### EVENT HANDLERS ### def on_change( self, *a ): self.sendEvent( 'presetChanged', self.getValue() ) class PresetLayout(MelFormLayout): ALLOW_MULTI_SELECTION = True def __new__( cls, parent, *a, **kw ): return MelForm.__new__( cls, parent ) def __init__( self, parent, tool, locale=LOCAL, ext=DEFAULT_XTN ): MelForm.__init__( self, parent ) self.tool = tool self.locale = locale self.ext = ext self.presetManager = PresetManager(tool, ext) self.populate() def populate( self ): children = self( q=True, ca=True ) if children is not None: for c in children: cmd.deleteUI( c ) other = self.other() otherLbl = "<-- %s" % other cmd.setParent( self ) self.UI_lbl_title = cmd.text(l='Managing "%s" presets' % self.ext) self.UI_lbl_presets = cmd.text(l="%s presets" % self.locale) self.UI_button_swap = cmd.button(h=18, l="view %s presets" % other, c=self.swap) self.UI_tsl_presets = cmd.textScrollList(allowMultiSelection=self.ALLOW_MULTI_SELECTION, sc=self.updateButtonStatus) self.UI_button_1 = cmd.button(l="move to %s" % other, c=self.move) self.UI_button_2 = cmd.button(l="copy to %s" % other, c=self.copy) self.UI_button_3 = cmd.button(l="rename", c=self.rename) self.UI_button_4 = cmd.button(l="delete", c=self.delete) self.POP_filemenu = cmd.popupMenu(b=3, p=self.UI_tsl_presets, pmc=self.popup_filemenu) self( e=True, af=((self.UI_lbl_title, "top", 5), (self.UI_lbl_title, "left", 5), (self.UI_lbl_presets, "left", 10), (self.UI_button_swap, "right", 5), (self.UI_tsl_presets, "left", 5), (self.UI_tsl_presets, "right", 5), (self.UI_button_1, "left", 5), (self.UI_button_2, "right", 5), (self.UI_button_3, "left", 5), (self.UI_button_3, "bottom", 5), (self.UI_button_4, "right", 5), (self.UI_button_4, "bottom", 5)), ac=((self.UI_lbl_presets, "top", 10, self.UI_lbl_title), (self.UI_button_swap, "top", 7, self.UI_lbl_title), (self.UI_button_1, "bottom", 0, self.UI_button_3), (self.UI_button_swap, "left", 10, self.UI_lbl_presets), (self.UI_tsl_presets, "top", 10, self.UI_lbl_presets), (self.UI_tsl_presets, "bottom", 5, self.UI_button_1), (self.UI_button_2, "bottom", 0, self.UI_button_4)), ap=((self.UI_button_1, "right", 0, 50), (self.UI_button_2, "left", 0, 50), (self.UI_button_3, "right", 0, 50), (self.UI_button_4, "left", 0, 50)) ) self.updateList() def other( self ): ''' returns the "other" locale ''' return LOCAL if self.locale == GLOBAL else GLOBAL def updateList( self ): ''' refreshes the preset list ''' presets = self.presetManager.listPresets(self.locale) cmd.textScrollList(self.UI_tsl_presets, e=True, ra=True) self.presets = presets for p in presets: cmd.textScrollList(self.UI_tsl_presets, e=True, a=p[-1]) self.updateButtonStatus() def updateButtonStatus( self, *args ): selected = self.selected() numSelected = len(selected) if numSelected == 0: cmd.button(self.UI_button_1, e=1, en=0) cmd.button(self.UI_button_2, e=1, en=0) cmd.button(self.UI_button_3, e=1, en=0) cmd.button(self.UI_button_4, e=1, en=0) elif numSelected == 1: cmd.button(self.UI_button_1, e=1, en=1) cmd.button(self.UI_button_2, e=1, en=1) cmd.button(self.UI_button_3, e=1, en=1) cmd.button(self.UI_button_4, e=1, en=1) else: cmd.button(self.UI_button_1, e=1, en=1) cmd.button(self.UI_button_2, e=1, en=1) cmd.button(self.UI_button_3, e=1, en=0) cmd.button(self.UI_button_4, e=1, en=1) def selected( self ): ''' returns the selected presets as Path instances - if nothing is selected, an empty list is returned ''' try: selectedIdxs = [idx-1 for idx in cmd.textScrollList(self.UI_tsl_presets, q=True, sii=True)] selected = [self.presets[n] for n in selectedIdxs] return selected except TypeError: return [] def getSelectedPresetNames( self ): selected = cmd.textScrollList( self.UI_tsl_presets, q=True, si=True ) or [] return [ Path( s ).name() for s in selected ] def getSelectedPresetName( self ): try: return self.getSelectedPresetNames()[ 0 ] except IndexError: return None def copy( self, *args ): files = [] for s in self.selected(): files.append( s.copy() ) self.sendEvent( 'presetsCopied', files ) def delete( self, *args ): files = self.selected() for s in files: s.delete() self.updateList() self.sendEvent( 'presetsDeleted', files ) def move( self, *args ): files = [] movedFiles = [] for s in self.selected(): ff = s.move() movedFiles.append( ff ) self.updateList() self.sendEvent( 'presetsMoved', files ) def rename( self, *args ): ''' performs the prompting and renaming of presets ''' selected = self.selected()[0] ans, newName = api.doPrompt(m='new name', tx=selected.name()) if ans != api.OK: return if not newName.endswith('.'+ self.ext): newName += '.'+ self.ext renamedPreset = selected.rename( newName ) self.updateList() self.sendEvent( 'presetRenamed', selected, renamedPreset ) def swap( self, *args ): ''' performs the swapping from the local to global locale ''' self.locale = self.other() self.populate() def syncall( self, *a ): ''' syncs to ALL global presets for the current tool - NOTE: this syncs to all global preset dirs in the mod hierarchy... ''' dirs = getPresetDirs(self.locale, self.tool) for dir in dirs: #P4Data(dir).sync() print 'syncing to %s...' % dir.resolve().asdir() self.updateList() def on_notepad( self, filepath ): filepath = Path( filepath ) subprocess.Popen( 'notepad "%s"' % filepath.asNative(), cwd=filepath.up() ) def popup_filemenu( self, parent, *args ): cmd.menu(parent, e=True, dai=True) cmd.setParent(parent, m=True) other = self.other() items = self.selected() numItems = len(items) if numItems: cmd.menuItem(l='copy to %s' % other, c=self.copy) cmd.menuItem(l='move to %s' % other, c=self.move) if len(items) == 1: filepath = items[0].resolve() cmd.menuItem(d=True) cmd.menuItem(l='open in notepad', c=lambda *x: self.on_notepad( filepath )) cmd.menuItem(d=True) api.addExploreToMenuItems(filepath) cmd.menuItem(d=True) cmd.menuItem(l='delete', c=self.delete) #if the file is a global file, display an option to sync to presets if self.locale == GLOBAL: if numItems: cmd.menuItem(d=True) cmd.menuItem(l='sync to presets', c=self.syncall) #if no files are selected, prompt the user to select files if numItems == 0: cmd.menuItem(en=False, l='select a preset file') PresetForm = PresetLayout class PresetWindow(BaseMelWindow): WINDOW_NAME = 'presetWindow' WINDOW_TITLE = 'Preset Manager' DEFAULT_SIZE = 275, 325 DEFAULT_MENU = 'Perforce' FORCE_DEFAULT_SIZE = True def __new__( cls, *a, **kw ): return BaseMelWindow.__new__( cls ) def __init__( self, tool, locale=LOCAL, ext=DEFAULT_XTN ): BaseMelWindow.__init__( self ) self.editor = PresetForm( self, tool, locale, ext ) cmd.setParent( self.getMenu( self.DEFAULT_MENU ), m=True ) cmd.menuItem(l='Sync to Global Presets', c=lambda *a: self.editor.syncall()) self.show() def presetsCopied( self, presets ): pass def presetsDeleted( self, presets ): pass def presetsMoved( self, presets ): pass def presetRenamed( self, preset, renamedPreset ): pass PresetUI = PresetWindow def load( tool, locale=LOCAL, ext=DEFAULT_XTN ): ''' this needs to be called to load the ui properly in maya ''' global ui ui = PresetUI(tool, locale, ext) #end
Python
try: import wingdbstub except ImportError: pass from baseMelUI import * from maya.cmds import * from common import printWarningStr #this dict stores attribute values for the selection - attributeChange scriptjobs fire when an attribute changes #but don't pass in pre/post values, or even the name of the attribute that has changed. So when the scriptjobs #are first setup, their attribute values are stored in this dict and are updated when they change PRE_ATTR_VALUES = {} class AttrpathCallback(object): ''' callable object that gets executed when the value of the attrpath changes ''' #defines whether the instance should early out when called or not ENABLED = True def __init__( self, ui, attrpath ): self.ui = ui self.attrpath = attrpath #setup the initial value of the attrpath in the global attr value dict time = currentTime( q=True ) PRE_ATTR_VALUES[ attrpath ] = getAttr( attrpath ) def __call__( self ): if not self.ENABLED: return #if autokey is turned on, bail - this + autokey = potentially weird behaviour #NOTE: the tool will turn autokey off automatically when loaded - so if its on, its because the user has turned it back on. Also #worth noting - this tool will restore the initial autokey state when closed/turned off... if autoKeyframe( q=True ): printWarningStr( "Autokey is enabled - This tool doesn't play nice with autokey! Please turn it off!" ) return #if there are no entries in here - bail, they've already been handled if not PRE_ATTR_VALUES: return #put the following into a single undo chunk try: undoInfo( openChunk=True ) for attrpath, preValue in PRE_ATTR_VALUES.iteritems(): curValue = getAttr( attrpath ) valueDelta = curValue - preValue #if there was no delta, keep loopin if not valueDelta: continue #if there are no keyframes on this attribute - keep loopin if not keyframe( attrpath, q=True, kc=True ): continue keyframe( attrpath, e=True, t=(), vc=valueDelta, relative=True ) PRE_ATTR_VALUES.clear() finally: undoInfo( closeChunk=True ) #setup an idle event to re-populate the PRE_ATTR_VALUES dict when everything has finished processing scriptJob( runOnce=True, idleEvent=self.ui.on_selectionChange ) class PosePropagatorLayout(MelHLayout): def __init__( self, parent ): MelHLayout.__init__( self, parent ) self._initialAutoKeyState = autoKeyframe( q=True, state=True ) self.UI_dummyParent = None #this is some dummy UI to store attribute change scriptjobs - this easily ensures things get teared down if the tool gets closed self.UI_on = MelButton( self, h=100, c=self.on_toggleEnable ) self.layout() self.updateState() #fire the selection change to update the current selection state self.on_selectionChange() self.setSceneChangeCB( self.on_selectionChange ) self.setSelectionChangeCB( self.on_selectionChange ) self.setTimeChangeCB( self.on_timeChange ) self.setDeletionCB( self.on_delete ) def setEnableState( self, state=True ): ''' sets the on/off state of the tool and updates UI accordingly ''' #we need to disable autokey when running this tool - but we want to restore the initial autokey state when #the tool is either turned off or closed, so we need to store the initial auto key state on the instance if state: self._initialAutoKeyState = autoKeyframe( q=True, state=True ) autoKeyframe( e=True, state=False ) else: autoKeyframe( e=True, state=self._initialAutoKeyState ) AttrpathCallback.ENABLED = state self.updateState() def updateState( self ): self.UI_on.setLabel( 'currently on: turn OFF' if AttrpathCallback.ENABLED else 'turn ON' ) self.UI_on.setColour( (1, 0, 0) if AttrpathCallback.ENABLED else (0.6, 0.6, 0.6) ) ### EVENT HANDLERS ### def on_toggleEnable( self, *a ): self.setEnableState( not AttrpathCallback.ENABLED ) def on_enable( self, *a ): self.setEnableState( True ) def on_disable( self, *a ): self.setEnableState( False ) def on_sceneChange( self ): ''' turn the tool off, and update state ''' self.setEnableState( False ) self.on_selectionChange() def on_selectionChange( self ): ''' delete the old attribute change callbacks and add new ones for the current selection ''' if self.UI_dummyParent is not None: self.UI_dummyParent.delete() PRE_ATTR_VALUES.clear() #create a dummy piece of UI to "hold" on to the scriptjobs self.UI_dummyParent = UI_dummyParent = MelButton( self, l='', w=1, h=1, vis=False ) for obj in ls( sl=True ): for attr in listAttr( obj, keyable=True ): attrpath = '%s.%s' % (obj, attr) if objExists( attrpath ): UI_dummyParent.setAttributeChangeCB( attrpath, AttrpathCallback( self, attrpath ), False ) def on_timeChange( self ): ''' when the time changes we need to refresh the values in the PRE_ATTR_VALUES dict ''' time = currentTime( q=True ) PRE_ATTR_VALUES.clear() for attrpath in PRE_ATTR_VALUES.keys(): PRE_ATTR_VALUES[ attrpath ] = getAttr( attrpath ) def on_delete( self ): autoKeyframe( e=True, state=self._initialAutoKeyState ) class PosePropagatorWindow(BaseMelWindow): WINDOW_NAME = 'posePropagatorWindow' WINDOW_TITLE = 'Pose Propagator' DEFAULT_MENU = None DEFAULT_SIZE = 275, 140 FORCE_DEFAULT_SIZE = True def __init__( self ): self.UI_editor = PosePropagatorLayout( self ) self.UI_editor.setEnableState( AttrpathCallback.ENABLED ) self.show() #end
Python
from maya import cmds as cmd def d_showWaitCursor(f): ''' turns the wait cursor on while the decorated method is executing, and off again once finished ''' def func( *args, **kwargs ): cmd.waitCursor( state=True ) try: return f( *args, **kwargs ) finally: cmd.waitCursor( state=False ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_disableViews(f): ''' disables all viewports before, and re-enables them after ''' def func( *args, **kwargs ): modelPanels = cmd.getPanel( vis=True ) emptySelConn = cmd.selectionConnection() for panel in modelPanels: if cmd.getPanel( to=panel ) == 'modelPanel': cmd.isolateSelect( panel, state=True ) cmd.modelEditor( panel, e=True, mlc=emptySelConn ) try: return f( *args, **kwargs ) finally: for panel in modelPanels: if cmd.getPanel( to=panel ) == 'modelPanel': cmd.isolateSelect( panel, state=False ) cmd.deleteUI( emptySelConn ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_autoKey(f): ''' forces autoKey on ''' def func( *args, **kwargs ): initialState = cmd.autoKeyframe( q=True, state=True ) cmd.autoKeyframe( state=True ) try: return f( *args, **kwargs ) finally: cmd.autoKeyframe( state=initialState ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_noAutoKey(f): ''' forces autoKey off ''' def func( *args, **kwargs ): initialState = cmd.autoKeyframe( q=True, state=True ) cmd.autoKeyframe( state=False ) try: return f( *args, **kwargs ) finally: cmd.autoKeyframe( state=initialState ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_restoreTime(f): ''' restores the initial time once the wrapped function exits ''' def func( *args, **kwargs ): initialTime = cmd.currentTime( q=True ) try: return f( *args, **kwargs ) finally: cmd.currentTime( initialTime, e=True ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_noUndo(f): ''' forces undo off ''' def func( *args, **kwargs ): initialState = cmd.undoInfo( q=True, state=True ) cmd.undoInfo( stateWithoutFlush=False ) try: return f( *args, **kwargs ) finally: cmd.undoInfo( stateWithoutFlush=initialState ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_unifyUndo(f): ''' wraps the function into a definite undo "chunk" - why this needs to be done for python is beyond me... ''' def func( *args, **kwargs ): cmd.undoInfo( openChunk=True ) try: return f( *args, **kwargs ) finally: cmd.undoInfo( closeChunk=True ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_progress( **dec_kwargs ): ''' deals with progress window... any kwargs given to the decorator on init are passed to the progressWindow init method ''' def ffunc(f): def func( *args, **kwargs ): try: cmd.progressWindow( **dec_kwargs ) except: print 'error init-ing the progressWindow' try: return f( *args, **kwargs ) finally: cmd.progressWindow( ep=True ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func return ffunc _ANIM_LAYER_ATTRS = [ 'mute', 'solo', 'lock', 'override', #'passthrough', 'weight', #'parentMute', #'childsoloed', #'siblingSolo', #'outMute', 'preferred', 'selected', 'collapse', 'backgroundWeight' ] if mayaVer >= 2011: _ANIM_LAYER_ATTRS += [ 'rotationAccumulationMode', 'scaleAccumulationMode' ] else: _ANIM_LAYER_ATTRS += [ 'rotationInterpolateMode', 'scaleInterpolateMode' ] def d_restoreAnimLayers( f ): ''' restores animation layer state - ''' #if this excepts, just return the function as is - anim layers aren't supported by this version try: cmd.ls( typ='animLayer' ) except RuntimeError: return f def func( *a, **kw ): #store pre-function values preDict = {} selectedLayers = [] for l in cmd.ls( typ='animLayer' ): preDict[ l ] = valueDict = {} if cmd.animLayer( l, q=True, selected=True ): selectedLayers.append( l ) for attr in _ANIM_LAYER_ATTRS: valueDict[ attr ] = cmd.getAttr( '%s.%s' % (l, attr) ) #run the function try: f( *a, **kw ) finally: #restore selection and all layer attributes for l, valueDict in preDict.iteritems(): for attr, value in valueDict.iteritems(): try: cmd.setAttr( '%s.%s' % (l, attr), value ) except RuntimeError: pass for l in cmd.ls( typ='animLayer' ): cmd.animLayer( l, e=True, selected=False ) for l in selectedLayers: cmd.animLayer( l, e=True, selected=True ) cmd.animLayer( forceUIRefresh=True ) func.__name__ = f.__name__ func.__doc__ = f.__doc__ return func def d_maintainSceneSelection(f): def wrapped( *a, **kw ): initSel = cmd.ls( sl=True ) try: f( *a, **kw ) finally: if cmd.ls( sl=True ) != initSel: initSel = [ o for o in initSel if cmd.objExists( o ) ] if initSel: cmd.select( initSel ) wrapped.__name__ = f.__name__ wrapped.__doc__ = f.__doc__ return wrapped #end
Python
from baseMelUI import * from changeIkFk import ChangeIkFkLayout from changeParent import ChangeParentLayout from changeRo import ChangeRoLayout __author__ = 'hamish@valvesoftware.com' class ChangeLayout(MelColumnLayout): def __init__( self, parent ): frame = MelFrameLayout( self, l='Change Ik/Fk', cll=True, cl=False ) ChangeIkFkLayout( frame ) frame = MelFrameLayout( self, l='Change Parent', cll=True, cl=True ) ChangeParentLayout( frame ) frame = MelFrameLayout( self, l='Change Rotation Order', cll=True, cl=True ) ChangeRoLayout( frame ) class ChangeWindow(BaseMelWindow): WINDOW_NAME = 'changeTool' WINDOW_TITLE = 'Change Tools' DEFAULT_SIZE = 300, 250 DEFAULT_MENU = 'Help' FORCE_DEFAULT_SIZE = True HELP_MENU = 'ChangeTool', __author__, 'https://intranet.valvesoftware.com/wiki/index.php/Change_Tool' def __init__( self ): ChangeLayout( self ) self.show() #end
Python
from names import * from apiExtensions import * def findItem( itemName ): itemName = str( itemName ) if cmd.objExists( itemName ): return itemName match = matchNames( itemName, cmd.ls( type='transform' ) )[ 0 ] if match: return match return None def resolveMappingToScene( mapping, threshold=1.0 ): ''' takes a mapping and returns a mapping with actual scene objects ''' assert isinstance( mapping, Mapping ) toSearch = cmd.ls( typ='transform' ) existingSrcs = [] existingTgts = [] for src, tgt in mapping.iteritems(): if not cmd.objExists( src ): src = matchNames( [ src ], toSearch, **kw )[ 0 ] if not cmd.objExists( tgt ): tgt = matchNames( [ tgt ], toSearch, **kw )[ 0 ] if cmd.objExists( src ) and cmd.objExists( tgt ): existingSrcs.append( src ) existingTgts.append( tgt ) return Mapping( existingSrcs, existingTgts ) #end
Python
from baseSkeletonBuilder import * class Leg(SkeletonPart): HAS_PARITY = True PLACER_NAMES = 'footTip', 'footInner', 'footOuter', 'heel' @property def thigh( self ): return self[ 0 ] @property def knee( self ): return self[ 1 ] @property def ankle( self ): return self[ 2 ] @property def toe( self ): return self[ 3 ] if len( self ) > 3 else None @classmethod def _build( cls, parent=None, buildToe=True, toeCount=0, **kw ): idx = Parity( kw[ 'idx' ] ) partScale = kw[ 'partScale' ] parent = getParent( parent ) root = getRoot() height = xform( root, q=True, ws=True, rp=True )[ 1 ] dirMult = idx.asMultiplier() parityName = idx.asName() sidePos = dirMult * partScale / 10.0 upPos = partScale / 20.0 fwdPos = -(idx / 2) * partScale / 5.0 footHeight = height / 15.0 if buildToe else 0 kneeOutMove = dirMult * partScale / 35.0 kneeFwdMove = partScale / 20.0 thigh = createJoint( 'thigh%s' % parityName ) cmd.parent( thigh, parent, relative=True ) move( sidePos, -upPos, fwdPos, thigh, r=True, ws=True ) knee = createJoint( 'knee%s' % parityName ) cmd.parent( knee, thigh, relative=True ) move( 0, -(height - footHeight) / 2.0, kneeFwdMove, knee, r=True, ws=True ) ankle = createJoint( 'ankle%s' % parityName ) cmd.parent( ankle, knee, relative=True ) move( 0, -(height - footHeight) / 2.0, -kneeFwdMove, ankle, r=True, ws=True ) jointSize( thigh, 2 ) jointSize( ankle, 2 ) allJoints = [] if buildToe: toe = createJoint( 'toeBase%s' % parityName ) cmd.parent( toe, ankle, relative=True ) move( 0, -footHeight, footHeight * 3, toe, r=True, ws=True ) allJoints.append( toe ) jointSize( toe, 1.5 ) for n in range( toeCount ): toeN = createJoint( 'toe_%d_%s' % (n, parityName) ) allJoints.append( toeN ) #move( dirMult * partScale / 50.0, 0, partScale / 25.0, toeN, ws=True ) cmd.parent( toeN, toe, relative=True ) rotate( 0, dirMult * 15, 0, thigh, r=True, ws=True ) return [ thigh, knee, ankle ] + allJoints def _buildPlacers( self ): placers = [] scale = getItemScale( self.ankle ) p = buildEndPlacer() p = parent( p, self.toe, r=True )[0] move( 0, 0, scale/3, p, r=True ) move( 0, 0, 0, p, moveY=True, a=True, ws=True ) placers.append( p ) p = buildEndPlacer() p = parent( p, self.ankle, r=True )[0] setAttr( '%s.ty' % p, -scale/1.5 ) move( 0, 0, 0, p, moveY=True, a=True, ws=True ) placers.append( p ) p = buildEndPlacer() p = parent( p, self.ankle, r=True )[0] setAttr( '%s.ty' % p, scale/1.5 ) move( 0, 0, 0, p, moveY=True, a=True, ws=True ) placers.append( p ) p = buildEndPlacer() p = parent( p, self.ankle, r=True )[0] move( 0, 0, -scale/3, p, r=True ) move( 0, 0, 0, p, moveY=True, a=True, ws=True ) placers.append( p ) return placers def _align( self, _initialAlign=False ): normal = getPlaneNormalForObjects( self.thigh, self.knee, self.ankle ) normal *= self.getParityMultiplier() parity = self.getParity() alignAimAtItem( self.thigh, self.knee, parity, worldUpVector=normal ) alignAimAtItem( self.knee, self.ankle, parity, worldUpVector=normal ) if self.toe: alignAimAtItem( self.ankle, self.toe, parity, upVector=ENGINE_UP, upType='scene' ) else: autoAlignItem( self.ankle, parity, upVector=ENGINE_UP, upType='scene' ) for i in self.getOrphanJoints(): alignItemToLocal( i ) def visualize( self ): pass def getIkFkItems( self ): return self.thigh, self.knee, self.ankle #end
Python
''' ''' def d_initCache(f): def __init__(*args, **kwargs): self = args[0] self._CACHE_ = {} return f(*args, **kwargs) __init__.__name__ = f.__name__ __init__.__doc__ = f.__doc__ return __init__ initCache = d_initCache def d_cacheValue(f): def cachedRetValFunc(*args, **kwargs): self = args[0] try: return self._CACHE_[ f ] except KeyError: val = f(*args, **kwargs) self._CACHE_[ f ] = val return val #it may be a parent class has caching turned on, but the child class does not... except AttributeError: return f(*args, **kwargs) cachedRetValFunc.__name__ = f.__name__ cachedRetValFunc.__doc__ = f.__doc__ return cachedRetValFunc cacheValue = d_cacheValue def d_cacheValueWithArgs(f): def cachedRetValFunc(*args, **kwargs): self = args[0] funcArgsTuple = (f.__name__,)+tuple(args[1:]) try: return self._CACHE_[funcArgsTuple] except KeyError: val = f(*args, **kwargs) self._CACHE_[funcArgsTuple] = val return val except TypeError: return f(*args, **kwargs) except AttributeError: return f(*args, **kwargs) cachedRetValFunc.__name__ = f.__name__ cachedRetValFunc.__doc__ = f.__doc__ return cachedRetValFunc cacheValueWithArgs = d_cacheValueWithArgs def d_resetCache(f): def resetCacheFunc(*args, **kwargs): self = args[ 0 ] retval = f(*args, **kwargs) try: self._CACHE_.clear() return retval except AttributeError: return retval resetCacheFunc.__name__ = f.__name__ resetCacheFunc.__doc__ = f.__doc__ return resetCacheFunc resetCache = d_resetCache #end
Python
import apiExtensions from maya.cmds import * from filesystem import removeDupes def resetAttrs( obj, skipVisibility=True ): ''' simply resets all keyable attributes on a given object to its default value great for running on a large selection such as all character controls... ''' #obj = apiExtensions.asMObject( obj ) attrs = listAttr( obj, k=True, s=True, m=True ) or [] if skipVisibility: if 'visibility' in attrs: attrs.remove( 'visibility' ) if not attrs: return selAttrs = channelBox( 'mainChannelBox', q=True, sma=True ) or channelBox( 'mainChannelBox', q=True, sha=True ) for attr in attrs: #if there are selected attributes AND the current attribute isn't in the list of selected attributes, skip it... if selAttrs: attrShortName = attributeQuery( attr, n=obj, shortName=True ) if attrShortName not in selAttrs: continue default = 0 try: default = attributeQuery( attr, n=obj, listDefault=True )[ 0 ] except RuntimeError: pass attrpath = '%s.%s' % (obj, attr) if not getAttr( attrpath, settable=True ): continue #need to catch because maya will let the default value lie outside an attribute's #valid range (ie maya will let you creat an attrib with a default of 0, min 5, max 10) try: setAttr( attrpath, default ) except RuntimeError: pass #end
Python
from triggered import Trigger from names import camelCaseToNice from filesystem import removeDupes from control import getNiceName from apiExtensions import asMObject, getShortName from maya.cmds import * import re import triggered import control import rigUtils import maya.cmds as cmd import apiExtensions attrState = control.attrState AXES = rigUtils.Axis.BASE_AXES class ChangeSpaceCmd(unicode): ''' contains a bunch of higher level tools to querying the space changing command string ''' _THE_LINES = 'zooFlags;', 'zooUtils;', 'zooChangeSpace \"-attr parent %d\" %%%d;' @classmethod def Create( cls, parentIdx, parentConnectIdx ): return cls( '\n'.join( cls._THE_LINES ) % (parentIdx, parentConnectIdx) ) @classmethod def IsChangeSpaceCmd( cls, theStr ): return '\nzooChangeSpace "' in theStr def getInterestingLine( self ): for line in self.split( '\n' ): if line.startswith( 'zooChangeSpace ' ): return line def getIndex( self ): interestingLine = self.getInterestingLine() indexStr = interestingLine.split( ' ' )[ -2 ].replace( '"', '' ) return int( indexStr ) def setIndex( self, index ): lines = self.split( '\n' ) for n, line in enumerate( lines ): if line.startswith( 'zooChangeSpace ' ): toks = line.split( ' ' ) toks[ -2 ] = '%d"' % index lines[ n ] = ' '.join( toks ) return ChangeSpaceCmd( '\n'.join( lines ) ) def getConnectToken( self ): interestingLine = self.getInterestingLine() lastToken = interestingLine.split( ' ' )[ -1 ].replace( ';', '' ) return lastToken def build( src, tgts, names=None, space=None, **kw ): ''' ''' if names is None: names = [ None for t in tgts ] conditions = [] for tgt, name in zip( tgts, names ): cond = add( src, tgt, name, space, **kw ) conditions.append( cond ) return conditions CONSTRAINT_TYPES = CONSTRAINT_PARENT, CONSTRAINT_POINT, CONSTRAINT_ORIENT = 'parentConstraint', 'pointConstraint', 'orientConstraint' CONSTRAINT_CHANNELS = { CONSTRAINT_PARENT: (['t', 'r'], ['ct', 'cr']), CONSTRAINT_POINT: (['t'], ['ct']), CONSTRAINT_ORIENT: (['r'], ['cr']) } NO_TRANSLATION = { 'skipTranslationAxes': ('x', 'y', 'z') } NO_ROTATION = { 'skipRotationAxes': ('x', 'y', 'z') } def add( src, tgt, name=None, space=None, maintainOffset=True, nodeWithParentAttr=None, skipTranslationAxes=(), skipRotationAxes=(), constraintType=CONSTRAINT_PARENT ): global AXES AXES = list( AXES ) if space is None: space = listRelatives( src, p=True, pa=True )[ 0 ] if nodeWithParentAttr is None: nodeWithParentAttr = src if not name: name = getNiceName( tgt ) if name is None: name = camelCaseToNice( str( tgt ) ) #if there is an existing constraint, check to see if the target already exists in its target list - if it does, return the condition used it uses attrState( space, ('t', 'r'), lock=False ) existingConstraint = findConstraint( src ) if existingConstraint: constraintType = nodeType( existingConstraint ) constraintFunc = getattr( cmd, constraintType ) targetsOnConstraint = constraintFunc( existingConstraint, q=True, tl=True ) if tgt in targetsOnConstraint: idx = targetsOnConstraint.index( tgt ) aliases = constraintFunc( existingConstraint, q=True, weightAliasList=True ) cons = listConnections( '%s.%s' % (existingConstraint, aliases[ idx ]), type='condition', d=False ) return cons[ 0 ] #when skip axes are specified maya doesn't handle things properly - so make sure #ALL transform channels are connected, and remove unwanted channels at the end... preT, preR = getAttr( '%s.t' % space )[0], getAttr( '%s.r' % space )[0] if existingConstraint: chans = CONSTRAINT_CHANNELS[ constraintType ] for channel, constraintAttr in zip( *chans ): for axis in AXES: spaceAttr = '%s.%s%s' %( space, channel, axis) conAttr = '%s.%s%s' % (existingConstraint, constraintAttr, axis) if not isConnected( conAttr, spaceAttr ): connectAttr( conAttr, spaceAttr ) #get the names for the parents from the parent enum attribute cmdOptionKw = { 'mo': True } if maintainOffset else {} if objExists( '%s.parent' % nodeWithParentAttr ): srcs, names = getSpaceTargetsNames( src ) addAttr( '%s.parent' % nodeWithParentAttr, e=True, enumName=':'.join( names + [name] ) ) #if we're building a pointConstraint instead of a parent constraint AND we already #have spaces on the object, we need to turn the -mo flag off regardless of what the #user set it to, as the pointConstraint maintain offset has different behaviour to #the parent constraint if constraintType in ( CONSTRAINT_POINT, CONSTRAINT_ORIENT ): cmdOptionKw = {} else: addAttr( nodeWithParentAttr, ln='parent', at="enum", en=name ) setAttr( '%s.parent' % nodeWithParentAttr, keyable=True ) #now build the constraint constraintFunction = getattr( cmd, constraintType ) constraint = constraintFunction( tgt, space, **cmdOptionKw )[ 0 ] weightAliasList = constraintFunction( constraint, q=True, weightAliasList=True ) targetCount = len( weightAliasList ) constraintAttr = weightAliasList[ -1 ] condition = shadingNode( 'condition', asUtility=True, n='%s_to_space_%s#' % (getShortName( src ), getShortName( tgt )) ) setAttr( '%s.secondTerm' % condition, targetCount-1 ) setAttr( '%s.colorIfTrue' % condition, 1, 1, 1 ) setAttr( '%s.colorIfFalse' % condition, 0, 0, 0 ) connectAttr( '%s.parent' % nodeWithParentAttr, '%s.firstTerm' % condition ) connectAttr( '%s.outColorR' % condition, '%s.%s' % (constraint, constraintAttr) ) #find out what symbol to use to find the parent attribute parentAttrIdx = 0 if not apiExtensions.cmpNodes( space, src ): parentAttrIdx = triggered.addConnect( src, nodeWithParentAttr ) #add the zooObjMenu commands to the object for easy space switching Trigger.CreateMenu( src, "parent to %s" % name, ChangeSpaceCmd.Create( targetCount-1, parentAttrIdx ) ) #when skip axes are specified maya doesn't handle things properly - so make sure #ALL transform channels are connected, and remove unwanted channels at the end... for axis, value in zip( AXES, preT ): if axis in skipTranslationAxes: attr = '%s.t%s' % (space, axis) delete( attr, icn=True ) setAttr( attr, value ) for axis, value in zip( AXES, preR ): if axis in skipRotationAxes: attr = '%s.r%s' % (space, axis) delete( attr, icn=True ) setAttr( attr, value ) #make the space node non-keyable and lock visibility attrState( space, [ 't', 'r', 's' ], lock=True ) attrState( space, 'v', *control.HIDE ) return condition def removeSpace( src, tgt ): ''' removes a target (or space) from a "space switching" object ''' tgts, names = getSpaceTargetsNames( src ) tgt_mobject = asMObject( tgt ) name = None for index, (aTgt, aName) in enumerate( zip( tgts, names ) ): aTgt = asMObject( aTgt ) if aTgt == tgt_mobject: name = aName break if name is None: raise AttributeError( "no such target" ) delete = False if len( tgts ) == 1: delete = True constraint = findConstraint( src ) parentAttrOn = findSpaceAttrNode( src ) space = findSpace( src ) srcTrigger = Trigger( src ) cmds = srcTrigger.iterMenus() if delete: delete( constraint ) deleteAttr( '%s.parent' % src ) else: constraintType = nodeType( constraint ) constraintFunc = getattr( cmd, constraintType ) constraintFunc( tgt, constraint, rm=True ) for slot, cmdName, cmdStr in srcTrigger.iterMenus(): if cmdName == ( "parent to %s" % name ): srcTrigger.removeMenu( slot ) #rebuild the parent attribute newNames = names[:] newNames.pop( index ) addAttr( '%s.parent' % parentAttrOn, e=True, enumName=':'.join( newNames ) ) #now we need to update the indicies in the right click command - all targets that were beyond the one we #just removed need to have their indices decremented for slot, cmdName, cmdStr in srcTrigger.iterMenus(): if not cmdName.startswith( 'parent to ' ): continue cmdStrObj = ChangeSpaceCmd( cmdStr ) cmdIndex = cmdStrObj.getIndex() if cmdIndex < index: continue cmdStrObj = cmdStrObj.setIndex( cmdIndex-1 ) srcTrigger.setMenuCmd( slot, cmdStrObj ) def getSpaceName( src, theTgt ): ''' will return the user specified name given to a particular target object ''' tgts, names = getSpaceTargetsNames( src ) for tgt, name in zip( tgts, names ): if tgt == theTgt: return name def getSpaceTargetsNames( src ): ''' this procedure returns a 2-tuple: a list of all targets, and a list of user specified names - for the right click menus ''' constraint = findConstraint( src ) if constraint is None: return [], [] space = findSpace( src, constraint ) if space is None: return [], [] constraintType = nodeType( constraint ) constraintFunc = getattr( cmd, constraintType ) targetsOnConstraint = constraintFunc( constraint, q=True, tl=True ) trigger = Trigger( src ) SPECIAL_STRING = 'parent to ' LEN_SPECIAL_STRING = len( SPECIAL_STRING ) tgts, names = [], [] for slotIdx, slotName, slotCmd in trigger.iterMenus(): if slotName.startswith( SPECIAL_STRING ): names.append( slotName[ LEN_SPECIAL_STRING: ] ) cmdStrObj = ChangeSpaceCmd( slotCmd ) cmdIndex = cmdStrObj.getIndex() tgts.append( targetsOnConstraint[ cmdIndex ] ) return tgts, names def findSpace( obj, constraint=None ): ''' will return the node being used as the "space node" for any given space switching object ''' if constraint is None: constraint = findConstraint( obj ) if constraint is None: return None cAttr = '%s.constraintParentInverseMatrix' % constraint spaces = listConnections( cAttr, type='transform', d=False ) if spaces: future = ls( listHistory( cAttr, f=True ), type='transform' ) if future: return future[ -1 ] def findConstraint( obj ): ''' will return the name of the constraint node thats controlling the "space node" for any given space switching object ''' parentAttrOn = findSpaceAttrNode( obj ) if parentAttrOn is None: return None pAttr = '%s.parent' % parentAttrOn if not objExists( pAttr ): return None conditions = listConnections( pAttr, type='condition', s=False ) or [] for condition in conditions: constraints = listConnections( '%s.outColorR' % condition, type='constraint', s=False ) if constraints: return constraints[ 0 ] return None def findSpaceAttrNode( obj ): ''' returns the node that contains the parent attribute for the space switch ''' parentAttrOn = ""; trigger = Trigger( obj ) for slotIdx, slotName, slotCmd in trigger.iterMenus(): if slotName.startswith( 'parent to ' ): cmdStrObj = ChangeSpaceCmd( slotCmd ) connectToken = cmdStrObj.getConnectToken() return trigger.resolve( connectToken ) #end
Python
from maya.cmds import * def getNamespaceTokensFromReference( node ): ''' returns a list of namespaces added to the given node via referencing ''' if not referenceQuery( node, inr=True ): return [] theReferenceFilepath = referenceQuery( node, filename=True ) theReferenceNode = file( theReferenceFilepath, q=True, referenceNode=True ) theReferenceNamespace = file( theReferenceFilepath, q=True, namespace=True ) #now get the parent namespaces for the reference - these are the namespaces found on the reference node namespaces = theReferenceNode.split( ':' ) #pop the last token - its the name of the reference node namespaces.pop() namespaces.append( theReferenceNamespace ) return namespaces def stripReferenceNamespaceFromNode( node ): ''' strips off any namespaces from the given node that were added due to referencing ''' referenceNamespaceToks = getNamespaceTokensFromReference( node ) return stripNamespaceFromNode( node, referenceNamespaceToks ) def stripNamespaceFromNode( node, namespace ): ''' Strips off the given namespace from the given node if possible If not possible, the original node name is returned ''' if namespace.endswith( ':' ): namespace = namespace[ :-1 ] return stripNamespaceTokensFromNode( namespace.split( ':' ) ) def stripNamespaceTokensFromNode( node, namespaceToks ): ''' Strips off the given namespace tokens from the given node if possible If not possible, the original node name is returned ''' numNamespaceToks = len( namespaceToks ) if not namespaceToks: return node #if the node name is a name path, we'll need to remove the referenced namespace tokens from each name path... pathToks = node.split( '|' ) newPathToks = [] for pathTok in pathToks: pathNamespaceToks = pathTok.split( ':' ) if pathNamespaceToks[ :numNamespaceToks ] == namespaceToks: newPathToks.append( ':'.join( pathNamespaceToks[ numNamespaceToks: ] ) ) else: newPathToks.append( pathTok ) return '|'.join( newPathToks ) def addNamespaceTokNamePath( name, namespace ): ''' adds the given namespace to a name path. example: addNamespaceTokNamePath( 'some|name|path', 'ns' ) returns: 'ns:some|ns:name|ns:path' ''' if namespace.endswith( ':' ): namespace = namespace[ :-1 ] namespacedToks = [] for pathTok in name.split( name, '|' ): namespacedToks.append( '%s:%s' % (namespace, name) ) return '|'.join( namespacedToks ) #end
Python
from maya.cmds import * from maya import OpenMaya from filesystem import Path, Preset, GLOBAL, LOCAL, removeDupes from names import * from vectors import * from melUtils import mel from picker import resolveCmdStr from mappingUtils import * from common import printWarningStr, printErrorStr from mayaDecorators import d_noAutoKey, d_unifyUndo, d_disableViews, d_restoreTime import api import maya TOOL_NAME = 'xferAnim' EXTENSION = 'postTraceScheme' eul = OpenMaya.MEulerRotation AXES = "x", "y", "z" kROOS = "xyz", "yzx", "zxy", "xzy", "yxz", "zyx" kM_ROOS = [eul.kXYZ, eul.kYZX, eul.kZXY, eul.kXZY, eul.kYXZ, eul.kZYX] POST_TRACE_ATTR_NAME = 'xferPostTraceCmd' MATRIX_ROTATION_ORDER_CONVERSIONS_TO = Matrix.ToEulerXYZ, Matrix.ToEulerYZX, Matrix.ToEulerZXY, Matrix.ToEulerXZY, Matrix.ToEulerYXZ, Matrix.ToEulerZYX def bakeRotateDelta( src, ctrl, presetStr ): ''' Bakes a post trace command into the ctrl object such that when ctrl is aligned to src (with post trace cmds enabled) src and tgt are perfectly aligned. This is useful because rig controls are rarely aligned to the actual joints they drive, but it can be useful when you have motion from a tool such as SFM, or generated from motion capture that needs to be applied back to a rig. ''' mat_j = Matrix( getAttr( '%s.worldInverseMatrix' % srcJoint ) ) mat_c = Matrix( getAttr( '%s.worldMatrix' % jointControl ) ) #generate the matrix describing offset between joint and the rig control mat_o = mat_j * mat_c #put into space of the control rel_mat = mat_o * Matrix( getAttr( '%s.parentInverseMatrix' % jointControl ) ) #now figure out the euler rotations for the offset ro = getAttr( '%s.ro' % jointControl ) offset = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ ro ]( rel_mat, True ) cmd.rotate( asEuler[ 0 ], asEuler[ 1 ], asEuler[ 2 ], jointControl, relative=True, os=True ) mel.zooSetPostTraceCmd( ctrl, presetStr % offset ) mel.zooAlign( "-src %s -tgt %s -postCmds 1" % (src, ctrl) ) return offset def bakeManualRotateDelta( src, ctrl, presetStr ): ''' When you need to apply motion from a skeleton that is completely different from a skeleton driven by the rig you're working with (transferring motion from old assets to newer assets for example) you can manually align the control to the joint and then use this function to generate offset rotations and bake a post trace cmd. ''' srcInvMat = Matrix( getAttr( '%s.worldInverseMatrix' % src ) ) ctrlMat = Matrix( getAttr( '%s.worldMatrix' % ctrl ) ) #generate the offset matrix as mat_o = ctrlMat * srcInvMat #now figure out the euler rotations for the offset ro = getAttr( '%s.ro' % ctrl ) rotDelta = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ ro ]( mat_o, True ) #now get the positional delta posDelta = Vector( xform( src, q=True, ws=True, rp=True ) ) - Vector( xform( ctrl, q=True, ws=True, rp=True ) ) posDelta *= -1 ctrlParentInvMat = Matrix( getAttr( '%s.parentInverseMatrix' % ctrl ) ) posDelta = posDelta * ctrlParentInvMat #construct a list to use for the format str formatArgs = tuple( rotDelta ) + tuple( posDelta ) #build the post trace cmd str mel.zooSetPostTraceCmd( ctrl, presetStr % formatArgs ) return rotDelta #this dict contains UI labels and a presets for offset commands... when adding new ones make sure it contains exactly three format strings... CMD_PRESETS = CMD_DEFAULT, CMD_SRC_TGT, CMD_IK_FOOT, CMD_COPY = ( ('rotate -r -os %0.2f %0.2f %0.2f #; move -r -os %0.4f %0.4f %0.4f #;', bakeManualRotateDelta), ('rotate -r -os %0.2f %0.2f %0.2f #; move -r -os %0.4f %0.4f %0.4f #;', bakeRotateDelta), ('rotate -r -os %0.2f %0.2f %0.2f #; move -r -os %0.4f %0.4f %0.4f #; traceToe # %%opt0%% x z;', bakeRotateDelta), ('float $f[] = `getAttr %%opt0%%.r`; setAttr #.rx $f[0]; setAttr #.ry $f[1]; setAttr #.rz $f[2];', None) ) def savePostTraceScheme( presetName ): ''' stores all post trace commands found in the current scene out to disk ''' #grab a list of transforms with post trace commands on them postTraceNodes = ls( "*.%s" % POST_TRACE_ATTR_NAME, r=True ) postTraceDict = {} for n in postTraceNodes: noNS = n.split( ':' )[ -1 ] #strip the namespace noNS = noNS.split( '.' )[ 0 ] #strip the attribute postTraceDict[ noNS ] = getAttr( n ) xportDict = api.writeExportDict( TOOL_NAME, 0 ) p = Preset( GLOBAL, TOOL_NAME, presetName, EXTENSION ) p.pickle( (xportDict, postTraceDict) ) return p def clearPostTraceScheme(): postTraceNodes = ls( "*.%s" % POST_TRACE_ATTR_NAME, r=True ) for n in postTraceNodes: #ideally delete the attribute try: deleteAttr( n ) #this can happen if the node is referenced - so just set it to an empty string... except RuntimeError: setAttr( n, '', typ='string' ) def loadPostTraceSchemeFilepath( presetFile ): ''' re-applies a stored post trace command scheme back to the controls found in the current scene ''' #first we need to purge all existing post trace commands clearPostTraceScheme() if not isinstance( presetFile, Path ): presetFile = Path( presetFile ) if not presetFile.isfile(): raise IOError, "no such preset" xportDict, postTraceDict = presetFile.unpickle() for n, postTraceCmd in postTraceDict.iteritems(): n = n.split( '.' )[ 0 ] #strip off the attribute possibles = ls( '*%s' % n, r=True ) if possibles: nInScene = possibles[0] mel.zooSetPostTraceCmd( nInScene, postTraceCmd ) def loadPostTraceScheme( presetName ): ''' added so the load save commands are symmetrical - its sometimes more convenient to load from just a preset name instead of a full filepath... esp when debugging ''' p = findPreset( presetName, TOOL_NAME, EXTENSION, LOCAL ) return loadPostTraceSchemeFilepath( p ) def autoGeneratePostTraceScheme( mapping, presetName=None ): cmdStr, cmdFunc = CMD_DEFAULT for src, tgt in mapping.iteritems(): src, tgt = findItem( src ), findItem( tgt ) if not src: continue if not tgt: continue t, r = getAttr( '%s.t' % tgt )[0], getAttr( '%s.r' % tgt )[0] print tgt, cmdFunc( src, tgt, cmdStr ) try: setAttr( '%s.t' % tgt, *t ) except RuntimeError: pass try: setAttr( '%s.r' % tgt, *r ) except RuntimeError: pass if presetName is not None: print 'SAVING TO', presetName savePostTraceScheme( presetName ) def getMappingFromPreset( presetName ): ''' parses a mapping file and returns the mapping dict ''' p = findPreset( presetName, 'zoo', 'mapping', LOCAL ) return p.read() def getPostTraceCmd( node ): return getAttr( '%s.%s' % (node, POST_TRACE_ATTR_NAME) ) def executePostTraceCmd( node ): cmdStr = getPostTraceCmd( node ) resolvedCmdStr = resolveCmdStr( cmdStr, node, [] ) mel.eval( resolvedCmdStr ) """ def trace( srcs, tgts, keysOnly=True, matchRotationOrder=True, processPostCmds=True, sortByHeirarchy=True, start=None, end=None, skip=1 ): if start is None: keys = keyframe( srcs, q=True ) keys.sort() start = keys[0] if end is None: keys = keyframe( srcs, q=True ) keys.sort() end = keys[-1] api.mel.zooXferAnimUtils() api.mel._zooXferTrace( srcs, tgts, 2 if keysOnly else 0, 0, int( matchRotationOrder ), int( processPostCmds ), int( sortByHeirarchy ), int( start ), int( end ), int( skip ) ) """ def constructDummyParentConstraint( src, tgt ): grp = group( em=True ) constraintNode = parentConstraint( src, grp )[0] parent( constraintNode, w=True ) delete( grp ) connectAttr( '%s.ro' % tgt, '%s.constraintRotateOrder' % constraintNode ) connectAttr( '%s.rotatePivotTranslate' % tgt, '%s.constraintRotateTranslate' % constraintNode ) connectAttr( '%s.rotatePivot' % tgt, '%s.constraintRotatePivot' % constraintNode ) connectAttr( '%s.parentInverseMatrix' % tgt, '%s.constraintParentInverseMatrix' % constraintNode ) return constraintNode def getParentCount( node ): count = 1 nodeParent = node while nodeParent: nodeParent = listRelatives( nodeParent, p=True, pa=True ) if nodeParent is None: break count += 1 return count class TracePair(object): SHORT_TRANSFORM_ATTRS = ('tx', 'ty', 'tz', 'rx', 'ry', 'rz') def __init__( self, src, tgt ): self._src = src self._tgt = tgt self._isTransform = objectType( src, isAType='transform' ) and objectType( tgt, isAType='transform' ) self._keyTimeData = {} self._postTraceCmd = None self._constraint = None self._parentCount = getParentCount( tgt ) self._attrsWeightedTangentsDealtWith = [] def __repr__( self ): return '%s( "%s", "%s" )' % (type( self ).__name__, self._src, self._tgt) __str__ = __repr__ def isTransform( self ): return self._isTransform def getSrcTgt( self ): return self._src, self._tgt def getParentCount( self ): return self._parentCount def getKeyTimes( self ): return self._keyTimeData.keys() def dealWithWeightedTangents( self, tgtAttrpath ): ''' this is annoying - so maya has two types of curves - weighted and non-weighted tangent curves, and they've not compatible. so we need to see what the type of the curve we're querying and make sure the keys we trace have the same curve type. this is easier said than done - the tgt object may already have keys. if it does, we can just convert the curve right now and be done with it, but if it doesn't, then we need to convert the curve to weighted tangents after the first key is set, or mess with the users preferences. neither is pretty... god maya sucks ''' if keyframe( tgtAttrpath, q=True, kc=True ): attr = tgtAttrpath[ tgtAttrpath.find( '.' ) + 1: ] srcAttrpath = '%s.%s' % (self._src, attr) srcWeightedTangentState = keyTangent( srcAttrpath, q=True, weightedTangents=True )[0] tgtWeightedTangentState = keyTangent( tgtAttrpath, q=True, weightedTangents=True )[0] if srcWeightedTangentState != tgtWeightedTangentState: keyTangent( tgtAttrpath, e=True, weightedTangents=srcWeightedTangentState ) self._attrsWeightedTangentsDealtWith.append( tgtAttrpath ) def preTrace( self ): if self._isTransform: if self._constraint is None: self._constraint = constructDummyParentConstraint( self._src, self._tgt ) #now grab any other keyable attributes keyableAttrs = listAttr( self._src, keyable=True, scalar=True, shortNames=True ) or [] for attr in keyableAttrs: tgtAttrpath = '%s.%s' % (self._tgt, attr) if not objExists( tgtAttrpath ): continue #check to see if we need to deal with weighted tangents srcAttrpath = '%s.%s' % (self._src, attr) if tgtAttrpath not in self._attrsWeightedTangentsDealtWith: self.dealWithWeightedTangents( tgtAttrpath ) #now get the list of keys for the attribute and store that as well srcKeysTimes = keyframe( srcAttrpath, q=True ) if srcKeysTimes: srcKeysInTangents = keyTangent( srcAttrpath, q=True, itt=True ) srcKeysOutTangents = keyTangent( srcAttrpath, q=True, ott=True ) srcKeysInX = keyTangent( srcAttrpath, q=True, ix=True ) srcKeysInY = keyTangent( srcAttrpath, q=True, iy=True ) srcKeysOutX = keyTangent( srcAttrpath, q=True, ox=True ) srcKeysOutY = keyTangent( srcAttrpath, q=True, oy=True ) #if the attr is a transform attr - set the srcAttrpath to the appropriate attribute on the constraint if attr in self.SHORT_TRANSFORM_ATTRS: srcAttrpath = '%s.c%s' % (self._constraint, attr) for keyTime, keyItt, keyOtt, ix, iy, ox, oy in zip( srcKeysTimes, srcKeysInTangents, srcKeysOutTangents, srcKeysInX, srcKeysInY, srcKeysOutX, srcKeysOutY ): self._keyTimeData.setdefault( keyTime, [] ) self._keyTimeData[ keyTime ].append( (srcAttrpath, tgtAttrpath, keyItt, keyOtt, ix, iy, ox, oy) ) #finally see if the node has a post trace cmd - if it does, track it postTraceCmdAttrpath = '%s.xferPostTraceCmd' % self._tgt if objExists( postTraceCmdAttrpath ): cmdStr = getAttr( postTraceCmdAttrpath ) self._postTraceCmd = resolveCmdStr( cmdStr, self._tgt, [] ) def traceFrame( self, keyTime ): if keyTime not in self._keyTimeData: return attrDataList = self._keyTimeData[ keyTime ] for attrData in attrDataList: #unpack the node data srcAttrpath, tgtAttrpath, keyItt, keyOtt, ix, iy, ox, oy = attrData #NOTE: setting itt and ott in the keyframe command doesn't work properly - if itt is spline and ott is stepped, maya sets them both to stepped... win. setKeyframe( tgtAttrpath, v=getAttr( srcAttrpath ) ) #check to see if we need to deal with weighted tangents #NOTE: we need to do this BEFORE setting any tangent data! if tgtAttrpath not in self._attrsWeightedTangentsDealtWith: self.dealWithWeightedTangents( tgtAttrpath ) #need to special case this otherwise maya will screw up the stepped tangents on the out curve... holy shit maya sucks :( if keyOtt == 'step': keyTangent( tgtAttrpath, e=True, t=(keyTime,), itt=keyItt, ott=keyOtt )#, ix=ix, iy=iy ) else: keyTangent( tgtAttrpath, e=True, t=(keyTime,), itt=keyItt, ott=keyOtt )#, ix=ix, iy=iy, ox=ox, oy=oy ) #execute any post trace command for the tgt nodes on this keyframe if self._postTraceCmd: postTraceCmdStr = resolveCmdStr( self._postTraceCmd, self._tgt, [] ) if postTraceCmdStr: maya.mel.eval( postTraceCmdStr ) #once the post trace cmd has been executed, make sure to re-key each attribute with a key on this frame for attrData in attrDataList: tgtAttrpath = attrData[1] setKeyframe( tgtAttrpath ) def postTrace( self ): if self._constraint: delete( self._constraint ) self._constraint = None #run an euler filter on the rotation curves if self._isTransform: filterCurve( '%s.rx' % self._tgt, '%s.ry' % self._tgt, '%s.rz' % self._tgt, filter='euler' ) class Tracer(object): def __init__( self, keysOnly=True, matchRotationOrder=True, processPostCmds=True, sortByHeirarchy=True, start=None, end=None, skip=1 ): self._tracePairs = [] self._keysOnly = keysOnly self._matchRotationOrder = matchRotationOrder self._processPostCmds = processPostCmds self._start = start self._end = end self._skipFrames = skip def setKeysOnly( self, state ): self._keysOnly = state def setMatchRotationOrder( self, state ): self._matchRotationOrder = state def setProcessPostCmds( self, state ): self._processPostCmds = state def setStart( self, frame ): self._start = frame def setEnd( self, frame ): self._end = frame def setSkip( self, count ): self._skipFrames = cound def _sortTransformNodes( self ): ''' ensures all nodes in the _keysTransformAttrpathDict are sorted hierarchically ''' parentCountDecoratedTracePairs = [] for tracePair in self._tracePairs: parentCountDecoratedTracePairs.append( (tracePair.getParentCount(), tracePair) ) parentCountDecoratedTracePairs.sort() tracePairs = [ tracePair for pCnt, tracePair in parentCountDecoratedTracePairs ] self._tracePairs = tracePairs def appendPair( self, src, tgt ): if not objExists( src ) or not objExists( tgt ): printWarningStr( "Either the src or tgt nodes don't exist!" ) return self._tracePairs.append( TracePair( src, tgt ) ) def setSrcsAndTgts( self, srcList, tgtList ): for src, tgt in zip( srcList, tgtList ): self.appendPair( src, tgt ) def getKeyTimes( self ): ''' returns a list of key times ''' if self._keysOnly: keyTimes = [] for tracePair in self._tracePairs: keyTimes += tracePair.getKeyTimes() keyTimes = list( set( keyTimes ) ) #this removes duplicates keyTimes.sort() return keyTimes else: start = self._start if start is None: start = playbackOptions( q=True, min=True ) end = self._end if end is None: end = playbackOptions( q=True, max=True ) keyTimes = range( start, end, self._skipFrames ) def getTransformNodePairs( self ): transformNodePairs = [] for tracePair in self._tracePairs: if tracePair.isTransform(): transformNodePairs.append( tracePair ) return transformNodePairs @d_unifyUndo @d_noAutoKey @d_disableViews @d_restoreTime def trace( self ): if not self._tracePairs: printWarningStr( "No objects to trace!" ) return #wrap the following in a try so we can ensure cleanup gets called always try: #make sure the objects in the transform list are sorted properly self._sortTransformNodes() #run the pre-trace method on all tracePair instances for tracePair in self._tracePairs: tracePair.preTrace() #early out if there are no keyframes keyTimes = self.getKeyTimes() if not keyTimes: printWarningStr( "No keys to trace!" ) return #match rotation orders if required transformTracePairs = list( self.getTransformNodePairs() ) if self._matchRotationOrder: for tracePair in transformTracePairs: src, tgt = tracePair.getSrcTgt() if getAttr( '%s.ro' % tgt, se=True ): setAttr( '%s.ro' % tgt, getAttr( '%s.ro' % src ) ) #clear out existing animation for the duration of the trace on target nodes for tracePair in self._tracePairs: src, tgt = tracePair.getSrcTgt() cutKey( tgt, t=(keyTimes[0], keyTimes[-1]), clear=True ) #execute the traceFrame method for each tracePair instance for keyTime in keyTimes: currentTime( keyTime ) for tracePair in self._tracePairs: tracePair.traceFrame( keyTime ) #make sure the postTrace method gets executed once the trace finishes finally: for tracePair in self._tracePairs: tracePair.postTrace() def trace( srcs, tgts, keysOnly=True, matchRotationOrder=True, processPostCmds=True, sortByHeirarchy=True, start=None, end=None, skip=1 ): tracer = Tracer( keysOnly, matchRotationOrder, processPostCmds, sortByHeirarchy, start, end, skip ) tracer.setSrcsAndTgts( srcs, tgts ) tracer.trace() class AnimCurveCopier(object): def __init__( self, srcAnimCurve, tgtAnimCurve ): self._src = srcAnimCurve self._tgt = tgtAnimCurve def iterSrcTgtKeyIndices( self ): src, tgt = self._src, self._tgt srcIndices = getAttr( '%s.keyTimeValue' % src, multiIndices=True ) or [] tgtIndices = getAttr( '%s.keyTimeValue' % tgt, multiIndices=True ) or [] srcTimeValues = getAttr( '%s.keyTimeValue[*]' % src ) or [] tgtTimeValues = getAttr( '%s.keyTimeValue[*]' % tgt ) or [] zippedTgtData = zip( tgtIndices, tgtTimeValues ) for srcIdx, (srcTime, srcValue) in zip( srcIndices, srcTimeValues ): for n, (tgtIdx, (tgtTime, tgtValue)) in enumerate( zippedTgtData ): if srcTime == tgtTime: yield (srcIdx, srcTime, srcValue), (tgtIdx, tgtTime, tgtValue) zippedTgtData = zippedTgtData[ n: ] #chop off the values before this one - we don't need to iterate over them again... break def copy( self, values=True, tangents=True, other=True ): src, tgt = self._src, self._tgt for srcData, tgtData in self.iterSrcTgtKeyIndices(): srcIdx, srcTime, srcValue = srcData tgtIdx, tgtTime, tgtValue = tgtData #if values: #setAttr( '%s.keyTimeValue[%d]' % (tgt, tgtIdx), tgtTime, srcValue ) if tangents: setAttr( '%s.keyTanLocked[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanLocked[%d]' % (tgt, tgtIdx) ) ) setAttr( '%s.keyWeightLocked[%d]' % (tgt, tgtIdx), getAttr( '%s.keyWeightLocked[%d]' % (tgt, tgtIdx) ) ) setAttr( '%s.keyTanInX[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanInX[%d]' % (tgt, tgtIdx) ) ) setAttr( '%s.keyTanInY[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanInY[%d]' % (tgt, tgtIdx) ) ) setAttr( '%s.keyTanOutX[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanOutX[%d]' % (tgt, tgtIdx) ) ) setAttr( '%s.keyTanOutY[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanOutY[%d]' % (tgt, tgtIdx) ) ) setAttr( '%s.keyTanInType[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanInType[%d]' % (tgt, tgtIdx) ) ) setAttr( '%s.keyTanOutType[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanOutType[%d]' % (tgt, tgtIdx) ) ) if other: setAttr( '%s.keyBreakdown[%d]' % (tgt, tgtIdx), getAttr( '%s.keyBreakdown[%d]' % (tgt, tgtIdx) ) ) #setAttr( '%s.keyTickDrawSpecial[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTickDrawSpecial[%d]' % (tgt, tgtIdx) ) ) def test(): tracer = Tracer() tracer.setSrcsAndTgts( ['pSphere2', 'pCylinder1'], ['pSphere1', 'pCube1'] ) tracer.trace() #end
Python
from vectors import Vector, Matrix, Axis, AX_X, AX_Y, AX_Z from rigUtils import MATRIX_ROTATION_ORDER_CONVERSIONS_FROM, MATRIX_ROTATION_ORDER_CONVERSIONS_TO from maya.cmds import * from maya.OpenMaya import MGlobal from mayaDecorators import d_unifyUndo import maya import apiExtensions AXES = Axis.BASE_AXES #try to load the zooMirror.py plugin try: loadPlugin( 'zooMirror.py', quiet=True ) except: import zooToolbox zooToolbox.loadZooPlugin( 'zooMirror.py' ) def getLocalRotMatrix( obj ): ''' returns the local matrix for the given obj ''' localMatrix = Matrix( getAttr( '%s.matrix' % obj ), 4 ) localMatrix.set_position( (0, 0, 0) ) return localMatrix def getWorldRotMatrix( obj ): ''' returns the world matrix for the given obj ''' worldMatrix = Matrix( getAttr( '%s.worldMatrix' % obj ), 4 ) worldMatrix.set_position( (0, 0, 0) ) return worldMatrix def setWorldRotMatrix( obj, matrix ): ''' given a world matrix, will set the transforms of the object ''' parentInvMatrix = Matrix( getAttr( '%s.parentInverseMatrix' % obj ) ) localMatrix = matrix * parentInvMatrix setLocalRotMatrix( obj, localMatrix ) @d_unifyUndo def setLocalRotMatrix( obj, matrix ): ''' given a world matrix, will set the transforms of the object ''' roo = getAttr( '%s.rotateOrder' % obj ) rot = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ roo ]( matrix, True ) #try to set the rotation - check whether all the rotation channels are settable if getAttr( '%s.r' % obj, se=True ): setAttr( '%s.r' % obj, *rot ) def mirrorMatrix( matrix, axis=AX_X, orientAxis=AX_X ): ''' axis is the axis things are flipped across orientAxis is the axis that gets flipped when mirroring orientations ''' assert isinstance( matrix, Matrix ) mirroredMatrix = Matrix( matrix ) #make sure we've been given a Axis instances... don't bother testing, just do it, and make it absolute (non-negative - mirroring in -x is the same as mirroring in x) mirrorAxis = abs( Axis( axis ) ) axisA = abs( Axis( orientAxis ) ) #flip all axes axisB, axisC = axisA.otherAxes() mirroredMatrix[ axisB ][ mirrorAxis ] = -matrix[ axisB ][ mirrorAxis ] mirroredMatrix[ axisC ][ mirrorAxis ] = -matrix[ axisC ][ mirrorAxis ] #the above flipped all axes - but this results in a changing of coordinate system handed-ness, so flip one of the axes back nonMirrorAxisA, nonMirrorAxisB = mirrorAxis.otherAxes() mirroredMatrix[ axisA ][ nonMirrorAxisA ] = -mirroredMatrix[ axisA ][ nonMirrorAxisA ] mirroredMatrix[ axisA ][ nonMirrorAxisB ] = -mirroredMatrix[ axisA ][ nonMirrorAxisB ] #if the input matrix was a 4x4 then mirror translation if matrix.size == 4: mirroredMatrix[3][ mirrorAxis ] = -matrix[3][ mirrorAxis ] return mirroredMatrix def getKeyableAttrs( obj ): attrs = listAttr( obj, keyable=True ) if attrs is None: return [] for attrToRemove in ('translateX', 'translateY', 'translateZ', \ 'rotateX', 'rotateY', 'rotateZ'): try: attrs.remove( attrToRemove ) except ValueError: pass return attrs class ControlPair(object): ''' sets up a relationship between two controls so that they can mirror/swap/match one another's poses. NOTE: when you construct a ControlPair setup (using the Create classmethod) ''' #NOTE: these values are copied from the zooMirror script - they're copied because the plugin generally doesn't exist on the pythonpath so we can't rely on an import working.... FLIP_AXES = (), (AX_X, AX_Y), (AX_X, AX_Z), (AX_Y, AX_Z) @classmethod def GetPairNode( cls, obj ): ''' given a transform will return the pair node the control is part of ''' if obj is None: return None if objectType( obj, isAType='transform' ): cons = listConnections( '%s.message' % obj, s=False, type='controlPair' ) if not cons: return None return cons[0] if nodeType( obj ) == 'controlPair': return obj return None @classmethod @d_unifyUndo def Create( cls, controlA, controlB=None, axis=None ): ''' given two controls will setup the relationship between them NOTE: if controlB isn't given then it will only be able to mirror its current pose. This is usually desirable on "central" controls like spine, head and neck controls ''' #make sure we've been given transforms - mirroring doesn't make a whole lotta sense on non-transforms if not objectType( controlA, isAType='transform' ): return None if controlB: #if controlA is the same node as controlB then set controlB to None - this makes it more obvious the pair is singular #NOTE: cmpNodes compares the actual MObjects, not the node names - just in case we've been handed a full path and a partial path that are the same node... if apiExtensions.cmpNodes( controlA, controlB ): controlB = None elif not objectType( controlB, isAType='transform' ): return None #see if we have a pair node for the controls already pairNode = cls.GetPairNode( controlA ) if pairNode: #if no controlB has been given see whether the pairNode we've already got also has no controlB - if so, we're done if not controlB: new = cls( pairNode ) if not new.controlB: return new #if controlB HAS been given, check whether to see whether it has the same pairNode - if so, we're done if controlB: pairNodeB = cls.GetPairNode( controlB ) if pairNode == pairNodeB: return cls( pairNode ) #otherwise create a new one pairNode = createNode( 'controlPair' ) connectAttr( '%s.message' % controlA, '%s.controlA' % pairNode ) if controlB: connectAttr( '%s.message' % controlB, '%s.controlB' % pairNode ) #name the node nodeName = '%s_mirrorConfig' if controlB is None else '%s_%s_exchangeConfig' % (controlA, controlB) pairNode = rename( pairNode, nodeName ) #instantiate it and run the initial setup code over it new = cls( pairNode ) new.setup( axis ) return new def __init__( self, pairNodeOrControl ): self.node = pairNode = self.GetPairNode( pairNodeOrControl ) self.controlA = None self.controlB = None cons = listConnections( '%s.controlA' % pairNode, d=False ) if cons: self.controlA = cons[0] cons = listConnections( '%s.controlB' % pairNode, d=False ) if cons: self.controlB = cons[0] #make sure we have a control A if self.controlA is None: raise TypeError( "Could not find controlA - need to!" ) def __eq__( self, other ): if isinstance( other, ControlPair ): other return self.node == other.node def __ne__( self, other ): return not self.__eq__( other ) def __hash__( self ): return hash( self.node ) def getAxis( self ): return Axis( getAttr( '%s.axis' % self.node ) ) @d_unifyUndo def setAxis( self, axis ): setAttr( '%s.axis' % self.node, axis ) def getFlips( self ): axes = getAttr( '%s.flipAxes' % self.node ) return list( self.FLIP_AXES[ axes ] ) @d_unifyUndo def setFlips( self, flips ): if isinstance( flips, int ): setAttr( '%s.flipAxes' % self.node, flips ) def getWorldSpace( self ): return getAttr( '%s.worldSpace' % self.node ) @d_unifyUndo def setWorldSpace( self, state ): setAttr( '%s.worldSpace' % self.node, state ) def isSingular( self ): if self.controlB is None: return True #a pair is also singular if controlA is the same as controlB #NOTE: cmpNodes does a rigorous comparison so it will catch a fullpath and a partial path that point to the same node if apiExtensions.cmpNodes( self.controlA, self.controlB ): return True return False def neverDoT( self ): return getAttr( '%s.neverDoT' % self.node ) def neverDoR( self ): return getAttr( '%s.neverDoR' % self.node ) def neverDoOther( self ): return getAttr( '%s.neverDoOther' % self.node ) @d_unifyUndo def setup( self, axis=None ): ''' sets up the initial state of the pair node ''' if axis: axis = abs( Axis( axis ) ) setAttr( '%s.axis' % self.node, axis ) #if we have two controls try to auto determine the orientAxis and the flipAxes if self.controlA and self.controlB: worldMatrixA = getWorldRotMatrix( self.controlA ) worldMatrixB = getWorldRotMatrix( self.controlB ) #so restPoseB = restPoseA * offsetMatrix #restPoseAInv * restPoseB = restPoseAInv * restPoseA * offsetMatrix #restPoseAInv * restPoseB = I * offsetMatrix #thus offsetMatrix = restPoseAInv * restPoseB offsetMatrix = worldMatrixA.inverse() * worldMatrixB AXES = AX_X.asVector(), AX_Y.asVector(), AX_Z.asVector() flippedAxes = [] for n in range( 3 ): axisNVector = Vector( offsetMatrix[ n ][ :3 ] ) #if the axes are close to being opposite, then consider it a flipped axis... if axisNVector.dot( AXES[n] ) < -0.8: flippedAxes.append( n ) for n, flipAxes in enumerate( self.FLIP_AXES ): if tuple( flippedAxes ) == flipAxes: setAttr( '%s.flipAxes' % self.node, n ) break #this is a bit of a hack - and not always true, but generally singular controls built by skeleton builder will work with this value elif self.controlA: setAttr( '%s.flipAxes' % self.node, 1 ) self.setWorldSpace( False ) def mirrorMatrix( self, matrix ): matrix = mirrorMatrix( matrix, self.getAxis() ) for flipAxis in self.getFlips(): matrix.setRow( flipAxis, -Vector( matrix.getRow( flipAxis ) ) ) return matrix @d_unifyUndo def swap( self, t=True, r=True, other=True ): ''' mirrors the pose of each control, and swaps them ''' #if there is no controlB, then perform a mirror instead... if not self.controlB: self.mirror() return worldSpace = self.getWorldSpace() #do the other attributes first - the parent attribute for example will change the position so we need to set it before setting transforms if other: if not self.neverDoOther(): if not self.isSingular(): for attr in getKeyableAttrs( self.controlA ): attrPathA = '%s.%s' % (self.controlA, attr) attrPathB = '%s.%s' % (self.controlB, attr) if objExists( attrPathA ) and objExists( attrPathB ): attrValA = getAttr( attrPathA ) attrValB = getAttr( attrPathB ) #make sure the attributes are settable before trying setAttr if getAttr( attrPathA, se=True ): setAttr( attrPathA, attrValB ) if getAttr( attrPathB, se=True ): setAttr( attrPathB, attrValA ) #do rotation if r: if not self.neverDoR(): if worldSpace: getMatrix = getWorldRotMatrix setMatrix = setWorldRotMatrix else: getMatrix = getLocalRotMatrix setMatrix = setLocalRotMatrix worldMatrixA = getMatrix( self.controlA ) worldMatrixB = getMatrix( self.controlB ) newB = self.mirrorMatrix( worldMatrixA ) newA = self.mirrorMatrix( worldMatrixB ) setMatrix( self.controlA, newA ) setMatrix( self.controlB, newB ) #do position if t: if not self.neverDoT(): axis = self.getAxis() if worldSpace: newPosA = xform( self.controlB, q=True, ws=True, rp=True ) newPosB = xform( self.controlA, q=True, ws=True, rp=True ) else: newPosA = list( getAttr( '%s.t' % self.controlB )[0] ) newPosB = list( getAttr( '%s.t' % self.controlA )[0] ) newPosA[ axis ] = -newPosA[ axis ] newPosB[ axis ] = -newPosB[ axis ] if worldSpace: if getAttr( '%s.t' % self.controlA, se=True ): move( newPosA[0], newPosA[1], newPosA[2], self.controlA, ws=True, rpr=True ) if getAttr( '%s.t' % self.controlB, se=True ): move( newPosB[0], newPosB[1], newPosB[2], self.controlB, ws=True, rpr=True ) else: if getAttr( '%s.t' % self.controlA, se=True ): setAttr( '%s.t' % self.controlA, *newPosA ) if getAttr( '%s.t' % self.controlB, se=True ): setAttr( '%s.t' % self.controlB, *newPosB ) @d_unifyUndo def mirror( self, controlAIsSource=True, t=True, r=True, other=True ): ''' mirrors the pose of controlA (or controlB if controlAIsSource is False) and puts it on the "other" control NOTE: if controlAIsSource is True, then the pose of controlA is mirrored and put on to controlB, otherwise the reverse is done ''' if self.isSingular(): control = otherControl = self.controlA else: if controlAIsSource: control = self.controlB otherControl = self.controlA else: control = self.controlA otherControl = self.controlB #do the other attributes first - the parent attribute for example will change the position so we need to set it before setting transforms if other: if not self.neverDoOther(): if not self.isSingular(): for attr in getKeyableAttrs( otherControl ): attrPath = '%s.%s' % (control, attr) otherAttrPath = '%s.%s' % (otherControl, attr) if objExists( attrPath ): setAttr( attrPath, getAttr( otherAttrPath ) ) worldSpace = self.getWorldSpace() #do rotation if r: if not self.neverDoR(): if worldSpace: getMatrix = getWorldRotMatrix setMatrix = setWorldRotMatrix else: getMatrix = getLocalRotMatrix setMatrix = setLocalRotMatrix matrix = getMatrix( otherControl ) newMatrix = self.mirrorMatrix( matrix ) setMatrix( control, newMatrix ) #do position if t: if not self.neverDoT(): if worldSpace: pos = xform( otherControl, q=True, ws=True, rp=True ) pos[ self.getAxis() ] = -pos[ self.getAxis() ] move( pos[0], pos[1], pos[2], control, ws=True, rpr=True ) else: pos = list( getAttr( '%s.t' % otherControl )[0] ) pos[ self.getAxis() ] = -pos[ self.getAxis() ] setAttr( '%s.t' % control, *pos ) @d_unifyUndo def match( self, controlAIsSource=True, t=True, r=True, other=True ): ''' pushes the pose of controlA (or controlB if controlAIsSource is False) to the "other" control NOTE: if controlAIsSource is True, then the pose of controlA is mirrored and copied and put on to controlB, otherwise the reverse is done ''' #if this is a singular pair, bail - there's nothing to do if self.isSingular(): return #NOTE: #restPoseB = restPoseA * offsetMatrix #and similarly: #so restPoseB * offsetMatrixInv = restPoseA if controlAIsSource: worldMatrix = getWorldRotMatrix( self.controlA ) control = self.controlB else: worldMatrix = getWorldRotMatrix( self.controlB ) control = self.controlA newControlMatrix = self.mirrorMatrix( worldMatrix ) setWorldRotMatrix( control, newControlMatrix, t=False ) setWorldRotMatrix( control, worldMatrix, r=False ) def getPairNodesFromObjs( objs ): ''' given a list of objects, will return a minimal list of pair nodes ''' pairs = set() for obj in objs: pairNode = ControlPair.GetPairNode( obj ) if pairNode: pairs.add( pairNode ) return list( pairs ) def getPairsFromObjs( objs ): return [ ControlPair( pair ) for pair in getPairNodesFromObjs( objs ) ] def getPairsFromSelection(): return getPairsFromObjs( ls( sl=True ) ) def iterPairAndObj( objs ): ''' yields a 2-tuple containing the pair node and the initializing object ''' pairNodesVisited = set() for obj in objs: pairNode = ControlPair.GetPairNode( obj ) if pairNode: if pairNode in pairNodesVisited: continue pair = ControlPair( pairNode ) yield pair, obj pairNodesVisited.add( pairNode ) @d_unifyUndo def setupMirroringFromNames( mandatoryTokens=('control', 'ctrl') ): ''' sets up control pairs for all parity based controls in the scene as determined by their names. ''' import names #stick the tokens in a set and ensure they're lower-case mandatoryTokens = set( [ tok.lower() for tok in mandatoryTokens ] ) visitedTransforms = set() for t in ls( type='transform' ): if t in visitedTransforms: continue visitedTransforms.add( t ) tName = names.Name( t ) if tName.get_parity() is names.Parity.NONE: continue containsMandatoryToken = False for tok in tName.split(): if tok.lower() in mandatoryTokens: containsMandatoryToken = True break if not containsMandatoryToken: continue otherT = names.Name( tName ).swap_parity() #swap_parity changes the parity of the instance - Name objects are mutable... ugh! should re-write it if otherT: if objExists( str( otherT ) ): visitedTransforms.add( str( otherT ) ) #sort the controls into left and right - we want the left to be controlA and right to be controlB controlPairs = [(tName.get_parity(), tName), (otherT.get_parity(), otherT)] controlPairs.sort() leftT, rightT = str( controlPairs[0][1] ), str( controlPairs[1][1] ) ControlPair.Create( leftT, rightT ) print 'creating a control pair on %s -> %s' % (leftT, rightT) #end
Python
from maya.cmds import * from baseMelUI import * from filesystem import removeDupes from rigUtils import MATRIX_ROTATION_ORDER_CONVERSIONS_FROM, MATRIX_ROTATION_ORDER_CONVERSIONS_TO, \ MAYA_ROTATION_ORDERS, ROO_XYZ, ROO_YZX, ROO_ZXY, ROO_XZY, ROO_YXZ, ROO_ZYX, ROT_ORDER_STRS from mayaDecorators import d_disableViews, d_noAutoKey, d_unifyUndo, d_restoreTime from animUtils import KeyServer from common import printWarningStr XYZ, YZX, ZXY, XZY, YXZ, ZYX = ROT_ORDER_STRS @d_unifyUndo @d_disableViews @d_noAutoKey @d_restoreTime def changeRo( objs=None, ro=XYZ ): if ro not in ROT_ORDER_STRS: raise TypeError( "need to specify a valid rotation order - one of: %s" % ' '.join( ROT_ORDER_STRS ) ) if objs is None: objs = ls( sl=True, type='transform' ) roIdx = list( ROT_ORDER_STRS ).index( ro ) #filter out objects that don't have all 3 rotation axes settable and while we're at it store the rotation orders for each object #in a dict - since accessing a python dict is WAY faster than doing a getAttr for each frame in the loop below RO_DICT = {} objsWithAllChannelsSettable = [] for obj in objs: if not getAttr( '%s.r' % obj, se=True ): printWarningStr( "Not all rotation axes on the object %s are settable - skipping!" % obj ) continue objRo = getAttr( '%s.ro' % obj ) #if the rotation order of this object is the same as what we're changing it to - skip the object entirely if objRo == roIdx: printWarningStr( "The object %s already has the rotation order %s - skipping!" % (obj, ro) ) continue RO_DICT[ obj ] = objRo objsWithAllChannelsSettable.append( obj ) #early out if we have no objects to work on objs = objsWithAllChannelsSettable if not objs: printWarningStr( "No objects to act on - exiting" ) return #cache the conversion method convertToMethod = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ roIdx ] #construct a key server object to march over keys and objects keyServer = KeyServer( objs, True ) for time in keyServer: for obj in keyServer.getNodesAtTime(): setKeyframe( obj, at='r' ) #now that we're secured the rotation poses with keys on all axes, fix up each rotation value to use the desired rotation order for time in keyServer: for obj in keyServer.getNodesAtTime(): currentRoIdx = RO_DICT[ obj ] rot = getAttr( '%s.r' % obj )[0] rotMatrix = MATRIX_ROTATION_ORDER_CONVERSIONS_FROM[ currentRoIdx ]( degrees=True, *rot ) newRot = convertToMethod( rotMatrix, True ) setAttr( '%s.r' % obj, *newRot ) setKeyframe( obj, at='r' ) #now change the rotation order to what it should be for obj in objs: setAttr( '%s.ro' % obj, roIdx ) class ChangeRoLayout(MelColumnLayout): def __init__( self, parent ): hLayout = MelHLayout( self ) lbl = MelLabel( hLayout, l='New Rotate Order', h=25 ) self.UI_rotateOrders = UI_rotateOrders = MelOptionMenu( hLayout ) for roStr in ROT_ORDER_STRS: UI_rotateOrders.append( roStr ) hLayout.layout() hLayout( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) ) self.UI_go = MelButton( self, l='Change Rotate Order', c=self.on_go ) #setup selection change callbacks and trigger it for the initial selection self.on_selectionChange() self.setSelectionChangeCB( self.on_selectionChange ) ### EVENT HANDLERS ### def on_selectionChange( self, *a ): for obj in ls( sl=True, type='transform' ) or []: if objExists( '%s.ro' % obj ): ro = getAttr( '%s.ro' % obj ) self.UI_rotateOrders.selectByIdx( ro ) self.UI_go.setEnabled( True ) return self.UI_go.setEnabled( False ) def on_go( self, *a ): roStr = self.UI_rotateOrders.getValue() changeRo( ro=roStr ) class ChangeRoWindow(BaseMelWindow): WINDOW_NAME = 'ChangeRooTool' WINDOW_TITLE = 'Change Rotate Order For Animated Nodes' DEFAULT_SIZE = 375, 90 DEFAULT_MENU = None def __init__( self ): self.UI_editor = ChangeRoLayout( self ) self.show() #end
Python
from filesystem import P4File, P4Change, removeDupes from baseMelUI import * from devTest import TEST_CASES, runTestCases class DevTestLayout(MelVSingleStretchLayout): def __init__( self, parent, *a, **kw ): MelVSingleStretchLayout.__init__( self, parent, *a, **kw ) self.UI_tests = UI_tests = MelObjectScrollList( self, ams=True ) self.UI_run = UI_run = MelButton( self, l='Run Tests', c=self.on_test ) for testCls in TEST_CASES: UI_tests.append( testCls ) self.setStretchWidget( UI_tests ) self.layout() ### EVENT HANDLERS ### def on_test( self, *a ): ''' run the selected tests - the modules are reloaded before running the tests so its easy to iterate when writing the tests ''' runTestCases( self.UI_tests.getSelectedItems() ) class DevTestWindow(BaseMelWindow): WINDOW_NAME = 'devTestWindow' WINDOW_TITLE = 'Maya Devtest Runner' DEFAULT_MENU = None DEFAULT_SIZE = 300, 300 FORCE_DEFAULT_SIZE = True HELP_MENU = 'devTest', 'hamish@macaronikazoo.com', None def __init__( self ): BaseMelWindow.__init__( self ) DevTestLayout( self ) self.show() #end
Python
''' this module is simply a miscellaneous module for rigging support code - most of it is maya specific convenience code for determining things like aimAxes, aimVectors, rotational offsets for controls etc... ''' from maya.cmds import * from vectors import * import apiExtensions import maya.cmds as cmd import meshUtils import api import vectors import random from maya import OpenMaya SPACES = SPACE_WORLD, SPACE_LOCAL, SPACE_OBJECT = range(3) ENGINE_FWD = MAYA_SIDE = MAYA_X = Vector((1, 0, 0)) ENGINE_UP = MAYA_FWD = MAYA_Z = Vector((0, 0, 1)) ENGINE_SIDE = MAYA_UP = MAYA_Y = Vector((0, 1, 0)) #pull in some globals... MPoint = OpenMaya.MPoint MVector = OpenMaya.MVector MMatrix = OpenMaya.MMatrix MTransformationMatrix = OpenMaya.MTransformationMatrix MBoundingBox = OpenMaya.MBoundingBox MSpace = OpenMaya.MSpace kWorld = MSpace.kWorld kTransform = MSpace.kTransform kObject = MSpace.kObject Axis = vectors.Axis AXES = Axis.BASE_AXES #these are the enum values for the rotation orders for transform nodes in maya MAYA_ROTATION_ORDERS = ROO_XYZ, ROO_YZX, ROO_ZXY, ROO_XZY, ROO_YXZ, ROO_ZYX = range( 6 ) MATRIX_ROTATION_ORDER_CONVERSIONS_FROM = Matrix.FromEulerXYZ, Matrix.FromEulerYZX, Matrix.FromEulerZXY, Matrix.FromEulerXZY, Matrix.FromEulerYXZ, Matrix.FromEulerZYX MATRIX_ROTATION_ORDER_CONVERSIONS_TO = Matrix.ToEulerXYZ, Matrix.ToEulerYZX, Matrix.ToEulerZXY, Matrix.ToEulerXZY, Matrix.ToEulerYXZ, Matrix.ToEulerZYX ROT_ORDER_STRS = 'xyz', 'yzx', 'zxy', 'xzy', 'yxz', 'zyx' def alignFast( objToAlign, dest ): if getAttr( '%s.t' % objToAlign, se=True ): pos = xform( dest, q=True, ws=True, rp=True ) move( pos[0], pos[1], pos[2], objToAlign, a=True, ws=True, rpr=True ) if getAttr( '%s.r' % objToAlign, se=True ): #rotation is a bit special because when querying the rotation we get back xyz world rotations - so we need to change the rotation order to xyz, set the global rotation then modify the rotation order while preserving orientation initialRo = getAttr( '%s.ro' % objToAlign ) setAttr( '%s.ro' % objToAlign, 0 ) rot = xform( dest, q=True, ws=True, ro=True ) rotate( rot[0], rot[1], rot[2], objToAlign, a=True, ws=True ) xform( objToAlign, p=True, roo=ROT_ORDER_STRS[ initialRo ] ) def cleanDelete( node ): ''' will disconnect all connections made to and from the given node before deleting it ''' if not objExists( node ): return connections = listConnections( node, connections=True, plugs=True ) connectionsIter = iter( connections ) for srcConnection in connectionsIter: tgtConnection = connectionsIter.next() #we need to test if the connection is valid because a previous disconnection may have affected this one if isConnected( srcConnection, tgtConnection ): try: #this may fail if the dest attr is locked - in which case just skip and hope deleting the node doesn't screw up the attribute value... disconnectAttr( srcConnection, tgtConnection ) except RuntimeError: pass cmd.delete( node ) def getObjectBasisVectors( obj ): ''' returns 3 world space orthonormal basis vectors that represent the orientation of the given object ''' worldMatrix = Matrix( cmd.getAttr( '%s.worldMatrix' % obj ), size=4 ) return Vector( worldMatrix[0][:3] ), Vector( worldMatrix[1][:3] ), Vector( worldMatrix[2][:3] ) def getLocalBasisVectors( obj ): ''' returns 3 world space orthonormal basis vectors that represent the local coordinate system of the given object ''' localMatrix = Matrix( cmd.getAttr( '%s.matrix' % obj ), size=4 ) return Vector( localMatrix[0][:3] ), Vector( localMatrix[1][:3] ), Vector( localMatrix[2][:3] ) def getPlaneNormalForObjects( objA, objB, objC, defaultVector=MAYA_UP ): posA = Vector( xform( objA, q=True, ws=True, rp=True ) ) posB = Vector( xform( objB, q=True, ws=True, rp=True ) ) posC = Vector( xform( objC, q=True, ws=True, rp=True ) ) vecA, vecB = posA - posB, posA - posC normal = vecA.cross( vecB ) #if the normal is too small, just return the given default axis if normal.magnitude() < 1e-2: normal = defaultVector return normal.normalize() def findPolePosition( end, mid=None, start=None, distanceMultiplier=1 ): if not objExists( end ): return Vector.Zero() try: if mid is None: mid = listRelatives( end, p=True, pa=True )[0] if start is None: start = listRelatives( mid, p=True, pa=True )[0] except TypeError: return Vector.Zero() joint0, joint1, joint2 = start, mid, end pos0 = Vector( xform( joint0, q=True, ws=True, rp=True ) ) pos1 = Vector( xform( joint1, q=True, ws=True, rp=True ) ) pos2 = Vector( xform( joint2, q=True, ws=True, rp=True ) ) #this is the rough length of the presumably "limb" we're finding the pole vector position for lengthFactor = (pos1-pos0).length() + (pos2-pos1).length() #get the vectors from 0 to 1, and 0 to 2 vec0_1 = pos1 - pos0 vec0_2 = pos2 - pos0 #project vec0_1 on to vec0_2 projA_B = vec0_2.normalize() * ( (vec0_1 * vec0_2) / vec0_2.length() ) #get the vector from the projected vector above, to the mid pos sub = vec0_1 - projA_B #if the magnitude is really small just return the position of the mid object if sub.length() < 1e-4: return pos1 sub = sub.normalize() polePos = pos0 + projA_B + (sub * lengthFactor) return polePos def largestT( obj ): ''' returns the index of the translation axis with the highest absolute value ''' pos = getAttr( '%s.t' % obj )[0] idx = indexOfLargest( pos ) if pos[ idx ] < 0: idx += 3 return idx def indexOfLargest( iterable ): ''' returns the index of the largest absolute valued component in an iterable ''' iterable = [(x, n) for n, x in enumerate( map(abs, iterable) )] iterable.sort() return Axis( iterable[-1][1] ) def betweenVector( obj1, obj2 ): ''' returns the vector between two objects ''' posA = Vector( xform( obj1, q=True, ws=True, rp=True ) ) posB = Vector( xform( obj2, q=True, ws=True, rp=True ) ) return posB - posA def getAimVector( obj ): children = cmd.listRelatives( obj, path=True, typ='transform' ) or [] if len( children ) == 1: return betweenVector(obj, children[0]) else: axisIdx = largestT( obj ) axisVector = Axis( axisIdx ).asVector() #now just return the axis vector in world space mat = Matrix( cmd.getAttr( '%s.worldMatrix' % obj ) ) return multVectorMatrix( axisVector, mat ) def getObjectAxisInDirection( obj, compareVector, defaultAxis=Axis(0) ): ''' returns the axis (an Axis instance) representing the closest object axis to the given vector the defaultAxis is returned if the compareVector is zero or too small to provide meaningful directionality ''' if not isinstance( compareVector, Vector ): compareVector = Vector( compareVector ) xPrime, yPrime, zPrime = getObjectBasisVectors( obj ) try: dots = compareVector.dot( xPrime, True ), compareVector.dot( yPrime, True ), compareVector.dot( zPrime, True ) except ZeroDivisionError: return defaultAxis idx = indexOfLargest( dots ) if dots[ idx ] < 0: idx += 3 return Axis( idx ) def getLocalAxisInDirection( obj, compareVector ): xPrime, yPrime, zPrime = getLocalBasisVectors( obj ) dots = compareVector.dot( xPrime, True ), compareVector.dot( yPrime, True ), compareVector.dot( zPrime, True ) idx = indexOfLargest( dots ) if dots[ idx ] < 0: idx += 3 return Axis( idx ) def getAnkleToWorldRotation( obj, fwdAxisName='z', performRotate=False ): ''' ankles are often not world aligned and cannot be world aligned on all axes, as the ankle needs to aim toward toe joint. for the purposes of rigging however, we usually want the foot facing foward (or along one of the primary axes ''' fwd = Vector.Axis( fwdAxisName ) fwdAxis = getObjectAxisInDirection( obj, fwd ) basisVectors = getObjectBasisVectors( obj ) fwdVector = basisVectors[ abs( fwdAxis ) ] #determine the directionality of the rotation direction = -1 if fwdAxis.isNegative() else 1 #flatten aim vector into the x-z plane fwdVector[ AX_Y ] = 0 fwdVector = fwdVector.normalize() * direction #now determine the rotation between the flattened aim vector, and the fwd axis angle = fwdVector.dot( fwd ) angle = Angle( math.acos( angle ), radian=True ).degrees * -direction #do the rotation... if performRotate: cmd.rotate(0, angle, 0, obj, r=True, ws=True) return (0, angle, 0) def getWristToWorldRotation( wrist, performRotate=False ): ''' returns the world space rotation values to align the given object to world axes. If performRotate is True the object will be rotated to this alignment. The rotation values are returned as euler rotation values in degrees ''' worldMatrix, worldScale = Matrix( getAttr( '%s.worldMatrix' % wrist ) ).decompose() bases = x, y, z = map( Vector, worldMatrix.crop( 3 ) ) newBases = [] allAxes = range( 3 ) for basis in bases: largestAxisValue = -2 #values will never be smaller than this, so the code below will always get run largestAxis = 0 #find which world axis this basis vector best approximates - we want to world align the basis vectors for n in range( 3 ): absAxisValue = abs( basis[n] ) if absAxisValue > largestAxisValue: largestAxisValue = absAxisValue largestAxis = n+3 if basis[n] < 0 else n #if the dot is negative, shift the axis index by 3 (which makes it negative) #track the largestAxisValue too - we want to use it as a measure of closeness newBases.append( Axis( largestAxis ).asVector() ) newBases = map( list, newBases ) matrixValues = newBases[0] + newBases[1] + newBases[2] worldRotMatrix = Matrix( matrixValues, 3 ) rots = worldRotMatrix.ToEulerXYZ( True ) if performRotate: rotate( rots[0], rots[1], rots[2], wrist, a=True, ws=True ) return tuple( rots ) def isVisible( dag ): ''' returns whether a dag item is visible or not - it walks up the hierarchy and checks both parent visibility as well as layer visibility ''' parent = dag while True: if not getAttr( '%s.v' % parent ): return False #check layer membership layers = listConnections( parent, t='displayLayer' ) if layers is not None: for l in layers: if not getAttr( '%s.v' % l ): return False try: parent = listRelatives( parent, p=True, pa=True )[0] except TypeError: break return True def areSameObj( objA, objB ): ''' given two objects, returns whether they're the same object or not - object path names make this tricker than it seems ''' try: return cmd.ls( objA ) == cmd.ls( objB ) except TypeError: return False def getBounds( objs ): minX, minY, minZ = [], [], [] maxX, maxY, maxZ = [], [], [] for obj in objs: tempMN = cmd.getAttr( '%s.bbmn' % obj )[ 0 ] tempMX = cmd.getAttr( '%s.bbmx' % obj )[ 0 ] minX.append( tempMN[ 0 ] ) minY.append( tempMN[ 1 ] ) minZ.append( tempMN[ 2 ] ) maxX.append( tempMX[ 0 ] ) maxY.append( tempMX[ 1 ] ) maxZ.append( tempMX[ 2 ] ) minX.sort() minY.sort() minZ.sort() maxX.sort() maxY.sort() maxZ.sort() return minX[ 0 ], minY[ 0 ], minZ[ 0 ], maxX[ -1 ], maxY[ -1 ], maxZ[ -1 ] def getTranslationExtents( objs ): ts = [ xform( i, q=True, ws=True, rp=True ) for i in objs ] xs, ys, zs = [ t[0] for t in ts ], [ t[1] for t in ts ], [ t[2] for t in ts ] mnx, mxx = min( xs ), max( xs ) mny, mxy = min( ys ), max( ys ) mnz, mxz = min( zs ), max( zs ) return mnx, mny, mnz, mxx, mxy, mxz def getObjsScale( objs ): mnX, mnY, mnZ, mxX, mxY, mxZ = getBounds( objs ) x = abs( mxX - mnX ) y = abs( mxY - mnY ) z = abs( mxZ - mnZ ) return (x + y + z) / 3.0 * 0.75 #this is kinda arbitrary def getJointBounds( joints, threshold=0.65, space=SPACE_OBJECT ): ''' if the joints are skinned, then the influenced verts that have weights greater than the given influenced are transformed into the space specified (if SPACE_OBJECT is used, the space of the first joint is used), and the bounds of the verts in this space are returned as a 2-tuple of bbMin, bbMax ''' global MVector, MTransformationMatrix, Vector if not isinstance( joints, (list, tuple) ): joints = [ joints ] theJoint = joints[ 0 ] verts = [] for j in joints: verts += meshUtils.jointVertsForMaya( j, threshold ) jointDag = api.getMDagPath( theJoint ) if space == SPACE_OBJECT: jointMatrix = jointDag.inclusiveMatrix() elif space == SPACE_LOCAL: jointMatrix = jointDag.exclusiveMatrix() elif space == SPACE_WORLD: jointMatrix = OpenMaya.MMatrix() else: raise TypeError( "Invalid space specified" ) vJointPos = MTransformationMatrix( jointMatrix ).rotatePivot( kWorld ) + MTransformationMatrix( jointMatrix ).getTranslation( kWorld ) vJointPos = Vector( [vJointPos.x, vJointPos.y, vJointPos.z] ) vJointBasisX = MVector(-1,0,0) * jointMatrix vJointBasisY = MVector(0,-1,0) * jointMatrix vJointBasisZ = MVector(0,0,-1) * jointMatrix bbox = MBoundingBox() for vert in verts: #get the position relative to the joint in question vPos = Vector( xform( vert, query=True, ws=True, t=True ) ) vPos = vJointPos - vPos #now transform the joint relative position into the coordinate space of that joint #we do this so we can get the width, height and depth of the bounds of the verts #in the space oriented along the joint vPosInJointSpace = Vector( vPos ) vPosInJointSpace = vPosInJointSpace.change_space( vJointBasisX, vJointBasisY, vJointBasisZ ) bbox.expand( MPoint( *vPosInJointSpace ) ) bbMin, bbMax = bbox.min(), bbox.max() bbMin = Vector( [bbMin.x, bbMin.y, bbMin.z] ) bbMax = Vector( [bbMax.x, bbMax.y, bbMax.z] ) return bbMin, bbMax def getJointSizeAndCentre( joints, threshold=0.65, space=SPACE_OBJECT, ignoreSkinning=False ): if ignoreSkinning: vec = Vector.Zero() else: minB, maxB = getJointBounds( joints, threshold, space ) vec = maxB - minB #if the bounding box is a point then lets see if we can derive a useful size for the joint based on existing children if not vec: #make sure we're dealing with a list of joints... if not isinstance( joints, (list, tuple) ): joints = [ joints ] children = listRelatives( joints, pa=True, typ='transform' ) or [] #if there are no children then we fall back on averaging the "radius" attribute for all given joints... if not children: radSum = sum( getAttr( '%s.radius' % j ) for j in joints ) s = float( radSum ) / len( joints ) * 5 #5 is an arbitrary number - tune it as required... return Vector( (s, s, s) ), Vector( (0, 0, 0) ) theJoint = joints[ 0 ] theJointPos = Vector( xform( theJoint, q=True, ws=True, rp=True ) ) #determine the basis vectors for <theJoint>. we want to transform the joint's size into the appropriate space if space == SPACE_OBJECT: theJointBasisVectors = getObjectBasisVectors( theJoint ) elif space == SPACE_LOCAL: theJointBasisVectors = getLocalBasisVectors( theJoint ) elif space == SPACE_WORLD: theJointBasisVectors = Vector( (1,0,0) ), Vector( (0,1,0) ), Vector( (0,0,1) ) else: raise TypeError( "Invalid space specified" ) bbox = MBoundingBox() bbox.expand( MPoint( 0, 0, 0 ) ) #make sure zero is included in the bounding box - zero is the position of <theJoint> for j in joints[ 1: ] + children: pos = Vector( xform( j, q=True, ws=True, rp=True ) ) - theJointPos pos = pos.change_space( *theJointBasisVectors ) bbox.expand( MPoint( *pos ) ) minB, maxB = bbox.min(), bbox.max() minB = Vector( (minB.x, minB.y, minB.z) ) maxB = Vector( (maxB.x, maxB.y, maxB.z) ) vec = maxB - minB centre = (minB + maxB) / 2.0 return Vector( map( abs, vec ) ), centre getJointSizeAndCenter = getJointSizeAndCentre #for spelling n00bs def getJointSize( joints, threshold=0.65, space=SPACE_OBJECT ): return getJointSizeAndCentre( joints, threshold, space )[ 0 ] def ikSpringSolver( start, end, **kw ): ''' creates an ik spring solver - this is wrapped simply because its not default maya functionality, and there is potential setup work that needs to be done to ensure its possible to create an ik chain using the spring solver ''' api.mel.ikSpringSolver() kw[ 'solver' ] = 'ikSpringSolver' handle, effector = cmd.ikHandle( '%s.rotatePivot' % start, '%s.rotatePivot' % end, **kw ) #now we want to ensure a sensible pole vector - so set that up jointChain = getChain( start, end ) poleVectorAttrVal = xform( jointChain[1], q=True, ws=True, rp=True ) restPoleVector = betweenVector( jointChain[0], jointChain[1] ) setAttr( '%s.springRestPoleVector' % handle, *restPoleVector ) setAttr( '%s.poleVector' % handle, *poleVectorAttrVal ) return handle, effector def resetSkinCluster( skinCluster ): ''' splats the current pose of the skeleton into the skinCluster - ie whatever the current pose is becomes the bindpose ''' skinInputMatrices = listConnections( '%s.matrix' % skinCluster, plugs=True, connections=True, destination=False ) #this happens if the skinCluster is bogus - its possible for deformers to become orphaned in the scene if skinInputMatrices is None: return #get a list of dag pose nodes connected to the skin cluster dagPoseNodes = listConnections( skinCluster, d=False, type='dagPose' ) or [] iterInputMatrices = iter( skinInputMatrices ) for dest in iterInputMatrices: src = iterInputMatrices.next() srcNode = src.split( '.' )[ 0 ] idx = dest[ dest.rfind( '[' )+1:-1 ] matrixAsStr = ' '.join( map( str, cmd.getAttr( '%s.worldInverseMatrix' % srcNode ) ) ) melStr = 'setAttr -type "matrix" %s.bindPreMatrix[%s] %s' % (skinCluster, idx, matrixAsStr) api.mel.eval( melStr ) #reset the stored pose in any dagposes that are conn for dPose in dagPoseNodes: dagPose( srcNode, reset=True, n=dPose ) def enableSkinClusters(): for c in ls( type='skinCluster' ): resetSkinCluster( c ) setAttr( '%s.nodeState' % c, 0 ) def disableSkinClusters(): for c in ls( type='skinCluster' ): setAttr( '%s.nodeState' % c, 1 ) def getSkinClusterEnableState(): for c in ls( type='skinCluster' ): if getAttr( '%s.nodeState' % c ) == 1: return False return True def buildMeasure( startNode, endNode ): measure = createNode( 'distanceDimShape', n='%s_to_%s_measureShape#' % (startNode, endNode) ) measureT = listRelatives( measure, p=True, pa=True )[ 0 ] locA = spaceLocator()[ 0 ] locB = spaceLocator()[ 0 ] cmd.parent( locA, startNode, r=True ) cmd.parent( locB, endNode, r=True ) locAShape = listRelatives( locA, s=True, pa=True )[ 0 ] locBShape = listRelatives( locB, s=True, pa=True )[ 0 ] connectAttr( '%s.worldPosition[ 0 ]' % locAShape, '%s.startPoint' % measure, f=True ) connectAttr( '%s.worldPosition[ 0 ]' % locBShape, '%s.endPoint' % measure, f=True ) return measureT, measure, locA, locB def buildAnnotation( obj, text='' ): ''' like the distance command above, this is a simple wrapper for creating annotation nodes, and having the nodes you actually want returned to you. whoever wrote these commands should be shot. with a large gun returns a 3 tuple containing the start transform, end transform, and annotation shape node ''' obj = str( obj ) #cast as string just in case we've been passed a PyNode instance rand = random.randint end = spaceLocator()[ 0 ] shape = annotate( end, p=(rand(0, 1000000), rand(1000000, 2000000), 2364), tx=text ) start = listRelatives( shape, p=True, pa=True )[ 0 ] endShape = listRelatives( end, s=True, pa=True )[ 0 ] delete( parentConstraint( obj, end ) ) for ax in Axis.AXES[ :3 ]: setAttr( '%s.t%s' % (start, ax), 0 ) setAttr( '%s.v' % endShape, 0 ) setAttr( '%s.v' % endShape, lock=True ) cmd.parent( end, obj ) return start, end, shape def getChain( startNode, endNode ): ''' returns a list of all the joints from the given start to the end inclusive ''' chainNodes = [ endNode ] for p in api.iterParents( endNode ): if not p: raise ValueError( "Chain terminated before reaching the end node!" ) chainNodes.append( p ) if apiExtensions.cmpNodes( p, startNode ): #cmpNodes is more reliable than just string comparing - cmpNodes casts to MObjects and compares object handles break chainNodes.reverse() return chainNodes def chainLength( startNode, endNode ): ''' measures the length of the chain were it to be straightened out ''' length = 0 curNode = endNode for p in api.iterParents( endNode ): curPos = Vector( xform( curNode, q=True, ws=True, rp=True ) ) parPos = Vector( xform( p, q=True, ws=True, rp=True ) ) dif = curPos - parPos length += dif.get_magnitude() if apiExtensions.cmpNodes( p, startNode ): #cmpNodes is more reliable than just string comparing - cmpNodes casts to MObjects and compares object handles break curNode = p return length def switchToFK( control, ikHandle=None, onCmd=None, offCmd=None ): ''' this proc will align the bones controlled by an ik chain to the fk chain ikHandle this flag specifies the name of the ikHandle to work on onCmd this flag tells the script what command to run to turn the ik handle on - it is often left blank because its assumed we're already in ik mode offCmd this flag holds the command to turn the ik handle off, and switch to fk mode NOTE: if the offCmd isn't specified, it defaults to: lambda c, ik: setAttr( '%s.ikBlend' % c, 0 ) both on and off callbacks take 2 args - the control and the ikHandle example: switchToFK( ikHandle1, onCmd=lambda ctrl, ik: setAttr( '%s.ikBlend' % ik, 1 ), offCmd=lambda c, ik: setAttr( '%s.ikBlend' % ik, 0 ) ) ''' if ikHandle is None: ikHandle = control if onCmd is None: onCmd = lambda c, ik: setAttr( '%s.ikBlend' % c, 0 ) if callable( onCmd ): onCmd( control, ikHandle ) joints = cmd.ikHandle( ikHandle, q=True, jl=True ) effector = cmd.ikHandle( ikHandle, q=True, ee=True ) effectorCtrl = listConnections( '%s.tx' % effector, d=False )[ 0 ] jRotations = [ getAttr( '%s.r' % j ) for j in joints ] if callable( offCmd ): offCmd( control, ikHandle ) for j, rot in zip( joints, jRotations ): if getAttr( '%s.rx' % j, settable=True ): setAttr( '%s.rx' % j, rot[ 0 ] ) if getAttr( '%s.ry' % j, settable=True ): setAttr( '%s.ry' % j, rot[ 1 ] ) if getAttr( '%s.rz' % j, settable=True ): setAttr( '%s.rz' % j, rot[ 2 ] ) def switchToIK( control, ikHandle=None, poleControl=None, onCmd=None, offCmd=None ): ''' this proc will align the IK controller to its fk chain flags used: -control this is the actual control being used to move the ikHandle - it is assumed to be the same object as the ikHandle, but if its different (ie if the ikHandle is constrained to a controller) use this flag -pole tells the script the name of the pole controller - if there is no pole vector control, leave this flag out -ikHandle this flag specifies the name of the ikHandle to work on -onCmd this flag tells the script what command to run to turn the ik handle on - it is often left blank because its assumed we're already in ik mode -offCmd this flag holds the command to turn the ik handle off, and switch to fk mode NOTE: if the offCmd isn't specified, it defaults to: if( `getAttr -se ^.ikb` ) setAttr ^.ikb 1; symbols to use in cmd strings: ^ refers to the ikHandle # refers to the control object example: zooAlignIK "-control somObj -ikHandle ikHandle1 -offCmd setAttr #.fkMode 0"; ''' if ikHandle is None: ikHandle = control if callable( onCmd ): onCmd( control, ikHandle, poleControl ) joints = cmd.ikHandle( ikHandle, q=True, jl=True ) effector = cmd.ikHandle( ikHandle, q=True, ee=True ) effectorCtrl = listConnections( '%s.tx' % effector, d=False )[ 0 ] mel.zooAlign( "-src %s -tgt %s" % (effectorCtrl, control) ) if poleControl is not None and objExists( poleControl ): pos = mel.zooFindPolePosition( "-start %s -mid %s -end %s" % (joints[ 0 ], joints[ 1 ], effectorCtrl) ) move( pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True ) if callable( offCmd ): offCmd( control, ikHandle, poleControl ) def replaceConstraintTarget( constraint, newTarget, targetIndex=0 ): ''' replaces the target at "targetIndex" with the new target ''' newTarget = apiExtensions.asMObject( str( newTarget ) ) for attr in attributeQuery( 'target', node=constraint, listChildren=True ): for connection in listConnections( '%s.target[%s].%s' % (constraint, targetIndex, attr), p=True, type='transform', d=False ) or []: toks = connection.split( '.' ) node = toks[ 0 ] if not apiExtensions.cmpNodes( node, newTarget ): toks[ 0 ] = str( newTarget ) connectAttr( '.'.join( toks ), '%s.target[%s].%s' % (constraint, targetIndex, attr), f=True ) def replaceGivenConstraintTarget( constraint, targetToReplace, newTarget ): ''' replaces targetToReplace transform on the given constraint with the newTarget transform ''' targetToReplace = apiExtensions.asMObject( targetToReplace ) newTarget = apiExtensions.asMObject( newTarget ) #nothing to do if the nodes are the same... if apiExtensions.cmpNodes( targetToReplace, newTarget ): return usedTargetIndices = getAttr( '%s.target' % constraint, multiIndices=True ) for idx in usedTargetIndices: for attr in attributeQuery( 'target', node=constraint, listChildren=True ): for connection in listConnections( '%s.target[%s].%s' % (constraint, idx, attr), p=True, type='transform', d=False ) or []: toks = connection.split( '.' ) node = toks[ 0 ] if apiExtensions.cmpNodes( node, targetToReplace ): toks[ 0 ] = str( newTarget ) connectAttr( '.'.join( toks ), '%s.target[%s].%s' % (constraint, idx, attr), f=True ) def setupBaseLimbTwister( joint, aimObject, upObject, aimAxis ): ''' Builds a bicep twist rig. Bicep twist joints are basically joints that sit next to the bicep (humerous) in the hierarchy and take all the weighting of the deltoid and upper triceps. Bicep twists don't rotate on their twist axis, but aim at the elbow, so they basically do exactly as the humerous does but don't twist. ''' if not isinstance( aimAxis, Axis ): aimAxis = Axis.FromName( aimAxis ) upAxes = [ ax.asVector() for ax in aimAxis.otherAxes() ] joint = apiExtensions.asMObject( joint ) upObject = apiExtensions.asMObject( upObject ) jWorldMatrix = joint.getWorldMatrix() upVectorsWorld = [ ax * jWorldMatrix for ax in upAxes ] upWorldInvMatrix = upObject.getWorldInverseMatrix() #we want to transform the aimObject's two different axes into the space of the up object upVectorsLocal = [ upVectorsWorld[0] * upWorldInvMatrix, upVectorsWorld[1] * upWorldInvMatrix ] matrixMult = createNode( 'pointMatrixMult', n='bicepTwister_primaryUpAxis' ) setAttr( '%s.inPoint' % matrixMult, *upVectorsLocal[0] ) setAttr( '%s.vectorMultiply' % matrixMult, True ) connectAttr( '%s.worldMatrix[0]' % upObject, '%s.inMatrix' % matrixMult ) vectorProduct = createNode( 'vectorProduct' ) connectAttr( '%s.output' % matrixMult, '%s.input1' % vectorProduct ) setAttr( '%s.operation' % vectorProduct, 1 ) aimNode = aimConstraint( aimObject, joint, aim=aimAxis.asVector(), wuo=upObject, wut='objectrotation' )[0] addAttr( aimNode, ln='upAndAimDot', at='double' ) #create an expression to normalize the constraintVector attribute coming out of the aimConstraint node - its not normalized, and the vector product node doesn't normalize inputs (wtf?!) expressionStr = '''float $mag = sqrt( (%(aimNode)s.constraintVectorX * %(aimNode)s.constraintVectorX) + (%(aimNode)s.constraintVectorY * %(aimNode)s.constraintVectorY) + (%(aimNode)s.constraintVectorZ * %(aimNode)s.constraintVectorZ) ) + 1; float $normX = %(aimNode)s.constraintVectorX / $mag; float $normY = %(aimNode)s.constraintVectorY / $mag; float $normZ = %(aimNode)s.constraintVectorZ / $mag; %(vectorProduct)s.input2X = %(matrixMult)s.outputX * $normX; %(vectorProduct)s.input2Y = %(matrixMult)s.outputX * $normY; %(vectorProduct)s.input2Z = %(matrixMult)s.outputX * $normZ;''' % locals() expression( s=expressionStr ) sdkDriver = '%s.outputX' % vectorProduct connectAttr( sdkDriver, '%s.upAndAimDot' % aimNode ) for upAxis, upVector, driverValues in zip( upAxes, upVectorsLocal, ((0, 0.1), (0.9, 1)) ): for driverValue in driverValues: for upAxisValue, upVectorValue, axisName in zip( upAxis, upVector, Axis.BASE_AXES ): axisName = axisName.upper() setDrivenKeyframe( '%s.upVector%s' % (aimNode, axisName), value=upAxisValue, currentDriver=sdkDriver, driverValue=driverValue, itt='linear', ott='linear' ) setDrivenKeyframe( '%s.worldUpVector%s' % (aimNode, axisName), value=upVectorValue, currentDriver=sdkDriver, driverValue=driverValue, itt='linear', ott='linear' ) for axisName in Axis.BASE_AXES: axisName = axisName.upper() setInfinity( '%s.upVector%s' % (aimNode, axisName), pri='oscillate', poi='oscillate' ) setInfinity( '%s.worldUpVector%s' % (aimNode, axisName), pri='oscillate', poi='oscillate' ) def reorderAttrs( obj, newAttribOrder ): for attr in newAttribOrder: objAttrpath = '%s.%s' % (obj, attr) #if the attribute is locked, we'll need to unlock it to rename it isAttrLocked = getAttr( objAttrpath, l=True ) if isAttrLocked: setAttr( objAttrpath, l=False ) #rename the attribute to a temporary name. You can't rename it to its own name, so we need to rename it to a proxy name, and then back again tempAttrname = '_temp__123xx' while objExists( '%s.%s' % (obj, tempAttrname) ): tempAttrname += '_1' tempAttrib = renameAttr( objAttrpath, tempAttrname ) renameAttr( '%s.%s' % (obj, tempAttrname), attr ) #if the attribute WAS locked, lock it again, in order to maximise transparency if isAttrLocked: setAttr( objAttrpath, l=True ) def dumpNodeAttrs( node ): ''' simple debug function - you can use this to dump out attributes for nodes, stick em in a text file and do a diff can be useful for tracking down how various undocumented nodes mysteriously work ''' attrs = listAttr( node ) for attr in attrs: try: print attr, getAttr( '%s.%s' % (node, attr) ) if attributeQuery( attr, n=node, multi=True ): indices = getAttr( '%s.%s' % (node, attr), multiIndices=True ) or [] for idx in indices: print '\t%d %s' % (idx, getAttr( '%s.%s[%d]' % (node, attr, idx) )) except RuntimeError: print attr except TypeError: print attr del( control ) #end
Python
from rigPrim_curves import * from spaceSwitching import build, NO_TRANSLATION, NO_ROTATION class FkSpine(PrimaryRigPart): __version__ = 0 SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Spine' ), ) def _build( self, skeletonPart, translateControls=True, **kw ): spineBase, spineEnd = skeletonPart.base, skeletonPart.end partParent, rootControl = getParentAndRootControl( spineBase ) #build a list of all spine joints - start from the bottom of the heirarchy, and work up - a joint only has one parent spines = [ spineEnd ] if spineBase != spineEnd: while True: p = getNodeParent( spines[ -1 ] ) spines.append( p ) if p == spineBase: break spines.reverse() #try to figure out a sensible offset for the spine controls - this is basically just an average of the all offsets for all spine joints spineOffset = AX_Z.asVector() * getAutoOffsetAmount( spines[ 0 ], spines ) #create the controls, and parent them #determine what axis to draw the spine controls - assume they're all the same as the spine base controlSpaces = [] controllers = [] startColour = ColourDesc( (1, 0.3, 0, 0.65) ) endColour = ColourDesc( (0.8, 1, 0, 0.65) ) spineColour = startColour colourInc = (endColour - startColour) / float( len( spines ) ) for n, j in enumerate( spines ): c = buildControl( "spine_%d_fkControl" % n, j, PivotModeDesc.BASE, ShapeDesc( 'pin', axis=AX_Z ), colour=spineColour, offset=spineOffset, scale=self.scale*1.5, niceName='Spine %d Control' % n ) cSpace = getNodeParent( c ) jParent = partParent if n: jParent = controllers[ -1 ] controllers.append( c ) controlSpaces.append( cSpace ) parent( cSpace, jParent ) spineColour += colourInc setNiceName( controllers[ 0 ], 'Spine Base' ) setNiceName( controllers[ -1 ], 'Spine End' ) #create the space switching for j, c in zip( spines, controllers ): buildDefaultSpaceSwitching( j, c, **spaceSwitching.NO_TRANSLATION ) #create line of action commands createLineOfActionMenu( spines, controllers ) #turn unwanted transforms off, so that they are locked, and no longer keyable if not translateControls: attrState( controllers, 't', *LOCK_HIDE ) return controllers, () class IKFKSpine(PrimaryRigPart): __version__ = 0 PRIORITY = 10 #make this a lower priority than the simple FK spine rig SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Spine' ), ) @classmethod def CanRigThisPart( cls, skeletonPart ): return len( skeletonPart ) >= 3 def _build( self, skeletonPart, squish=True, **kw ): objs = skeletonPart.items parentControl, rootControl = getParentAndRootControl( objs[0] ) fittedCurve, linearCurve, proxies, fixedLengthProxies, controls, splineIkHandle, halfIdx = buildControls( objs, parentControl, name='spineControl', **kw ) buildDefaultSpaceSwitching( objs[0], controls[-1] ) parent( proxies, self.getPartsNode() ) parent( fittedCurve, linearCurve, self.getPartsNode() ) if splineIkHandle: parent( splineIkHandle, self.getPartsNode() ) if fixedLengthProxies: parent( fixedLengthProxies[0], self.getPartsNode() ) return controls, () #end
Python
''' Referencing in maya kinda sucks. Getting reference information from nodes/files is split across at least 3 different mel commands in typically awkward autodesk fashion, and there is a bunch of miscellaneous functionality that just doesn't exist at all. So this module is supposed to be a collection of functionality that alleviates this somewhat... ''' from maya.cmds import * from filesystem import Path def isFileReferenced( filepath ): return ReferencedFile.IsFilepathReferenced( filepath ) def stripNamespaceFromNamePath( name, namespace ): ''' strips out the given namespace from a given name path. example: stripNamespaceFromNamePath( 'moar:ns:wow:some|moar:ns:wow:name|moar:ns:wow:path', 'ns' ) returns: 'wow:some|wow:name|wow:path' ''' if namespace.endswith( ':' ): namespace = namespace[ :-1 ] cleanPathToks = [] for pathTok in name.split( '|' ): namespaceToks = pathTok.split( ':' ) if namespace in namespaceToks: idx = namespaceToks.index( namespace ) namespaceToks = namespaceToks[ idx+1: ] cleanPathToks.append( ':'.join( namespaceToks ) ) return '|'.join( cleanPathToks ) def addNamespaceTokNamePath( name, namespace ): ''' adds the given namespace to a name path. example: addNamespaceTokNamePath( 'some|name|path', 'ns' ) returns: 'ns:some|ns:name|ns:path' ''' if namespace.endswith( ':' ): namespace = namespace[ :-1 ] namespacedToks = [] for pathTok in name.split( name, '|' ): namespacedToks.append( '%s:%s' % (namespace, name) ) return '|'.join( namespacedToks ) class ReferencedFile(object): @classmethod def IterAll( cls ): for referenceNode in ls( type='reference' ): try: referenceFilepath = Path( referenceQuery( referenceNode, filename=True ) ) #maya throws an exception on "shared" references - whatever the F they are. so catch and skip when this happens except RuntimeError: continue yield referenceFilepath @classmethod def IsFilepathReferenced( cls, filepath ): for refFilepath in cls.IterAll(): if refFilepath == filepath: return True return False def __init__( self, filepath ): self._filepath = filepath def getReferenceNode( self ): return file( self._filepath, q=True, referenceNode=True ) def getReferenceNamespace( self ): ''' returns the namespace for this reference - this doesn't include referenced namespaces if this reference is nested ''' return file( self._filepath, q=True, namespace=True ) def isNested( self ): ''' returns whether this reference is nested ''' return referenceQuery( self.getReferenceNode(), inr=True ) def load( self ): raise NotImplemented def unload( self ): raise NotImplemented class ReferencedNode(object): def __init__( self, node ): self._node = node self._isReferenced = referenceQuery( node, inr=True ) def isReferenced( self ): return self._isReferenced def getFilepath( self, copyNumber=False ): ''' will return the filepath to the scene file this node comes from. If copyNumber=True then the "copy number" will be included in the filepath - see the docs for the referenceQuery mel command for more information ''' if not self._isReferenced: return None return Path( referenceQuery( self._node, filename=True, withoutCopyNumber=not copyNumber ) ) def getReferencedFile( self, copyNumber=False ): return ReferencedFile( self.getFilepath() ) def getReferenceNode( self ): if not self._isReferenced: return None return file( self.getFilepath(), q=True, referenceNode=True ) def getNamespace( self ): raise NotImplemented def getReferenceNamespace( self ): ''' returns the namespace for this reference - this doesn't include referenced namespaces if this reference is nested ''' return file( self.getFilepath( True ), q=True, namespace=True ) def getNode( self ): return self._node def getUnreferencedNode( self ): ''' returns the node name as it would be in the scene the node comes from ''' refNode = self.getReferenceNode() return stripNamespaceFromNamePath( self._node, self.getReferenceNamespace() ) def removeEdits( self ): raise NotImplemented #end
Python
''' provides console colouring - currently only NT is supported ''' STD_OUTPUT_HANDLE = -11 FG_BLUE = 0x01 FG_GREEN = 0x02 FG_CYAN = 0x03 FG_RED = 0x04 FG_MAGENTA = 0x05 FG_YELLOW = 0x06 FG_WHITE = 0x07 BRIGHT = 0x08 BG_BLUE = 0x10 BG_GREEN = 0x20 BG_CYAN = 0x30 BG_RED = 0x40 BG_MAGENTA = 0x50 BG_YELLOW = 0x60 BG_BRIGHT = 0x80 import sys try: import ctypes def setConsoleColour( colour ): ''' sets the subsequent console spew to a given colour eg. setConsoleColour(BRIGHT | FG_GREEN) ''' std_out_handle = ctypes.windll.kernel32.GetStdHandle( STD_OUTPUT_HANDLE ) ctypes.windll.kernel32.SetConsoleTextAttribute( std_out_handle, colour ) except: def setConsoleColour( colour ): pass class ColouredWriter: def __init__( self, colour ): self.colour = colour def write( self, msg ): setConsoleColour( self.colour ) sys.stdout.write( msg ) setConsoleColour( FG_WHITE ) def logInColour( msg, colour ): print >> ColouredWriter( colour ), msg ''' create some useful, common colouredWriter instances. an example for using these: print >> Error, 'hello, im an error' ''' Warn = ColouredWriter( BRIGHT | FG_YELLOW ) Error = ColouredWriter( BRIGHT | FG_RED ) Good = ColouredWriter( BRIGHT | FG_GREEN ) BigError = ColouredWriter( BRIGHT | FG_RED | BG_RED ) def logAsWarning( msg ): print >> Warn, msg def logAsError( msg ): print >> Error, msg #end
Python
from baseRigPrimitive import * from skeletonPart_arbitraryChain import ArbitraryChain class ControlHierarchy(PrimaryRigPart): __version__ = 0 #part doesn't have a CONTROL_NAMES list because parts are dynamic - use indices to refer to controls SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'ArbitraryChain' ), ) def _build( self, part, controlShape=DEFAULT_SHAPE_DESC, spaceSwitchTranslation=False, parents=(), rigOrphans=False, **kw ): joints = list( part ) + (part.getOrphanJoints() if rigOrphans else []) return controlChain( self, joints, controlShape, spaceSwitchTranslation, parents, rigOrphans, **kw ), () class WeaponControlHierarchy(PrimaryRigPart): __version__ = 0 SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'WeaponRoot' ), ) def _build( self, part, controlShape=DEFAULT_SHAPE_DESC, spaceSwitchTranslation=True, parents=(), **kw ): return controlChain( self, part.selfAndOrphans(), controlShape, spaceSwitchTranslation, parents, True, **kw ), () def controlChain( rigPart, joints, controlShape=DEFAULT_SHAPE_DESC, spaceSwitchTranslation=False, parents=(), rigOrphans=False, **kw ): scale = kw[ 'scale' ] #discover parent nodes namespace = '' try: namespace = getNamespaceFromReferencing( joints[ 0 ] ) except IndexError: pass parents = tuple( '%s%s' % (namespace, p) for p in parents ) ### DETERMINE THE PART'S PARENT CONTROL AND THE ROOT CONTROL ### parentControl, rootControl = getParentAndRootControl( joints[ 0 ] ) ctrls = [] prevParent = parentControl for item in joints: ctrl = buildControl( '%s_ctrl' % item, item, PivotModeDesc.BASE, controlShape, size=AUTO_SIZE ) ctrlSpace = getNodeParent( ctrl ) #do parenting parent( ctrlSpace, prevParent ) #stuff objects into appropriate variables prevParent = ctrl ctrls.append( ctrl ) #lock un-needed axes if not spaceSwitchTranslation: attrState( ctrl, 't', *LOCK_HIDE ) #setup space switching buildKwargs = {} if spaceSwitchTranslation else spaceSwitching.NO_TRANSLATION for n, (ctrl, j) in enumerate( zip( ctrls, joints ) ): buildDefaultSpaceSwitching( j, ctrl, parents, reverseHierarchy=False, **buildKwargs ) createLineOfActionMenu( joints, ctrls ) return ctrls #end
Python
from baseSkeletonBuilder import * class _QuadCommon(object): AVAILABLE_IN_UI = False def _buildPlacers( self ): assert isinstance( self, SkeletonPart ) parity = self.getParity() parityMultiplier = parity.asMultiplier() scale = self.getBuildScale() / 30 toeTipPlacer = buildEndPlacer() heelPlacer = buildEndPlacer() innerRollPlacer = buildEndPlacer() outerRollPlacer = buildEndPlacer() placers = toeTipPlacer, heelPlacer, innerRollPlacer, outerRollPlacer cmd.parent( placers, self.end, r=True ) fwd = MAYA_SIDE side = MAYA_UP setAttr( '%s.t' % toeTipPlacer, *(fwd * 2 * scale) ) setAttr( '%s.t' % heelPlacer, *(-fwd * scale) ) setAttr( '%s.t' % innerRollPlacer, *(side * scale * parityMultiplier) ) setAttr( '%s.t' % outerRollPlacer, *(-side * scale * parityMultiplier) ) return placers def visualize( self ): pass class QuadrupedFrontLeg(_QuadCommon, SkeletonPart.GetNamedSubclass('Arm')): ''' A quadruped's front leg is more like a biped's arm as it has clavicle/shoulder blade functionality, but is generally positioned more like a leg. It is a separate part because it is rigged quite differently from either a bipedal arm or a bipedal leg. ''' AVAILABLE_IN_UI = True PLACER_NAMES = 'toeTip', 'innerRoll', 'outerRoll', 'heelRoll' @classmethod def _build( cls, parent=None, **kw ): idx = Parity( kw[ 'idx' ] ) partScale = kw[ 'partScale' ] parent = getParent( parent ) height = xform( parent, q=True, ws=True, rp=True )[ 1 ] dirMult = idx.asMultiplier() parityName = idx.asName() clavicle = createJoint( 'quadClavicle%s' % parityName ) cmd.parent( clavicle, parent, relative=True ) move( dirMult * partScale / 10.0, -partScale / 10.0, partScale / 6.0, clavicle, r=True, ws=True ) bicep = createJoint( 'quadHumerous%s' % parityName ) cmd.parent( bicep, clavicle, relative=True ) move( 0, -height / 3.0, -height / 6.0, bicep, r=True, ws=True ) elbow = createJoint( 'quadElbow%s' % parityName ) cmd.parent( elbow, bicep, relative=True ) move( 0, -height / 3.0, height / 10.0, elbow, r=True, ws=True ) wrist = createJoint( 'quadWrist%s' % parityName ) cmd.parent( wrist, elbow, relative=True ) move( 0, -height / 3.0, 0, wrist, r=True, ws=True ) jointSize( clavicle, 2 ) jointSize( wrist, 2 ) return [ clavicle, bicep, elbow, wrist ] class QuadrupedBackLeg(_QuadCommon, SkeletonPart.GetNamedSubclass( 'Arm' )): ''' The creature's back leg is more like a biped's leg in terms of the joints it contains. However, like the front leg, the creature stands on his "tip toes" at the back as well. ''' AVAILABLE_IN_UI = False @classmethod def _build( cls, parent=None, **kw ): idx = Parity( kw[ 'idx' ] ) partScale = kw[ 'partScale' ] parent = getParent( parent ) height = xform( parent, q=True, ws=True, rp=True )[ 1 ] dirMult = idx.asMultiplier() parityName = idx.asName() kneeFwdMove = height / 10.0 thigh = createJoint( 'quadThigh%s' % parityName ) thigh = cmd.parent( thigh, parent, relative=True )[ 0 ] move( dirMult * partScale / 10.0, -partScale / 10.0, -partScale / 5.0, thigh, r=True, ws=True ) knee = createJoint( 'quadKnee%s' % parityName ) knee = cmd.parent( knee, thigh, relative=True )[ 0 ] move( 0, -height / 3.0, kneeFwdMove, knee, r=True, ws=True ) ankle = createJoint( 'quadAnkle%s' % parityName ) ankle = cmd.parent( ankle, knee, relative=True )[ 0 ] move( 0, -height / 3.0, -kneeFwdMove, ankle, r=True, ws=True ) toe = createJoint( 'quadToe%s' % parityName ) toe = cmd.parent( toe, ankle, relative=True )[ 0 ] move( 0, -height / 3.0, 0, toe, r=True, ws=True ) jointSize( thigh, 2 ) jointSize( ankle, 2 ) jointSize( toe, 1.5 ) return [ thigh, knee, ankle, toe ] class SatyrLeg(_QuadCommon, SkeletonPart.GetNamedSubclass('Leg')): AVAILABLE_IN_UI = True PLACER_NAMES = QuadrupedFrontLeg.PLACER_NAMES @property def thigh( self ): return self[ 0 ] @property def knee( self ): return self[ 1 ] @property def ankle( self ): return self[ 2 ] @property def toe( self ): return self[ 3 ] if len( self ) > 3 else None @classmethod def _build( cls, parent=None, **kw ): idx = Parity( kw[ 'idx' ] ) partScale = kw[ 'partScale' ] parent = getParent( parent ) height = xform( parent, q=True, ws=True, rp=True )[ 1 ] dirMult = idx.asMultiplier() parityName = idx.asName() legDrop = partScale / 12.0 sectionDist = (height - legDrop) / 3.0 kneeFwdMove = (height - legDrop) / 3.0 thigh = createJoint( 'thigh%s' % parityName ) thigh = cmd.parent( thigh, parent, relative=True )[ 0 ] move( dirMult * partScale / 10.0, -legDrop, 0, thigh, r=True, ws=True ) knee = createJoint( 'knee%s' % parityName ) knee = cmd.parent( knee, thigh, relative=True )[ 0 ] move( 0, -sectionDist, kneeFwdMove, knee, r=True, ws=True ) ankle = createJoint( 'ankle%s' % parityName ) ankle = cmd.parent( ankle, knee, relative=True )[ 0 ] move( 0, -sectionDist, -kneeFwdMove, ankle, r=True, ws=True ) toe = createJoint( 'toeBall%s' % parityName ) toe = cmd.parent( toe, ankle, relative=True )[ 0 ] move( 0, -sectionDist, kneeFwdMove / 2.0, toe, r=True, ws=True ) jointSize( thigh, 2 ) jointSize( ankle, 2 ) jointSize( toe, 1.5 ) return [ thigh, knee, ankle, toe ] def _align( self, _initialAlign=False ): upperNormal = getPlaneNormalForObjects( self.thigh, self.knee, self.ankle ) upperNormal *= self.getParityMultiplier() parity = self.getParity() alignAimAtItem( self.thigh, self.knee, parity, worldUpVector=upperNormal ) alignAimAtItem( self.knee, self.ankle, parity, worldUpVector=upperNormal ) if self.toe: lowerNormal = getPlaneNormalForObjects( self.knee, self.ankle, self.toe ) lowerNormal *= self.getParityMultiplier() alignAimAtItem( self.ankle, self.toe, parity, worldUpVector=upperNormal ) for i in self.getOrphanJoints(): alignItemToLocal( i ) #end
Python
import re import rigPrimitives from maya.cmds import * from baseMelUI import * from mayaDecorators import d_disableViews, d_noAutoKey, d_unifyUndo, d_restoreTime from common import printWarningStr from triggered import Trigger from rigUtils import findPolePosition, alignFast _FK_CMD_NAME = 'switch to FK'.lower() _IK_CMD_NAME = 'switch to IK'.lower() def cropValues( valueList, minVal=None, maxVal=None ): ''' assumes the input list is sorted NOTE: the input list is modified in place and nothing is returned ''' if minVal is not None: while valueList: if valueList[0] < minVal: valueList.pop( 0 ) else: break if maxVal is not None: while valueList: if valueList[-1] > maxVal: valueList.pop() else: break def getJointsFromIkHandle( handle ): #get the joints the ik control drives - we need these to get keyframes from so we know which frames to trace the ik control on joints = ikHandle( handle, q=True, jl=True ) effector = ikHandle( handle, q=True, ee=True ) cons = listConnections( '%s.tx' % effector, d=False ) if not cons: printWarningStr( "Could not find the end effector control!" ) return joints.append( cons[0] ) return joints def getControlsFromObjs( control ): ''' attempts to retrieve the pole vector control, the ik handle and all fk controls given an ik rig control. The information is returned in a 3 tuple containing: ikHandle, poleControl, fkControls ''' errorValue = None, None, None, None try: part = rigPrimitives.RigPart.InitFromItem( control ) return part.getControl( 'control' ), part.getIkHandle(), part.getControl( 'poleControl' ), part.getFkControls() except rigPrimitives.RigPartError: pass #so if the control we've been given isn't a rig primitive, lets try to extract whatever information we can from right click commands - if any exist trigger = Trigger( ikControl ) switchCmdStr = None for n, cmdName, cmdStr in trigger.iterMenus(): if cmdName.lower() == _IK_CMD_NAME: switchCmdStr = trigger.resolve( cmdStr ) break if switchCmdStr is None: printWarningStr( "Cannot find the %s command - aborting!" % _IK_CMD_NAME ) return errorValue #extract the control handle from the switch command - it may or may not exist, depending on which rexStr = re.compile( '-ikHandle \%([a-ZA-Z0-9_:|]+)', re.IGNORECASE | re.MULTILINE ) match = rexStr.search( switchCmdStr ) if not match: if match.groups()[0]: control = match.groups()[0] #extract the ik handle from the switch command rexStr = re.compile( '-ikHandle \%([a-ZA-Z0-9_:|]+)', re.IGNORECASE | re.MULTILINE ) match = rexStr.search( switchCmdStr ) if not match: printWarningStr( "Could not determine the ik handle from the given control" ) return errorValue handle = match.groups()[0] if handle is None: printWarningStr( "Could not find the ik handle at the given connect index!" ) return errorValue #now extract the pole control from the switch command rexStr = re.compile( '-pole \%([a-ZA-Z0-9_:|]+)', re.IGNORECASE | re.MULTILINE ) match = rexStr.search( switchCmdStr ) if not match: printWarningStr( "Could not determine the pole vector control from the given control" ) return errorValue poleControl = match.groups()[0] if poleControl is None: printWarningStr( "Could not find the ik handle at the given connect index!" ) return errorValue return control, poleControl, handle, getJointsFromIkHandle( handle ) @d_unifyUndo @d_disableViews @d_noAutoKey @d_restoreTime def switchAnimationToFk( control, handle=None, attrName='ikBlend', onValue=1, offValue=0, key=True, startFrame=None, endFrame=None ): #grab the key times for keys set on the t or r channels on the ik control - these are the frames we want to switch to fk on keyTimes = keyframe( control, q=True, at=('t', 'r'), tc=True ) if not keyTimes: switchToFk( control, handle, attrName, offValue, key ) printWarningStr( "No keys found on the ik control - nothing to do!" ) return #remove duplicate key times and sort them keyTimes = removeDupes( keyTimes ) keyTimes.sort() cropValues( keyTimes, startFrame, endFrame ) joints = getJointsFromIkHandle( handle ) for time in keyTimes: currentTime( time, e=True ) switchToFk( control, handle, attrName, onValue, offValue, key, joints ) select( joints[-1] ) @d_unifyUndo @d_disableViews @d_noAutoKey @d_restoreTime def switchAnimationToIk( control, poleControl=None, handle=None, attrName='ikBlend', onValue=1, key=True, startFrame=None, endFrame=None ): #get the joints the ik control drives - we need these to get keyframes from so we know which frames to trace the ik control on joints = getJointsFromIkHandle( handle ) if not joints: printWarningStr( "Cannot find the fk controls for the given ik control" ) return #grab the key times for keys set on the t or r channels on the ik control - these are the frames we want to switch to fk on keyTimes = keyframe( joints, q=True, at=('t', 'r'), tc=True ) if not keyTimes: switchToIk( ikControl, poleControl, handle, attrName, onValue, key ) printWarningStr( "No keys found on the fk controls - nothing to do!" ) return #remove duplicate key times and sort them keyTimes = removeDupes( keyTimes ) keyTimes.sort() cropValues( keyTimes, startFrame, endFrame ) #clear out the keys for the ik control cutKey( control, poleControl, t=(keyTimes[0], keyTimes[-1]), cl=True ) startFrame = keyTimes[0] currentTime( startFrame, e=True ) setKeyframe( control, poleControl, t=(startFrame,) ) for time in keyTimes: currentTime( time, e=True ) switchToIk( control, poleControl, handle, attrName, onValue, key, joints, _isBatchMode=True ) setKeyframe( control, t=keyTimes, at=attrName, v=onValue ) select( control ) def switchToFk( control, handle=None, attrName='ikBlend', onValue=1, offValue=0, key=False, joints=None ): if handle is None: handle = control if handle is None or not objExists( handle ): printWarningStr( "no ikHandle specified" ) return #if we weren't passed in joints - discover them now if joints is None: joints = getJointsFromIkHandle( handle ) #make sure ik is on before querying rotations setAttr( '%s.%s' % (control, attrName), onValue ) rots = [] for j in joints: rot = getAttr( "%s.r" % j )[0] rots.append( rot ) #now turn ik off and set rotations for the joints setAttr( '%s.%s' % (control, attrName), offValue ) for j, rot in zip( joints, rots ): for ax, r in zip( ('x', 'y', 'z'), rot ): if getAttr( '%s.r%s' % (j, ax), se=True ): setAttr( '%s.r%s' % (j, ax), r ) alignFast( joints[2], handle ) if key: setKeyframe( joints ) setKeyframe( '%s.%s' % (control, attrName) ) def switchToIk( control, poleControl=None, handle=None, attrName='ikBlend', onValue=1, key=False, joints=None, _isBatchMode=False ): if handle is None: handle = control if handle is None or not objExists( handle ): printWarningStr( "no ikHandle specified" ) return #if we weren't passed in joints - discover them now if joints is None: joints = getJointsFromIkHandle( handle ) alignFast( control, joints[2] ) if poleControl: if objExists( poleControl ): pos = findPolePosition( joints[2], joints[1], joints[0] ) move( pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True ) setKeyframe( poleControl ) setAttr( '%s.%s' % (control, attrName), onValue ) if key: setKeyframe( control, at=('t', 'r') ) if not _isBatchMode: setKeyframe( control, at=attrName ) class ChangeIkFkLayout(MelColumnLayout): def __init__( self, parent ): self.UI_control = MelObjectSelector( self, 'control ->', None, 100 ) self.UI_pole = MelObjectSelector( self, 'pole control ->', None, 100 ) self.UI_handle = MelObjectSelector( self, 'IK handle ->', None, 100 ) self.UI_control.setChangeCB( self.on_controlChanged ) hLayout = MelHLayout( self ) self.UI_toFk = MelButton( hLayout, l='Switch to FK', c=self.on_toFk ) self.UI_toIk = MelButton( hLayout, l='Switch to IK', c=self.on_toIk ) hLayout.layout() self.on_controlChanged() def setControl( self, control ): self.UI_control.setValue( control ) ### EVENT HANDLERS ### def on_controlChanged( self ): control = self.UI_control.getValue() if control: self.UI_toFk.setEnabled( True ) self.UI_toIk.setEnabled( True ) control, handle, poleControl, _tmp = getControlsFromObjs( control ) self.UI_control.setValue( control, False ) if handle: self.UI_handle.setValue( handle, False ) if poleControl: self.UI_pole.setValue( poleControl, False ) else: self.UI_toFk.setEnabled( False ) self.UI_toIk.setEnabled( False ) ### EVENT HANDLERS ### def on_sceneChange( self, a ): self.UI_control.clear() self.UI_pole.clear() self.UI_handle.clear() def on_toFk( self, *a ): control = self.UI_control.getValue() if control: switchAnimationToFk( control, self.UI_handle.getValue() ) def on_toIk( self, *a ): control = self.UI_control.getValue() if control: switchAnimationToIk( control, self.UI_pole.getValue(), self.UI_handle.getValue() ) class ChangeIkFkWindow(BaseMelWindow): WINDOW_NAME = 'changeIkFkWindow' WINDOW_TITLE = 'Ik Fk Switcher' DEFAULT_SIZE = 400, 150 DEFAULT_MENU = None FORCE_DEFAULT_SIZE = True def __init__( self ): self.UI_editor = ChangeIkFkLayout( self ) self.show() def setControl( self, control ): self.UI_editor.setControl( control ) def loadSelectedInTool(): sel = ls( sl=True, type='transform' ) if sel: if not ChangeIkFkWindow.Exists(): ChangeIkFkWindow() for layout in ChangeIkFkLayout.IterInstances(): layout.setControl( sel[0] ) #end
Python
from filesystem import Path, removeDupes, Callback from api import mel from names import getCommonPrefix from baseMelUI import * import maya.cmds as cmd import mappingEditor import skinWeights import meshUtils import rigUtils import time import api def isMesh( item ): shapes = cmd.listRelatives( item, shapes=True, pa=True ) if shapes is None: return None for s in shapes: if cmd.nodeType( s ) == 'mesh': return s class LockJointsLayout(MelForm): SUSPEND_UPDATE = False def __init__( self, parent ): MelForm.__init__( self, parent ) self._mesh = None self._prefix = '' class JointList(MelObjectScrollList): def itemAsStr( tsl, item ): locked = cmd.getAttr( '%s.liw' % item ) prefix = '# ' if locked else ' ' return '%s%s' % (prefix, item.replace( self._prefix, '' )) self.UI_tsl = JointList( self, ams=True, sc=self.on_selectJoint, dcc=self.on_dcc ) self.POP_tsl = cmd.popupMenu( b=3, p=self.UI_tsl, pmc=self.build_tslMenu ) self.UI_lock = cmd.button( l="lock", c=self.on_lock ) self.UI_unlock = cmd.button( l="unlock", c=self.on_unlock ) self.UI_lockAll = cmd.button( l="LOCK ALL", c=self.on_lockAll ) self.UI_unlockAll = cmd.button( l="UNLOCK ALL", c=self.on_unlockAll ) self( e=True, af=((self.UI_tsl, 'top', 0), (self.UI_tsl, 'left', 0), (self.UI_tsl, 'right', 0), (self.UI_lock, 'left', 0), (self.UI_unlock, 'right', 0), (self.UI_lockAll, 'left', 0), (self.UI_lockAll, 'bottom', 0), (self.UI_unlockAll, 'right', 0), (self.UI_unlockAll, 'bottom', 0)), ap=((self.UI_lock, 'right', 0, 50), (self.UI_unlock, 'left', 0, 50), (self.UI_lockAll, 'right', 0, 50), (self.UI_unlockAll, 'left', 0, 50)), ac=((self.UI_tsl, 'bottom', 0, self.UI_lock), (self.UI_lock, 'bottom', 0, self.UI_lockAll), (self.UI_unlock, 'bottom', 0, self.UI_unlockAll)) ) self.setSelectionChangeCB( self.on_selectionChange ) self.on_selectionChange() @classmethod def Update( cls ): for inst in cls.IterInstances(): inst.syncSelection() def iterSelected( self ): return iter( self.UI_tsl.getSelectedItems() ) def attachToMesh( self, mesh ): self._mesh = mesh self._skinCluster = mel.findRelatedSkinCluster( mesh ) joints = cmd.skinCluster( self._skinCluster, q=True, inf=True ) self._prefix = getCommonPrefix( joints ) self.UI_tsl.setItems( joints ) self.on_updateState() def updateJointState( self, joint ): self.UI_tsl.update() def setLockStateForSelected( self, state=True, updateUI=True ): for j in self.iterSelected(): cmd.setAttr( '%s.liw' % j, state ) if updateUI: self.on_updateState() def setLockStateForAll( self, state=True, updateUI=True ): for j in self.UI_tsl: cmd.setAttr( '%s.liw' % j, state ) if updateUI: self.on_updateState() def smoothBetweenSelectedJoints( self ): ''' performs a flood smooth between the selected joints ''' #grab initial state initialLockState = [ cmd.getAttr( '%s.liw' % j ) for j in self.UI_tsl ] initMode = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, sao=True ) initOpacity = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, opacity=True ) initValue = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, value=True ) self.setLockStateForAll( True, False ) self.setLockStateForSelected( False, False ) #perform the smooth cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, sao='smooth' ) j = self.iterSelected().next() if j is not None: cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, value=1, opacity=1, clear=True ) #restore state cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, sao=initMode ) cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, opacity=initOpacity ) cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, value=initValue ) for j, state in zip( self.UI_tsl, initialLockState ): cmd.setAttr( '%s.liw' % j, state ) def syncSelection( self ): ''' syncs the list selection with the existing paint skin weights UI ''' cur = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, inf=True ) if cur is None: return self.UI_tsl.clearSelection() self.UI_tsl.selectByValue( cur ) ### MENU BUILDERS ### def build_tslMenu( self, *a ): cmd.setParent( a[ 0 ], m=True ) cmd.menu( a[ 0 ], e=True, dai=True ) numSelected = sum(( 1 for j in self.iterSelected() )) cmd.menuItem( l="Select Verts For Joint", c=self.on_selectVerts ) if numSelected > 1: cmd.menuItem( l="Select Verts Shared By Selected", c=self.on_selectIntersectingVerts ) cmd.menuItem( l="Select Whole Mesh", c=self.on_selectMesh ) cmd.menuItem( d=True ) #cmd.menuItem( l="Smooth Between Selected Joints", c=self.on_smooth ) ### EVENT HANDLERS ### def on_selectionChange( self, *a ): self.syncSelection() sel = cmd.ls( sl=True ) for s in sel: mesh = isMesh( s ) #its already setup! bail! if self._mesh == mesh: return if mesh: self.attachToMesh( mesh ) return def on_updateState( self, *a ): if self.SUSPEND_UPDATE: return self.UI_tsl.update() def on_selectJoint( self, *a ): if cmd.currentCtx() == 'artAttrSkinContext': selJ = self.iterSelected().next() if selJ is None: return mel.artSkinSelectInfluence( 'artAttrSkinPaintCtx', selJ, selJ ) def on_dcc( self, *a ): cmd.select( cl=True ) for j in self.iterSelected(): cmd.select( j, add=True ) def on_lock( self, *a ): self.setLockStateForSelected() def on_unlock( self, *a ): self.setLockStateForSelected( False ) def on_lockAll( self, *a ): self.setLockStateForAll() def on_unlockAll( self, *a ): self.setLockStateForAll( False ) def on_selectVerts( self, *a ): selJoints = self.UI_tsl.getSelectedItems() if not selJoints: return verts = [] for j in selJoints: verts += meshUtils.jointVertsForMaya( j ) if verts: cmd.hilite( [ self._mesh ] ) cmd.select( verts ) mel.artAttrSkinToolScript( 4 ) def on_selectIntersectingVerts( self, *a ): selJoints = self.UI_tsl.getSelectedItems() if not selJoints: return allVerts = [] jointVerts = {} for j in selJoints: jointVerts[ j ] = verts = meshUtils.jointVertsForMaya( j ) allVerts += verts allVerts = set( allVerts ) commonVerts = [] for j, jVerts in jointVerts.iteritems(): commonVerts += allVerts.intersection( set( jVerts ) ) if commonVerts: cmd.hilite( [ self._mesh ] ) cmd.select( commonVerts ) mel.artAttrSkinToolScript( 4 ) def on_selectMesh( self, *a ): cmd.hilite( unHilite=True ) cmd.select( self._mesh ) mel.artAttrSkinToolScript( 4 ) def on_smooth( self, *a ): self.smoothBetweenSelectedJoints() class LockJointsWindow(BaseMelWindow): WINDOW_NAME = 'lockWeightEditor' WINDOW_TITLE = 'weight locker' DEFAULT_SIZE = 300, 400 DEFAULT_MENU = None FORCE_DEFAULT_SIZE = True def __new__( cls, **kw ): return BaseMelWindow.__new__( cls, resizeToFitChildren=True, maximizeButton=False, sizeable=True ) def __init__( self ): BaseMelWindow.__init__( self ) self.editor = LockJointsLayout( self ) self.show() class SectionLabel(MelHSingleStretchLayout): def __init__( self, parent, label ): MelHSingleStretchLayout.__init__( self, parent ) MelSeparator( self, w=25, h=20 ) MelLabel( self, l=label, h=20 ) s = MelSeparator( self, h=20 ) self.setStretchWidget( s ) self.layout() class Spacer(MelLabel): def __new__( cls, parent, size=10 ): return MelLabel.__new__( cls, parent, w=size, h=size, l='' ) def __init__( self, parent, size=10 ): MelLabel.__init__( self, parent, size ) class SkinButtonsLayout(MelHLayout): def __init__( self, parent ): MelHLayout.__init__( self, parent ) a = self.UI_skinOff = MelButton( self, l='Turn Skinning Off', c=self.on_skinOff ) b = self.UI_skinOn = MelButton( self, l='Turn Skinning On', c=self.on_skinOn ) c = MelButton( self, l='Reset All Skin Clusters', c=self.on_resetSkin ) self.updateSkinButtons() self.layout() def updateSkinButtons( self ): state = rigUtils.getSkinClusterEnableState() self.UI_skinOn( e=True, en=not state ) self.UI_skinOff( e=True, en=state ) ### EVENT HANDLERS ### def on_skinOff( self, e=None ): rigUtils.disableSkinClusters() self.updateSkinButtons() def on_skinOn( self, e=None ): rigUtils.enableSkinClusters() self.updateSkinButtons() def on_resetSkin( self, e=None ): for sc in ls( typ='skinCluster' ): rigUtils.resetSkinCluster( sc ) class WeightsToOtherLayout(MelHLayout): def __init__( self, parent ): MelHLayout.__init__( self, parent ) self.UI_toParent = MelButton( self, l='Weighting To Parent Joint', ann='Transfers weighting from all selected joints to their respective parents', c=self.on_toParent ) self.UI_toOther = MelButton( self, l='Weighting To Last Selected Joint', ann='Transfers the weighting from the selected joints to the joint that was selected last', c=self.on_toOther ) self.layout() ### EVENT HANDLERS ### def on_toParent( self, e=None ): sel = cmd.ls( sl=True, type='transform' ) or [] for s in sel: meshUtils.weightsToOther( s ) def on_toOther( self, e=None ): sel = cmd.ls( sl=True, type='transform' ) or [] lastSelectedJoint = sel.pop() for s in sel: meshUtils.weightsToOther( s, lastSelectedJoint ) class MeshMappingEditor(mappingEditor.MappingEditor): WINDOW_NAME = 'skinWeightsMeshMapper' WINDOW_TITLE = 'Mesh Re-Map Editor' class JointMappingEditor(mappingEditor.MappingEditor): WINDOW_NAME = 'skinWeightsJointMapper' WINDOW_TITLE = 'Joint Re-Map Editor' class SkinWeightsLayout(MelColumnLayout): LBL_MESH_REMAP_BUTTON_HASMAP = "define mesh re-mapping (map defined)" LBL_MESH_REMAP_BUTTON_NOMAP = "define mesh re-mapping" LBL_JOINT_REMAP_BUTTON_HASMAP = "define joint re-mapping (map defined)" LBL_JOINT_REMAP_BUTTON_NOMAP = "define joint re-mapping" def __init__( self, parent, *a, **kw ): MelColumnLayout.__init__( self, parent, *a, **kw ) SectionLabel( self, 'store options' ) hLayout = MelHSingleStretchLayout( self ) self.UI_fileLbl = MelLabel( hLayout, l="weight file (optional)" ) self.UI_file = MelTextField( hLayout ) hLayout.setStretchWidget( self.UI_file ) hLayout.layout() MelPopupMenu( self.UI_file, pmc=self.build_popup ) self.UI_storeA = MelButton( self, l="store selection to file", c=self.on_storeA ) #self.UI_storeB = MelButton( self, l="store joint volumes to file", c=self.on_storeB ) Spacer( self ) SectionLabel( self, 'restore options' ) hLayout = MelHSingleStretchLayout( self ) self.UI_average = MelCheckBox( hLayout, l="average found verts", v=1 ) self.UI_ratioLbl = MelLabel( hLayout, l="max ratio" ) self.UI_ratio = MelFloatField( hLayout, v=2, w=50 ) hLayout.setStretchWidget( self.UI_ratio ) hLayout.layout() self.UI_mirror = MelCheckBox( self, l="mirror on restore", v=0 ) self.UI_meshMapping = MelButton( self, l=self.LBL_MESH_REMAP_BUTTON_NOMAP, c=self.on_meshMap ) self.UI_jointMapping = MelButton( self, l=self.LBL_JOINT_REMAP_BUTTON_NOMAP, c=self.on_jointMap ) self.UI_meshMapping.hide() self.UI_jointMapping.hide() #SectionLabel( mainLayout, 'restore options' ) #self.UI_restoreById = MelCheckBox( mainLayout, l="restore by id", v=0, cc=self.on_changeRestoreMode ) self.UI_restore = MelButton( self, l="restore from tmp file", c=self.on_restore ) self.on_changeRestoreMode() def getMeshRemapDict( self ): try: return self._UI_meshMap.getMapping().asFlatDict() except AttributeError: return None def getJointRemapDict( self ): try: return self._UI_jointMap.getMapping().asFlatDict() except AttributeError: return None ### MENU BUILDERS ### def build_popup( self, parent, *a ): cmd.setParent( parent, m=True ) cmd.menu( parent, e=True, dai=True ) thisFile = Path( cmd.file( q=True, sn=True ) ) #if the file doesn't exist, then use teh cwd if not thisFile.exists(): thisFile = thisFile.getcwd() / "tmp.ma" dir = thisFile.up() curFile = Path( cmd.textField( self.UI_file, q=True, tx=True ) ) for f in dir.files(): if f.hasExtension( skinWeights.EXTENSION ): cmd.menuItem( l=f.name(), cb=f==curFile, c=api.Callback( cmd.textField, self.UI_file, e=True, tx=f ) ) cmd.menuItem( d=True ) cmd.menuItem( l="browse", c=self.on_browseWeightFile ) cmd.menuItem( d=True ) cmd.menuItem( l="clear", c=lambda *a: cmd.textField( self.UI_file, e=True, tx='' ) ) if curFile.exists(): cmd.menuItem( d=True ) api.addExploreToMenuItems( curFile ) ### EVENT HANDLERS ### def on_changeRestoreMode( self, *a ): #if self.UI_restoreById.getValue(): #self.UI_average.disable() ##self.UI_doPreview.disable() #self.UI_ratio.disable() #self.UI_mirror.disable() #self.UI_meshMapping.enable() #self.UI_jointMapping.disable() #else: self.UI_average.enable() #self.UI_doPreview.enable() self.UI_ratio.enable() self.UI_mirror.enable() self.UI_meshMapping.disable() self.UI_jointMapping.enable() def on_meshMap( self, *a ): try: mapping = self._UI_meshMap.getMapping() self._UI_meshMap = MeshMappingEditor() self._UI_meshMap.editor.setMapping( mapping ) self._UI_meshMap.editor.ALLOW_MULTI_SELECTION = False except AttributeError: filepath = self.getFilepath() data = WeightSaveData( filepath.unpickle() ) meshes = list( data.getUsedMeshes() ) sceneMeshes = cmd.ls( typ='mesh' ) if sceneMeshes: sceneMeshes = cmd.listRelatives( sceneMeshes, p=True, pa=True ) mapping = names.Mapping( meshes, sceneMeshes, threshold=0.1 ) self._UI_meshMap = MeshMappingEditor() self._UI_meshMap.editor.setMapping( mapping ) self._UI_meshMap.editor.ALLOW_MULTI_SELECTION = False self.on_mappingUIStatus() def on_jointMap( self, *a ): try: mapping = self._UI_jointMap.getMapping() self._UI_jointMap = MeshMappingEditor() self._UI_jointMap.editor.setMapping( mapping ) self._UI_jointMap.editor.ALLOW_MULTI_SELECTION = False except AttributeError: filepath = self.getFilepath() data = WeightSaveData( filepath.unpickle() ) joints = list( data.getUsedJoints() ) sceneJoints = cmd.ls( typ='joint' ) mapping = names.Mapping( joints, sceneJoints, threshold=0.1 ) self._UI_jointMap = JointMappingEditor() self._UI_jointMap.editor.setMapping( mapping ) self._UI_jointMap.editor.ALLOW_MULTI_SELECTION = False self.on_mappingUIStatus() def on_browseWeightFile( self, *a ): startDir = getDefaultPath().up() filepath = cmd.fileDialog( directoryMask= startDir / "/*.weights" ) if filepath: cmd.textField( self.UI_file, e=True, tx=filepath ) def on_storeA( self, *a ): kw = {} if self.UI_file.getValue(): kw[ 'filepath' ] = Path( self.UI_file.getValue() ) skinWeights.saveWeights( cmd.ls( sl=True ), **kw ) def on_storeB( self, *a ): kw = {} if self.UI_file.getValue(): kw[ 'filepath' ] = Path( self.UI_file.getValue() ) joints = cmd.ls( type='joint', r=True ) jointMeshes = removeDupes( cmd.listRelatives( joints, ad=True, pa=True, type='mesh' ) ) skinWeights.saveWeights( jointMeshes, **kw ) def on_restore( self, *a ): filepath = None if self.UI_file.getValue(): filepath = Path( self.UI_file.getValue() ) skinWeights.loadWeights( cmd.ls( sl=True ), filepath, True, #not self.UI_restoreById.getValue(), self.UI_ratio.getValue(), (-1,) if self.UI_mirror.getValue() else None, averageVerts=self.UI_average.getValue(), doPreview=False, #self.UI_doPreview.getValue(), meshNameRemapDict=self.getMeshRemapDict(), jointNameRemapDict=self.getJointRemapDict() ) def on_mappingUIStatus( self, *a ): #do we have a mesh re-map? try: self._UI_meshMap self.UI_meshMapping( e=True, l=self.LBL_MESH_REMAP_BUTTON_HASMAP ) except AttributeError: self.UI_meshMapping( e=True, l=self.LBL_MESH_REMAP_BUTTON_NOMAP ) #do we have a joint re-map? try: self.UI_jointMapping( e=True, l=self.LBL_JOINT_REMAP_BUTTON_HASMAP ) except AttributeError: self.UI_jointMapping( e=True, l=self.LBL_JOINT_REMAP_BUTTON_NOMAP ) class SkinWeightsWindow(BaseMelWindow): WINDOW_NAME = 'weightSave' WINDOW_TITLE = 'weight save' DEFAULT_SIZE = 425, 375 DEFAULT_MENU = None HELP_MENU = WINDOW_NAME, 'hamish@valvesoftware.com', None FORCE_DEFAULT_SIZE = False def __init__( self ): BaseMelWindow.__init__( self ) scroll = MelScrollLayout( self ) col = MelColumnLayout( scroll, rs=5 ) SkinWeightsLayout( col ) Spacer( col ) SectionLabel( col, 'Skinning Control' ) SkinButtonsLayout( col ) Spacer( col ) SectionLabel( col, 'Weight Transfer' ) WeightsToOtherLayout( col ) Spacer( col ) SectionLabel( col, 'Transfer Skinning' ) def tmp( *a ): sel = cmd.ls( sl=True ) if len( sel ) > 1: src = sel.pop( 0 ) for tgt in sel: skinWeights.transferSkinning( src, tgt ) MelButton( col, l='Transfer From Source to Target', c=tmp ) self.show() self.layout() #end
Python
from baseRigPrimitive import * HandSkeletonCls = SkeletonPart.GetNamedSubclass( 'Hand' ) FINGER_IDX_NAMES = HandSkeletonCls.FINGER_IDX_NAMES or () class Hand(PrimaryRigPart): __version__ = 0 SKELETON_PRIM_ASSOC = ( HandSkeletonCls, ) CONTROL_NAMES = 'control', 'poses' NAMED_NODE_NAMES = ( 'qss', ) ADD_CONTROLS_TO_QSS = False def _build( self, skeletonPart, taper=0.8, **kw ): return self.doBuild( skeletonPart.bases, taper=taper, **kw ) def doBuild( self, bases, wrist=None, num=0, names=FINGER_IDX_NAMES, taper=0.8, **kw ): if wrist is None: wrist = getNodeParent( bases[ 0 ] ) scale = kw[ 'scale' ] idx = kw[ 'idx' ] parity = Parity( idx ) colour = ColourDesc( 'orange' ) suffix = parity.asName() #parityMult = parity.asMultiplier() parityMult = 1.0 # no parity flip on controls partParent, rootControl = getParentAndRootControl( bases[ 0 ] ) minSlider = -90 maxSlider = 90 minFingerRot = -45 #rotation at minimum slider value maxFingerRot = 90 #rotation at maxiumum slider value #get the bounds of the geo skinned to the hand and use it to determine default placement of the slider control bounds = getJointBounds( [ wrist ] + bases ) backwardAxis = getObjectAxisInDirection( wrist, Vector( (0, 0, -1) ) ) dist = bounds[ not backwardAxis.isNegative() ][ backwardAxis % 3 ] #build the main hand group, and the slider control for the fingers handSliders = buildControl( "hand_sliders"+ suffix, wrist, shapeDesc=ShapeDesc( None, 'pointer', backwardAxis ), constrain=False, colour=colour, offset=(0, 0, dist*1.25), scale=scale*1.25 ) poseCurve = buildControl( "hand_poses"+ suffix, handSliders, shapeDesc=ShapeDesc( None, 'starCircle', AX_Y ), oriented=False, constrain=False, colour=colour, parent=handSliders, scale=scale ) handQss = sets( empty=True, text="gCharacterSet", n="hand_ctrls"+ suffix ) handGrp = getNodeParent( handSliders ) poseCurveTrigger = Trigger( poseCurve ) setAttr( '%s.v' % poseCurve, False ) #constrain the group to the wrist parentConstraint( wrist, handGrp ) parent( handGrp, partParent ) attrState( (handSliders, poseCurve), ('t', 'r'), *LOCK_HIDE ) addAttr( poseCurve, ln='controlObject', at='message' ) #build the attribute so posesToSliders knows where to write the pose sliders to when poses are rebuilt connectAttr( '%s.message' % handSliders, '%s.controlObject' % poseCurve ) #now start building the controls allCtrls = [ handSliders, poseCurve ] allSpaces = [] allConstraints = [] baseControls = [] baseSpaces = [] slider_curl = [] slider_bend = [] for n, base in enumerate( bases ): #discover the list of joints under the current base name = names[ n ] if not num: num = 100 joints = [ base ] for i in range( num ): children = listRelatives( joints[ -1 ], type='joint' ) if not children: break joints.append( children[ 0 ] ) num = len( joints ) #build the controls ctrls = [] startColour = ColourDesc( (1, 0.3, 0, 0.65) ) endColour = ColourDesc( (0.8, 1, 0, 0.65) ) colour = startColour colourInc = (endColour - startColour) iColor = 1 if len( joints ) > 1: colourInc /= len( joints ) - 1 for i, j in enumerate( joints ): ctrlScale = ( scale / 3.5 ) * (taper ** i) c = buildControl( "%sControl_%d%s" % (name, i, suffix), j, shapeDesc=ShapeDesc( 'sphere', 'ring', axis=AIM_AXIS ), colour=colour, parent=handGrp, scale=ctrlScale, qss=handQss ) #setAttr( '%s.v' % c, False ) #hidden by default cParent = getNodeParent( c ) colours.setDrawOverrideColor( c, (23 + iColor) ) cmd.color( c, ud=iColor ) iColor += 1 if iColor > 8: iColor = 1 colour += colourInc if i: parent( cParent, ctrls[ -1 ] ) ctrls.append( c ) poseCurveTrigger.connect( getNodeParent( c ) ) allCtrls += ctrls ###------ ###CURL SLIDERS ###------ driverAttr = name +"Curl" addAttr( handSliders, ln=driverAttr, k=True, at='double', min=minSlider, max=maxSlider, dv=0 ) driverAttr = '%s.%s' % (handSliders, driverAttr) setAttr( driverAttr, keyable=True ) spaces = [ getNodeParent( c ) for c in ctrls ] for s in spaces: setDrivenKeyframe( '%s.r' % s, cd=driverAttr ) setAttr( driverAttr, maxSlider ) for s in spaces: rotate( 0, maxFingerRot * parityMult, 0, s, r=True, os=True ) setDrivenKeyframe( '%s.r' % s, cd=driverAttr ) setAttr( driverAttr, minSlider ) for s in spaces: rotate( 0, minFingerRot * parityMult, 0, s, r=True, os=True ) setDrivenKeyframe( '%s.r' % s, cd=driverAttr ) setAttr( driverAttr, 0 ) slider_curl.append( driverAttr ) ###------ ###BEND SLIDERS ###------ driverAttr = name +"Bend" addAttr( handSliders, ln=driverAttr, k=True, at='double', min=minSlider, max=maxSlider, dv=0 ) driverAttr = '%s.%s' % (handSliders, driverAttr) setAttr( driverAttr, keyable=True ) baseCtrlSpace = spaces[ 0 ] setDrivenKeyframe( '%s.r' % baseCtrlSpace, cd=driverAttr ) setAttr( driverAttr, maxSlider ) rotate( 0, maxFingerRot * parityMult, 0, baseCtrlSpace, r=True, os=True ) setDrivenKeyframe( '%s.r' % baseCtrlSpace, cd=driverAttr ) setAttr( driverAttr, minSlider ) rotate( 0, minFingerRot * parityMult, 0, baseCtrlSpace, r=True, os=True ) setDrivenKeyframe( '%s.r' % baseCtrlSpace, cd=driverAttr ) setAttr( driverAttr, 0 ) slider_bend.append( driverAttr ) ##reorder the finger sliders #attrOrder = [ attrpath.split( '.' )[1] for attrpath in slider_curl + slider_bend ] #reorderAttrs( handSliders, attrOrder ) #add toggle finger control vis handSlidersTrigger = Trigger( handSliders ) qssIdx = handSlidersTrigger.connect( handQss ) handSlidersTrigger.createMenu( 'Toggle Finger Controls', 'string $objs[] = `sets -q %%%d`;\nint $vis = !getAttr( $objs[0] +".v" );\nfor( $o in $objs ) setAttr( $o +".v", $vis );' % qssIdx ) return allCtrls, [handQss] #end
Python
import baseMelUI, visManager, api, skinCluster, presets, presetsUI import maya.cmds as cmd mel = api.mel melecho = api.melecho name = __name__ ui = None class VisManagerUI(baseMelUI.BaseMelWindow): WINDOW_NAME = "visManagerUI" WINDOW_TITLE = 'vis set manager' DEFAULT_SIZE = 254, 375 SPACER = " " EXPANDED = "[-] " COLLAPSED = "[+]" def __init__( self ): baseMelUI.BaseMelWindow.__init__( self ) mel.zooVisManUtils() mel.zooVisInitialSetup() api.mel.eval(r'''scriptJob -p %s -e "SceneOpened" "python(\"visManagerUI.ui.populate()\");";''' % self.WINDOW_NAME) self.UI_form = cmd.formLayout(docTag=0) self.UI_check_state = cmd.checkBox(v=self.state(), al="left", l="turn ON", cc=self.on_state_change) self.UI_button_marks = cmd.button(l="bookmarks") self.UI_tsl_sets = cmd.textScrollList(ams=1, dcc=self.on_collapse, nr=18, sc=self.on_select) self.POP_marks = cmd.popupMenu(p=self.UI_button_marks, b=1, aob=1, pmc=self.popup_marks) self.POP_marks_sh = cmd.popupMenu(p=self.UI_button_marks, sh=1, b=1, aob=1, pmc=self.popup_marks_add) self.POP_sets = cmd.popupMenu(p=self.UI_tsl_sets, b=3, pmc=self.popup_sets) self.reparentUI = None cmd.formLayout(self.UI_form, e=True, af=((self.UI_check_state, "top", 3), (self.UI_check_state, "left", 3), (self.UI_button_marks, "top", 0), (self.UI_button_marks, "right", 0), (self.UI_tsl_sets, "left", 0), (self.UI_tsl_sets, "bottom", 0)), ac=((self.UI_button_marks, "left", 5, self.UI_check_state), (self.UI_tsl_sets, "top", 0, self.UI_button_marks)), ap=((self.UI_tsl_sets, "right", 0, 100)) ) self.populate() self.show() def __del__( self ): if self.reparentUI is not None: if cmd.window(self.reparentUI, ex=True): cmd.deleteUI(self.reparentUI) def populate( self ): sets = mel.zooVisManListHeirarchically() cmd.textScrollList(self.UI_tsl_sets, e=True, ra=True) while True: try: vset = sets.pop(0) name = self.EXPANDED childSets = mel.zooSetRelatives(vset, 0, 0, 1) depth = len(mel.zooSetRelatives(vset, 0, 1, 1)) #count the number of parents to see how deep in the tree the set is if not childSets: name = self.SPACER if cmd.objExists("%s.isoCollapse" % vset): #if this set is collapsed we need to remove all its children from the list and change the name prefix name = self.COLLAPSED for toRemove in childSets: sets.remove(toRemove) name += self.SPACER * depth name += vset cmd.textScrollList(self.UI_tsl_sets, e=True, a=name) except IndexError: break self.updateSelection() def updateSelection( self ): ''' updates the tsl to reflect the sets that are currently active if any ''' cmd.textScrollList(self.UI_tsl_sets, e=True, da=True) displayNames = cmd.textScrollList(self.UI_tsl_sets, q=True, ai=True) activeISOs = mel.zooVisManGetActiveSets() toSelect = [] for iso in activeISOs: for name in displayNames: if name.rfind(iso) != -1: toSelect.append(name) break for item in toSelect: cmd.textScrollList(self.UI_tsl_sets, e=True, si=item) def selection( self ): selection = cmd.textScrollList(self.UI_tsl_sets, q=True, si=True) if not selection: return [] clean = [] for s in selection: idxName = s.rfind(' ') if idxName == -1: clean.append(s) else: clean.append(s[idxName+1:]) return clean def state( self ): return mel.zooVisManGetState() def on_state_change( self, *args ): mel.zooVisManSetVisState( cmd.checkBox(self.UI_check_state, q=True, v=True) ) def on_select( self, *args ): mel.zooVisManSetActiveSets( self.selection() ) def on_collapse( self, *args ): selSets = self.selection() state = not mel.zooVisManGetCollapseState(selSets[0]) for s in selSets: mel.zooVisManSetCollapseState(s, state) self.populate() def on_reparent( self, *args ): self.reparentUI = ParentChooserUI( self.selection() ) def on_new( self, *args ): parent = '' try: parent = self.selection()[0] except IndexError: pass ret = cmd.promptDialog(t="new isoSet", message="set name", b=("OK", "Cancel"), db="OK") text = cmd.promptDialog(q=True, tx=True) if ret != "OK": return if text == "": return newSet = mel.zooVisManCreateSet(parent, text, cmd.ls(sl=True)) cmd.select(cl=True) self.populate() def on_delete( self, *args ): for vset in self.selection(): if cmd.objExists(vset): mel.zooVisManDeleteSet(vset) self.populate() def on_add( self, *args ): mel.zooVisManAddToSet(self.selection(), cmd.ls(sl=True)) def on_remove( self, *args ): mel.zooVisManRemFromSet(self.selection(), cmd.ls(sl=True)) def on_set_select( self, *args ): mel.zooVisManSelectFrom(self.selection()) def on_joint_affected_faces( self, recursive=False ): ''' ''' faces = [] selJoints = cmd.ls(sl=True, type='joint') for j in selJoints: faces += skinCluster.jointFacesForMaya(j, 0.1) if recursive: for j in cmd.listRelatives(selJoints, ad=True, type='joint'): faces += skinCluster.jointFacesForMaya(j, 0.1) mel.zooVisManAddToSet(self.selection(), faces) def on_create_bookmark( self, *args ): ans = cmd.promptDialog(m='', t='', b=('OK', 'Cancel'), db='OK') if ans != 'OK': return markName = cmd.promptDialog(q=True, tx=True) mel.zooVisManCreateBookmark(markName, self.selection()) def on_activate_mark( self, markName, add ): mel.zooVisManActivateBookmark(markName, add) self.updateSelection() def on_eazel( self, *args ): curState = cmd.optionVar(q='zooVisManEazel') if cmd.optionVar(ex='zooVisManEazel') else True cmd.optionVar(iv=('zooVisManEazel', not curState)) def popup_marks( self, parent, *args, **kwargs ): cmd.setParent(parent, m=True) cmd.menu(parent, e=True, dai=True) add = kwargs.get('add', False ) marks = mel.zooVisManListBookmarks() for mark in marks: cmd.menuItem(l=mark, c=api.Callback(self.on_activate_mark, mark, add)) cmd.menuItem(d=1) cmd.menuItem(l='create bookmark', c=self.on_create_bookmark) def popup_marks_add( self, parent, *args ): self.popup_marks(parent, add=True) def popup_sets( self, parent, *args ): cmd.setParent(parent, m=True) cmd.menu(parent, e=True, dai=True) items = self.selection() addEazel = cmd.optionVar(q='zooVisManEazel') if cmd.optionVar(ex='zooVisManEazel') else True enable = bool(items) cmd.menuItem(en=enable, l="+ selection to vis set", c=self.on_add) cmd.menuItem(en=enable, l="- selection from vis set", c=self.on_remove) cmd.menuItem(en=enable, l="select items in vis set", c=self.on_set_select) cmd.menuItem(en=enable, l="parent to...", c=self.on_reparent) cmd.menuItem(d=True) cmd.menuItem(l="new vis set", c=self.on_new) cmd.menuItem(en=enable, l="remove vis set", c=self.on_delete) cmd.menuItem(d=True) cmd.menuItem(l="always show eazel", cb=addEazel, c=self.on_eazel) cmd.menuItem(d=True) cmd.menuItem(l="merge all sets (nasty hack)", c="mel.hackyMergeSets()") cmd.menuItem(l="add faces affected by joint", c=self.on_joint_affected_faces) cmd.menuItem(l="add faces affected by joint heirarchy", c=self.on_joint_affected_faces) cmd.menuItem(d=True) #build the preset list... visPresets = presets.listAllPresets(visManager.TOOL_NAME, visManager.EXTENSION, True) cmd.menuItem(l="build sets from preset", sm=True) for locale, pList in visPresets.iteritems(): for p in pList: cmd.menuItem(l=p.name(), c=api.Callback(self.import_preset, p.name(), locale, True, True)) cmd.setParent('..', m=True) cmd.menuItem(l="import preset volumes", sm=True) for locale, pList in visPresets.iteritems(): for p in pList: cmd.menuItem(l=p.name(), c=api.Callback(self.import_preset, p.name(), locale, False, False)) cmd.setParent('..', m=True) selected = cmd.ls(sl=True) cmd.menuItem(en=len(selected)==1, l="export volume preset", c=self.export_preset) cmd.menuItem(l="manage presets", c=lambda *x: presetsUI.load(visManager.TOOL_NAME, visManager.DEFAULT_LOCALE, visManager.EXTENSION)) cmd.menuItem(d=True) cmd.menuItem(l='create sphere volume', c=lambda *x: assets.createExportVolume(assets.ExportManager.kVOLUME_SPHERE)) cmd.menuItem(l='create cube volume', c=lambda *x: assets.createExportVolume(assets.ExportManager.kVOLUME_CUBE)) def import_preset( self, presetName, locale, createSets, deleteVolumes ): visManager.importPreset(presetName, locale, createSets, deleteVolumes) self.populate() def export_preset( self, *args ): ans, name = api.doPrompt(t="volume preset name", m="enter a name for the volume preset", db=api.OK) if ans != api.OK: return selected = cmd.ls(sl=True) visManager.exportPreset(name, selected[0]) #now delete the vis volumes cmd.delete(selected[0]) class ParentChooserUI(baseMelUI.BaseMelWindow): WINDOW_NAME = "visManagerParentChooser" WINDOW_TITLE = "vis set manager" NO_PARENT = '--no parent--' DEFAULT_SIZE = 180, 200 def __init__( self, setsToReparent ): baseMelUI.BaseMelWindow.__init__( self ) allSets = set( mel.zooVisManListHeirarchically() ) allSets.difference_update( set(setsToReparent) ) self.UI_form = cmd.formLayout() self.UI_tsl = cmd.textScrollList(ams=0, nr=18) self.UI_button_parent = cmd.button(l="parent") cmd.textScrollList(self.UI_tsl, e=True, dcc='%s.ui.reparentUI.on_done()' % name) cmd.button(self.UI_button_parent, e=True, c='%s.ui.reparentUI.on_done()' % name) # cmd.textScrollList(self.UI_tsl, e=True, a=self.NO_PARENT) for vset in allSets: cmd.textScrollList(self.UI_tsl, e=True, a=vset) cmd.formLayout(self.UI_form, e=True, af=((self.UI_tsl, "top", 0), (self.UI_tsl, "left", 0), (self.UI_tsl, "right", 0), (self.UI_button_parent, "left", 0), (self.UI_button_parent, "right", 0), (self.UI_button_parent, "bottom", 0)), ac=((self.UI_tsl, "bottom", 0, self.UI_button_parent)) ) #select the no parent option cmd.textScrollList(self.UI_tsl, e=True, si=self.NO_PARENT) self.show() def selection( self ): sel = cmd.textScrollList(self.UI_tsl, q=True, si=True) try: return sel[0] except IndexError: return self.NO_PARENT def on_done( self ): sel = self.selection() if sel == self.NO_PARENT: sel = '' mel.zooVisManSetParent(ui.selection(), sel) ui.populate() cmd.deleteUI(self.WINDOW_NAME) def load(): global ui ui = VisManagerUI() #end
Python
import maya.OpenMaya as om import maya.cmds as cmd from math import sqrt class BlendShape(): def __init__( self, nodeName ): self.name = nodeName self.__minRowLength = 5 def __repr__( self ): return self.targets def __str__( self ): return str(self.__repr__()) def __add__( self, value ): '''value should be a string or a list of strings (object names)''' if isinstance(value,str): self.append(value) elif isinstance(value,list) or isinstance(value,tuple): for val in value: self.__add__(val) else: raise ArithmeticError("only supports adding strings (name of a known target object) or lists/tuples of strings") return self def __sub__( self, value ): '''value should be a string or a list of strings (object names)''' if isinstance(value,str): self.pop(value) elif isinstance(value,list) or isinstance(value,tuple): for val in value: self.__add__(val) else: raise ArithmeticError("only supports subtracting strings (name of a known target object) or lists/tuples of strings") return self def __getattr__( self, attr ): if attr in self.targets: return cmd.getAttr(self.name +'.'+ attr) #else: # raise AttributeError("the %s target doesn't exist"%(attr,)) def __getitem__( self, idx ): return cmd.getAttr(self.name +'.w['+ idx +']') def append( self, shapeNameToAdd=None, name=None ): '''deals with adding a target of name shape to the blendshape''' if shapeNameToAdd == None: #in this case the user wants to append the current shape of the object being driven to the target list dupe = cmd.duplicate(self.obj)[0] shapeNameToAdd = dupe self.zeroTweak() if cmd.objExists(shapeNameToAdd): if name != None: shapeNameToAdd = cmd.rename(shapeNameToAdd,name) #make sure the name doesn't clash with an existing target name - otherwise maya will bork while shapeNameToAdd in self.targets: shapeNameToAdd += 'Dupe' numTgts = len(self.targets) cmd.blendShape(self.name,edit=True,target=(self.obj,numTgts,shapeNameToAdd,1.0)) self.collapse(shapeNameToAdd) self.zeroTweak() return shapeNameToAdd def expand( self, targetToExpand ): '''makes all the target shapes appear as objects in the scene - objects are placed to the right (assuming +z is facing forward and +y up) of the base object placed a bounding box width apart. row length is at least 5, but for large numbers of targets it takes the square root of the target count''' SEPARATION_X = 1.3 SEPARATION_Y = 1.3 expanded = self.expanded targets = self.targets num = len(expanded) if targetToExpand in targets: if self.isExpanded(targetToExpand): return self.getExpandedName(targetToExpand) obj = self.obj maxRowLength = max(self.__minRowLength,int(sqrt(len(targets)))) #get the size of the object so we can place them away from the original bbox = cmd.getAttr(obj +'.bbmn')[0] + cmd.getAttr(obj +'.bbmx')[0] size = ( (bbox[3]-bbox[0])*SEPARATION_X, (bbox[4]-bbox[1])*SEPARATION_Y ) x = num%maxRowLength + 1 y = int(num/maxRowLength) * -1 index = self.getTargetIdx(targetToExpand) self.setTargetWeight(targetToExpand,1,crossfade=True) dupe = cmd.duplicate(obj)[0] dupe = cmd.rename(dupe,targetToExpand) cmd.connectAttr(dupe +'.worldMesh[0]', self.name +'.inputTarget[0].inputTargetGroup['+ str(index) +'].inputTargetItem[6000].inputGeomTarget') #now move the objects away from the base so they're easier to visualize cmd.move(size[0]*x,size[1]*y,0,dupe,moveX=True,moveY=True,relative=True) return dupe else: raise AttributeError("target doesn't exist") def expandAll( self ): '''expands all targets - convenience really. this is horribly inefficient, but unless the target count grows into the multi thousands this shouldn't become a problem...''' initSelection = cmd.ls(selection=True) targets = self.targets weights = self.weights dupes = [] for target in targets: weight = cmd.getAttr(self.name +'.'+ target) dupes.append(self.expand(target)) self.setTargetWeight(target,weight,False) if initSelection: cmd.select(initSelection) return dupes def __getExpanded( self ): expanded = cmd.listConnections(self.name +'.it',destination=False) if expanded: return expanded else: return [] expanded = property(__getExpanded) def getExpandedName( self, target ): index = self.getTargetIdx(target) expanded = cmd.listConnections(self.name +'.it[0].inputTargetGroup['+ str(index) +'].inputTargetItem[6000].inputGeomTarget',destination=False) if expanded: return expanded[0] else: return [] def isExpanded( self, target=None ): '''returns whether a given target has been expanded or not. if no target is given this will return whether ANY target has been expanded''' cons = self.__getExpanded() if target: if self.getExpandedName(target) in cons: return True else: if cons: return True return False def collapse( self, targetToCollapse ): '''collapses the given target object so it's no longer visible in the scene''' if self.isExpanded(targetToCollapse): expandedName = self.getExpandedName(targetToCollapse) cmd.delete(expandedName) def collapseAll( self ): for target in self.targets: self.collapse(target) def pop( self, targetToRemove ): '''pops the given shape name or shape index out of the blendShape node - creating the object in the scene, and removing it from the blendShape node''' targets = self.targets indicies = self.indicies if targetToRemove in targets: blendIdx = self.getTargetIdx(targetToRemove) shape = self.expand(targetToRemove) cmd.blendShape(self.name,edit=True,remove=True,target=(self.obj,blendIdx,shape,1.0)) return shape else: raise AttributeError("target doesn't exist") def remove( self, targetToRemove ): cmd.delete(self.pop(targetToRemove)) def update( self, targetToUpdate ): '''overwrites the target name given with the current shape of self.name''' targets = self.targets if targetToUpdate in targets: nameIdx = targets.index(targetToUpdate) baseDupe = cmd.duplicate(self.obj)[0] self.zeroTweak() newTarget = self.expand(targetToUpdate) cmd.select((baseDupe,newTarget)) tmpBlendNode = cmd.blendShape()[0] cmd.setAttr(tmpBlendNode +'.w[0]',1) cmd.delete(newTarget,constructionHistory=True) cmd.delete(baseDupe) self.collapse(targetToUpdate) cmd.select(self.obj) else: raise AttributeError("target doesn't exist") def zeroTweak( self ): '''deals with zeroing out the tweak node values that have accumulated on a base mesh''' tweakNode = cmd.ls(cmd.listHistory(self.shape),type='tweak')[0] totalVertCount = cmd.getAttr(self.shape +'.vrts',size=True) for n in range(totalVertCount): cmd.setAttr(tweakNode +'.vlist[0].vt['+ str(n) +']',0,0,0) def __getTargetNameandIndicies( self ): '''returns a list of the target names on the blendshape. both the index list and the name list are guaranteed to be in the correct order''' indicies = [] aliasList = cmd.aliasAttr(self.name,query=True) if aliasList == None: return [] for n in range(1,len(aliasList),2): idx = int(aliasList[n][7:][:-1]) indicies.append(idx) indicies.sort() names = [None]*len(indicies) #build the name array of the correct size for n in range(0,len(aliasList),2): curNameIdx = int(aliasList[n+1][7:][:-1]) for i in range(len(indicies)): if curNameIdx == indicies[i]: names[i] = aliasList[n] return names,indicies def __getTargetNames( self ): '''returns a list of the target names on the blendshape''' names,indicies = self.__getTargetNameandIndicies() return names targets = property(__getTargetNames) def __getTargetWeights( self ): '''returns a list of the target names on the blendshape''' return cmd.getAttr(self.name +'.w')[0] weights = property(__getTargetWeights) def __getIndicies( self ): '''returns a list of the target names on the blendshape''' names,indicies = self.__getTargetNameandIndicies() return indicies indicies = property(__getIndicies) def getTargetIdx( self, target ): '''given a target name this method will return its index in the weight attribute''' indicies = [] aliasList = cmd.aliasAttr(self.name,query=True) if aliasList == None: raise Exception( "not aliasAttr found on %s"%(self.name,)) for n in range(0,len(aliasList),2): if aliasList[n] == target: idx = aliasList[n+1][7:][:-1] return int(idx) raise AttributeError("target doesn't exist") def __getObject( self ): return cmd.listRelatives(self.__getShape(),parent=True)[0] obj = property(__getObject) def __getShape( self ): return cmd.ls(cmd.listHistory(self.name +'.outputGeometry',future=True),type='mesh')[0] shape = property(__getShape) def rename( self, oldName, newName ): '''will rename a blend shape target - if the target doesn't exist, the method does nothing...''' names = self.targets aliasList = cmd.aliasAttr(self.name,query=True) if oldName in names: idx = aliasList.index(oldName) aliasList[idx] = newName for n in range(1,len(aliasList),2): aliasList[n] = self.name +'.'+ aliasList[n] #now remove all the alias' for name in names: cmd.aliasAttr(self.name +'.'+ name,remove=True) #finally rebuild the alias' cmdStr = 'aliasAttr ' + ' '.join(aliasList) +';' maya.mel.eval(cmdStr) def setTargetWeight( self, target, weight, additive=False, crossfade=False ): inititalWeight = cmd.getAttr(self.name +'.'+ target) if target in self.targets: #print 'data:',target,weight,additive,crossfade cmd.setAttr(self.name +'.'+ target,weight) if crossfade: pct = abs(1-weight) / 1 idx = self.targets.index(target) others = self.targets[:] others.pop(idx) for other in others: otherWeight = abs(cmd.getAttr(self.name +'.'+ other)) cmd.setAttr(self.name +'.'+ other,min(0,otherWeight*pct)) else: raise AttributeError("target doesn't exist") def setAllWeights( self, weight=0 ): targets = self.targets for index in self.indicies: self.setTargetWeight(targets[index],weight,False) def propagateTweaks( self ): '''propagates the data currently in the tweak node to all target objects - this is useful when large changes to a basemesh need to be made across all targets. NOTE: this is only possible if targets are expanded...''' tweakNode = cmd.ls(cmd.listHistory(self.shape),type='tweak')[0] self.collapseAll() self.expandAll() self.zeroTweak() self.collapseAll() #need to connect the tweak node up to targets... def deleteHistory( self ): '''does a collapse history without destroying blendshape data - this essentially allows you do change topology on a blendshape setup easily''' self.collapseAll() #make sure everything is collapsed newTargets = self.expandAll() #do an expand to ensure all the targets have the same topology as the base mesh #now we just need to delete the history and rebuild the blendshape setup obj = self.obj cmd.delete(obj,constructionHistory=True) newTargets += [obj] self.name = cmd.blendShape(newTargets)[0] self.collapseAll() def setWeightApi( self, target, weight ): '''this only exists because its not undoable - which strangely enough is useful - see vBlendShapeManager.mel->doSlideCmd() for details''' sTmp = om.MSelectionList() sTmp.add(self.name) idx = self.getTargetIdx(target) blendShapeObj = om.MObject() sTmp.getDependNode(0,blendShapeObj) blendFn = om.MFnDependencyNode(blendShapeObj) weightPG = om.MPlug(blendFn.findPlug("w")) targetPG = om.MPlug(weightPG.elementByPhysicalIndex(idx)) targetPG.setFloat(weight) class BlendShapePV(BlendShape): def __init__( self, nodeName ): BlendShape.__init__(self,nodeName) cmd.loadPlugin('blendTools',quiet=True) self.falloffWeights = [] def setAllSliders( self, weight ): for target in self.targets: BlendShape.setTargetWeight( self, target, weight ) def setTargetWeight( self, target, weight, additive=False, crossfade=False, falloff=0, selection=None ): '''deals with setting the weight map for a named shape''' targets = self.targets indicies = self.indicies if target in targets: idx = self.getTargetIdx(target) #determine the default selection to use if selection == None: sel = cmd.ls(selection=True) if sel: selection = cmd.polyListComponentConversion(sel,toVertex=True) else: selection = self.obj +'.vtx[*]' if selection == '*': selection = self.obj +'.vtx[*]' #print 'data:',target,weight,falloff,additive,crossfade,selection #cmd.blendPerVert(selection,node=self.name,target=idx,weight=weight,falloff=falloff,additive=additive,crossfade=crossfade) cmd.applyFalloffArray(n=self.name,t=tgtIdx,w=weight,add=additive,x=crossfade,undo=True,l=self.falloffWeights) else: raise AttributeError("target doesn't exist") def setAllWeights( self, weight=0 ): targets = self.targets for target in targets: self.setTargetWeight(target,weight) def generateFalloffList( self, falloff ): maya.mel.eval('$g_vertFallOffWeights = `getFalloffArray -f %f`;'%falloff) #self.falloffWeights = cmd.getFalloffArray(f=falloff) def setWeightApi( self, target, weight, additive=False, crossfade=False ): '''uses the current falloff weight list''' if not self.falloffWeights: return #if no falloff weight map has been generated, bail tgtIdx = self.targets.index(target) #cmd.applyFalloffArray(node=self.name,target=tgtIdx,w=weight,add=additive,x=crossfade,l=self.falloffWeights) addStr,xStr = '','' if additive: addStr = '-add' if crossfade: xStr = '-x' maya.mel.eval('applyFalloffArray -n %s -t %d -w %f %s %s -l $g_vertFallOffWeights;')%( self.name,tgtIdx,weight,addStr,xStr) def getBlendFromObject( object ): blendNodes = cmd.ls(cmd.listHistory(object),type='blendShape') if blendNodes != None: return blendNodes[0] def clamp( value, min=0, max=1): if value<min: return min if value>max: return max return value #end
Python
''' these are the optional args and their default values for the keyed rig primitive build functions ''' PRIM_OPTIONS = { 'zooBuildControl': {}, 'zooCSTBuildPrimBasicSpine': {}, #'parents': tuple(), #'hips': '', #'scale': 1.0, #'spaceswitching': True, #'colour': 'lightblue 0.65', #'buildhips': True }, 'zooCSTBuildPrimHead': {}, #'parents': tuple(), #'headType': 'skingeometry', #'neckType': 'pin', #'colour': 'blue 0.92' #'scale': 1.0, #'orient': True, #'spaceswitching': True, #'pickwalking': True, #'buildNeck': True, #'neckCount': True }, 'zooCSTBuildPrimArm': {}, #'parents': tuple(), #'scale': 1.0, #'buildclav': True, #'spaceswitching': True, #'pickwalking': True, #'allPurpose': True, #'stretch': False }, 'zooCSTBuildPrimLeg': { #'parents': tuple(), #'ikType': 'skingeometry', #'allPurpose': True, #'scale': 1.0, #'spaceswitching': True, #'pickwalking': True, 'stretch': False }, 'zooCSTBuildPrimHand': { 'names': ("index", "mid", "ring", "pinky", "thumb"), #'axes': ("#", "#", "#", "#", "#"), #'colour': 'orange 0.65', #'maxSlider': 90, #'minSlider': -90, #'maxFingerRot': 90, #'minFingerRot': -90, #'scale': 1.0, 'taper': 1.0, #'pickwalking': True, 'num': 0, #'invert': True, 'sliders': True, 'triggers': True, 'stretch': False } } #end
Python
import os import sys import cgitb import inspect import traceback from filesystem import findMostRecentDefitionOf def printMsg( *args ): for a in args: print a, def SHOW_IN_UI(): from wx import MessageBox, ICON_ERROR MessageBox( 'Sorry, it seems an un-expected problem occurred.\nYour error has been reported. Good Luck!', 'An Unhandled Exception Occurred', ICON_ERROR ) DEFAULT_AUTHOR = 'mel@macaronikazoo.com' def exceptionHandler( *args ): ''' This is a generic exception handler that can replace the default python exception handler if needed (ie: sys.excepthook=exceptionHandler). It will mail ''' try: eType, e, tb = args except TypeError: eType, e, tb = sys.exc_info() printMsg( '### ERROR - Python Unhandled Exception' ) printMsg( '### ', eType.__name__, e ) # toolName = findMostRecentDefitionOf( 'TOOL_NAME' ) or '<NO_TOOL>' #generate the message env = os.environ message = 'Subject: [ERROR] %s\n\n%s\n\n%s\n\n%s' % (toolName, cgitb.text( args ), '\n'.join( sys.path ),'\n'.join( [ '%s=%s' % (k, env[ k ]) for k in sorted( env.keys() ) ] )) #try to write a log fLog = open( 'c:/python_tool_log_%s.txt' % toolName, 'w' ) try: fLog.write( message ) except: pass finally: fLog.close() #try to mail a callstack try: import smtplib author = findMostRecentDefitionOf( '__author__' ) or DEFAULT_AUTHOR svr = smtplib.SMTP( 'exchange2' ) svr.sendmail(os.environ[ 'USERNAME' ], [author, os.environ[ 'USERNAME' ]], message) except Exception, x: printMsg( 'ERROR: failed to mail exception dump', x ) #try to post an error dial try: SHOW_IN_UI() except: pass def d_handleExceptions(f): ''' if you can't/don't want to setup a generic exception handler, you can decorate a function with this to have exceptions handled exception hanlding decorator. basically this decorator will catch any exceptions thrown by the decorated function, and spew a useful callstack to the event log - as well as throwing up a dial to alert of the issue... ''' def newFunc( *a, **kw ): try: return f( *a, **kw ) except: exc_info = sys.exc_info() exceptionHandler( *exc_info ) newFunc.__name__ = f.__name__ newFunc.__doc__ = f.__doc__ return newFunc class ExceptionHandledType(type): ''' metaclass that will wrap all callable attributes of a class with the d_handleExceptions exception handler decorator above. this is mainly useful for maya/modo, because neither app lets you specify your own global exception handler - yet you want to be able to capture this exception data and turn it into a meaningful error description that can be sent back to the tool author ''' def __new__( cls, name, bases, attrs ): global d_handleExceptions newAttrs = {} for itemName, item in attrs.iteritems(): if callable( item ): newAttrs[ itemName ] = d_handleExceptions( item ) else: newAttrs[ itemName ] = item return type.__new__( cls, name, bases, newAttrs ) def generateTraceableStrFactory( prefix, printFunc=None ): ''' returns 2 functions - the first will generate a traceable message string, while the second will print the generated message string. The second is really a convenience function, but is called enough to be worth it you can also specify your own print function - if no print function is specified then the print builtin is used ''' def generateTraceableStr( *args, **kw ): frameInfos = inspect.getouterframes( inspect.currentframe() ) _nFrame = kw.get( '_nFrame', 1 ) #frameInfos[0] contains the current frame and associated calling data, while frameInfos[1] is the frame that called this one - which is the frame we want to print data about callingFrame, callingScript, callingLine, callingName, _a, _b = frameInfos[_nFrame] lineStr = 'from line %s in the function %s in the script %s' % (callingLine, callingName, callingScript) return '%s%s: %s' % (prefix, ' '.join( map( str, args ) ), lineStr) def printTraceableStr( *args ): msg = generateTraceableStr( _nFrame=2, *args ) if printFunc is None: print( msg ) else: printFunc( msg ) return generateTraceableStr, printTraceableStr generateInfoStr, printInfoStr = generateTraceableStrFactory( '*** INFO ***: ' ) generateWarningStr, printWarningStr = generateTraceableStrFactory( '*** WARNING ***: ' ) generateErrorStr, printErrorStr = generateTraceableStrFactory( '*** ERROR ***: ' ) #end
Python
from baseRigPrimitive import * class Head(PrimaryRigPart): __version__ = 0 SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Head' ), ) CONTROL_NAMES = 'control', 'gimbal', 'neck' def _build( self, skeletonPart, translateControls=False, **kw ): return self.doBuild( skeletonPart.head, translateControls=translateControls, **kw ) def doBuild( self, head, neckCount=1, translateControls=False, **kw ): scale = self.scale partParent, rootControl = getParentAndRootControl( head ) colour = ColourDesc( 'blue' ) lightBlue = ColourDesc( 'lightblue' ) #build the head controls - we always need them headControl = buildControl( "headControl", head, shapeDesc=Shape_Skin( [head] + (listRelatives( head, ad=True, type='joint' ) or []) ), colour=colour, scale=scale ) headControlSpace = getNodeParent( headControl ) headGimbal = buildControl( "head_gimbalControl", head, shapeDesc=ShapeDesc( None, 'starCircle' ), colour=colour, oriented=False, scale=scale, autoScale=True, parent=headControl, niceName='Head' ) #now find the neck joints neckJoints = [] curParent = head for n in range( neckCount ): curParent = getNodeParent( curParent ) neckJoints.append( curParent ) neckJoints.reverse() #determine an offset amount for the neck controls based on the geometry skinned to the necks and head joint neckOffset = AX_Z.asVector() * getAutoOffsetAmount( head, neckJoints ) #build the controls for them neckControls = [] theParent = partParent for n, j in enumerate( neckJoints ): c = buildControl( 'neck_%d_Control' % n, j, PivotModeDesc.BASE, ShapeDesc( 'pin', axis=AX_Z ), colour=lightBlue, scale=scale*1.5, offset=neckOffset, parent=theParent, niceName='Neck %d' % n ) if not translateControls: attrState( c, 't', *LOCK_HIDE ) theParent = c neckControls.append( c ) if neckCount == 1: neckControls[ 0 ] = rename( neckControls[ 0 ], 'neckControl' ) setNiceName( neckControls[ 0 ], 'Neck' ) elif neckCount >= 2: setNiceName( neckControls[ 0 ], 'Neck Base' ) setNiceName( neckControls[ -1 ], 'Neck End' ) if neckCount: parent( headControlSpace, neckControls[ -1 ] ) else: parent( headControlSpace, partParent ) #build space switching if neckControls: spaceSwitching.build( headControl, (neckControls[ 0 ], partParent, rootControl, self.getWorldControl()), space=headControlSpace, **spaceSwitching.NO_TRANSLATION ) for c in neckControls: spaceSwitching.build( c, (partParent, rootControl, self.getWorldControl()), **spaceSwitching.NO_TRANSLATION ) #add right click menu to turn on the gimbal control gimbalIdx = Trigger( headControl ).connect( headGimbal ) Trigger.CreateMenu( headControl, "toggle gimbal control", "string $shapes[] = `listRelatives -f -s %%%d`;\nint $vis = `getAttr ( $shapes[0] +\".v\" )`;\nfor( $s in $shapes ) setAttr ( $s +\".v\" ) (!$vis);" % gimbalIdx ) #turn unwanted transforms off, so that they are locked, and no longer keyable, and set rotation orders gimbalShapes = listRelatives( headGimbal, s=True ) for s in gimbalShapes: setAttr( '%s.v' % s, 0 ) setAttr( '%s.ro' % headControl, 3 ) setAttr( '%s.ro' % headGimbal, 3 ) if not translateControls: attrState( (headControl, headGimbal), 't', *LOCK_HIDE ) controls = [ headControl, headGimbal ] + neckControls return controls, () #end
Python
from maya.cmds import * from maya import cmds as cmd from baseMelUI import * import names import control import baseMelUI import spaceSwitching class ParentsScrollList(MelObjectScrollList): def itemAsStr( self, item ): return '%s :: %s' % tuple( item ) class SpaceSwitchingLayout(MelVSingleStretchLayout): def __init__( self, parent, *a, **kw ): MelVSingleStretchLayout.__init__( self, parent, expand=True, *a, **kw ) w = 130 hLayout = MelHSingleStretchLayout( self ) self.UI_controlBtn = UI_controlBtn = MelButton( hLayout, l='obj to space switch ->', w=w, c=self.on_loadControl ) self.UI_control = UI_control = MelNameField( hLayout ) hLayout.setStretchWidget( UI_control ) hLayout.layout() hLayout = MelHSingleStretchLayout( self ) self.UI_spaceBtn = UI_spaceBtn = MelButton( hLayout, l='obj to constrain ->', w=w, c=self.on_loadSpace ) self.UI_space = UI_space = MelNameField( hLayout ) hLayout.setStretchWidget( UI_space ) hLayout.layout() hLayout = MelHLayout( self ) self.UI_constrainT = UI_constrainT = MelCheckBox( hLayout, l='constrain translation', v=True, cc=self.on_constrainChange ) self.UI_constrainR = UI_constrainR = MelCheckBox( hLayout, l='constrain rotation', v=True, cc=self.on_constrainChange ) self.UI_constraintType = UI_constraintType = MelOptionMenu( hLayout ) hLayout.layout() #populate the option menu with the constraint types for constraintType in spaceSwitching.CONSTRAINT_TYPES: UI_constraintType.append( constraintType ) ### PARENTS LIST ### self.UI_parentsLbl = UI_parentsLbl = MelLabel( self, l='Parents (double click to rename)', align='center' ) hLayout = MelHSingleStretchLayout( self, expand=True ) self.UI_parents = UI_parents = ParentsScrollList( hLayout, dcc=self.on_renameParent ) upDnLayout = MelVLayout( hLayout ) self.UI_up = UI_up = MelButton( upDnLayout, l='up', c=self.on_up ) self.UI_dn = UI_dn = MelButton( upDnLayout, l='dn', c=self.on_dn ) upDnLayout.layout() hLayout.setStretchWidget( UI_parents ) hLayout.layout() self.setStretchWidget( hLayout ) ### ADD/REMOVE PARENTS BUTTONS ### hLayout = MelHLayout( self ) self.UI_addParent = UI_addParent = MelButton( hLayout, l='add parent', c=self.on_addParent ) self.UI_remParent = UI_remParent = MelButton( hLayout, l='remove parent', c=self.on_removeParent ) self.UI_removeAll = UI_removeAll = MelButton( hLayout, l='remove all', c=self.on_removeAll ) hLayout.layout() self.UI_build = UI_build = MelButton( self, l='build space switch', c=self.on_build ) ### DO FINAL LAYOUT ### self.layout() self.setSceneChangeCB( self.on_sceneChange ) self.update() def update( self ): setEnabled = bool( self.getControl() and self.getSpace() ) self.UI_addParent.enable( setEnabled ) self.UI_remParent.enable( setEnabled ) self.UI_removeAll.enable( setEnabled ) self.UI_build.enable( setEnabled ) if not self.UI_constrainT.getValue() and not self.UI_constrainR.getValue(): self.UI_build.enable( False ) if not self.UI_parents.getItems(): self.UI_build.enable( False ) def setControl( self, control ): self.UI_space.clear() self.UI_control.setObj( control ) self.UI_parents.clear() self.update() def getControl( self ): return self.UI_control.getObj() def setSpace( self, space ): self.UI_space.setObj( space ) self.update() def getSpace( self ): return self.UI_space.getObj() def addParent( self, parent, name=None ): #sanity check - make sure the parent isn't either the control, the space, already in the list or a child of either the control or space if parent == self.getControl(): return elif parent == self.getSpace(): return if name is None: name = spaceSwitching.getSpaceName( self.getControl(), parent ) if name is None: name = names.camelCaseToNice( str( parent ) ) self.UI_parents.append( [parent, name] ) ### EVENT HANDLERS ### def on_loadControl( self, *a ): selected = ls( sl=True ) if selected: theControl = selected[ 0 ] self.setControl( theControl ) space = spaceSwitching.findSpace( theControl ) #if there is an existing space for the control, use it - otherwise try to guess one if space: self.setSpace( space ) else: space = listRelatives( theControl, p=True, pa=True ) if space: self.setSpace( space[0] ) parents, names = spaceSwitching.getSpaceTargetsNames( theControl ) for parent, name in zip( parents, names ): self.addParent( parent, name ) self.update() def on_loadSpace( self, *a ): selected = ls( sl=True ) if selected: theSpace = selected[ 0 ] self.setSpace( theSpace ) self.update() def on_constrainChange( self, *a ): self.update() def on_addParent( self, *a ): selected = ls( sl=True ) for item in selected: self.addParent( item ) self.update() def on_removeParent( self, *a ): self.UI_parents.removeSelectedItems() self.update() def on_removeAll( self, *a ): self.UI_parents.clear() self.update() def on_renameParent( self, *a ): selItems = self.UI_parents.getSelectedItems() if selItems: theItem = selItems[ 0 ] ret = cmd.promptDialog( t='Enter a name', m='Enter the name you want the parent to appear as', tx=theItem[1], b=('OK', 'Cancel'), db='OK' ) if ret == 'OK': theItem[ 1 ] = cmd.promptDialog( q=True, tx=True ) self.UI_parents.update() def on_up( self, *a ): self.UI_parents.moveSelectedItemsUp() def on_dn( self, *a ): self.UI_parents.moveSelectedItemsDown() def on_sceneChange( self, *a ): self.UI_control.clear() self.UI_space.clear() self.UI_parents.clear() self.update() def on_build( self, *a ): theControl = self.getControl() theSpace = self.getSpace() for parent, name in self.UI_parents.getItems(): spaceSwitching.add( theControl, parent, name=name, space=theSpace, skipTranslationAxes=() if self.UI_constrainT.getValue() else ('x', 'y', 'z'), skipRotationAxes=() if self.UI_constrainR.getValue() else ('x', 'y', 'z'), constraintType=self.UI_constraintType.getValue() ) #spaceSwitching.build( self.getControl(), parents, names=parentNames, space=self.getSpace() ) class SpaceSwitchingWindow(BaseMelWindow): WINDOW_NAME = 'spaceSwitchingWindow' WINDOW_TITLE = 'Space Switching' DEFAULT_SIZE = 400, 350 DEFAULT_MENU = None #HELP_MENU = 'spaceSwitching', 'hamish@macaronikazoo.com', None FORCE_DEFAULT_SIZE = True def __init__( self ): self.editor = SpaceSwitchingLayout( self ) self.show() #end
Python
from baseRigPrimitive import * class Root(PrimaryRigPart): __version__ = 0 SKELETON_PRIM_ASSOC = ( skeletonBuilder.Root, ) CONTROL_NAMES = 'control', 'gimbal', 'hips' def _build( self, skeletonPart, buildHips=True, **kw ): root = skeletonPart.base #deal with colours colour = ColourDesc( 'blue' ) darkColour = colour.darken( 0.5 ) lightColour = colour.lighten( 0.5 ) #hook up the scale from the main control connectAttr( '%s.scale' % self.getWorldControl(), '%s.scale' % root ) partParent, altRootControl = getParentAndRootControl( root ) #try to determine a sensible size for the root control - basically grab teh autosize of the root joint, and take the x-z plane values size = control.getJointSize( [root], 0.5, SPACE_WORLD ) ringSize = Vector( (size[0], size[0] + size[2] / 3.0, size[2]) ) #create the controls, and parent them rootControl = buildControl( 'upperBodyControl', (root, PlaceDesc.WORLD), shapeDesc=ShapeDesc( 'band', axis=AX_Y ), colour=colour, constrain=False, size=size, parent=partParent ) rootGimbal = buildControl( 'gimbalControl', (root, PlaceDesc.WORLD), shapeDesc=ShapeDesc( 'ring', axis=AX_Y ), colour=darkColour, oriented=False, offset=(0, size.y/2, 0), size=ringSize, parent=rootControl, niceName='Upper Body Control' ) hipsControl = buildControl( 'hipsControl', (root, PlaceDesc.WORLD), shapeDesc=ShapeDesc( 'ring', axis=AX_Y ), colour=lightColour, constrain=False, oriented=False, offset=(0, -size.y/2, 0), size=ringSize, parent=rootGimbal ) rootSpace = listRelatives( rootControl, p=True, pa=True ) #delete the connections to rotation so we can put an orient constraint on the root joint to teh hips control for ax in AXES: delete( '%s.r%s' % (root, ax), icn=True ) orientConstraint( hipsControl, root, mo=True ) attrState( hipsControl, 't', *LOCK_HIDE ) #turn unwanted transforms off, so that they are locked, and no longer keyable attrState( (rootGimbal, hipsControl), 't', *LOCK_HIDE ) for s in listRelatives( rootGimbal, s=True, pa=True ): setAttr( '%s.visibility' % s, False ) xform( rootControl, p=1, roo='xzy' ) xform( rootGimbal, p=1, roo='zxy' ) #add right click menu to turn on the gimbal control Trigger.CreateMenu( rootControl, "toggle gimbal control", "{\nstring $kids[] = `listRelatives -pa -type transform #`;\n$kids = `listRelatives -s $kids[0]`;\nint $vis = `getAttr ( $kids[0] +\".v\" )`;\nfor( $k in $kids ) setAttr ( $k +\".v\" ) (!$vis);\n}" ) Trigger.CreateMenu( rootGimbal, "toggle gimbal control", "{\nstring $kids[] = `listRelatives -pa -s #`;\nint $vis = `getAttr ( $kids[0] +\".v\" )`;\nfor( $k in $kids ) setAttr ( $k +\".v\" ) (!$vis);\nselect `listRelatives -p`;\n}" ) controls = rootControl, rootGimbal, hipsControl return controls, () def setupMirroring( self ): for control in self: pair = poseSym.ControlPair.Create( control ) pair.setFlips( 0 ) #end
Python
from baseSkeletonPreset import * #end
Python
from baseRigPrimitive import * from spaceSwitching import build, NO_TRANSLATION, NO_ROTATION class SplineIK(PrimaryRigPart): __version__ = 2 SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'ArbitraryChain' ), ) PRIORITY = 11 @classmethod def CanRigThisPart( cls, skeletonPart ): return len( skeletonPart ) >= 3 def _build( self, skeletonPart, allowFixedLength=True, constrainBetween=True, **kw ): objs = skeletonPart.items parentControl, rootControl = getParentAndRootControl( objs[0] ) fittedCurve, linearCurve, proxies, fixedLengthProxies, controls, splineIkHandle, halfIdx = buildControls( objs, parentControl, allowFixedLength=allowFixedLength, constrainBetween=constrainBetween, **kw ) buildDefaultSpaceSwitching( objs[0], controls[0] ) buildDefaultSpaceSwitching( objs[0], controls[-1] ) setAttr( '%s.v' % fixedLengthProxies[0], False ) #group all the proxy joints together miscGrp = asMObject( group( em=True ) ) rename( miscGrp, '%s_%d_miscGrp%s#' % (type( self ).__name__, self.getIdx(), self.getSuffix()) ) parent( proxies, miscGrp ) parent( fixedLengthProxies[0], miscGrp ) parent( fittedCurve, linearCurve, miscGrp ) parent( miscGrp, self.getPartsNode() ) parent( splineIkHandle, miscGrp ) return controls def buildControls( objs, controlParent=None, name='control', midName='midControl', allowFixedLength=True, constrainBetween=True, constrainBetweenMid=True, **kw ): numObjs = numControls = len( objs ) if numObjs < 3: raise RigPartError( "Need to specify more than 3 objects to use spline IK" ) scale = kw.get( 'scale', 15 ) fittedCurve, linearCurve, proxies = buildCurveThroughObjs( objs, False ) fittedCurveShape = listRelatives( fittedCurve, s=True, pa=True )[0] #hide the curves and lock them down setAttr( '%s.v' % fittedCurve, False ) setAttr( '%s.v' % linearCurve, False ) attrState( (fittedCurve, linearCurve), ('t', 'r', 's'), *LOCK_HIDE ) #hook up a curve info node curveMeasure = createNode( 'curveInfo' ) curveMeasure = rename( curveMeasure, 'curve_measure#' ) connectAttr( '%s.worldSpace[0]' % fittedCurveShape, '%s.inputCurve' % curveMeasure, f=True ) knots = getAttr( '%s.knots' % curveMeasure )[ 0 ][ 2:-2 ] #figure out which control should be the "mid" control halfWayKnotValue = knots[-1] / 2 halfIdx = numObjs / 2 for idx, knot in enumerate( knots ): if knot < halfWayKnotValue: halfIdx = idx else: #is this value closer to the mid knot value? if so use it deltas = [ (abs( knots[ halfIdx ] - halfWayKnotValue ), halfIdx), (abs( knots[ idx ] - halfWayKnotValue ), idx) ] deltas.sort() halfIdx = deltas[0][1] break #now build the controls controls = [] name, midName = '%s_%%d' % name, '%s_%%d' % midName for n, obj in enumerate( objs ): isHalfCtrl = n == halfIdx ctrlName = midName % n if isHalfCtrl else name % n ctrlScale = scale*1.3 if n in (isHalfCtrl, 0, numControls-1) else scale ctrlColour = ColourDesc( 'darkblue' ) if isHalfCtrl else ColourDesc( 'blue' ) nControl = buildControl( ctrlName, obj, PivotModeDesc.MID, 'sphere2', ctrlColour, constrain=False, parent=controlParent, scale=ctrlScale, asJoint=True ) #need to be joints to use for skinning below control.setItemRigControl( obj, nControl ) controls.append( nControl ) halfWayControl = controls[ halfIdx ] #setup the middle controls to be constrained between all controls if constrainBetween: constraintMethod = pointConstraint if numObjs >= 5 and constrainBetweenMid: lengths = [ betweenVector( controls[0], c ).get_magnitude() for c in controls[ 1:halfIdx+1 ] ] lengthSum = sum( lengths ) midControlsA = controls[ 1:halfIdx ] for length, ctrl in zip( lengths, midControlsA ): ctrlParent = listRelatives( ctrl, p=True, pa=True )[0] baseWeight = length / lengthSum constraintMethod( controls[0], ctrlParent, w=1-baseWeight, mo=True ) constraintMethod( halfWayControl, ctrlParent, w=baseWeight, mo=True ) lengths = [ betweenVector( controls[0], c ).get_magnitude() for c in controls[ halfIdx:-1 ] ] lengthSum = sum( lengths ) midControlsB = controls[ halfIdx + 1:-1 ] for length, ctrl in zip( lengths, midControlsB ): ctrlParent = listRelatives( ctrl, p=True, pa=True )[0] baseWeight = length / lengthSum constraintMethod( halfWayControl, ctrlParent, w=1-baseWeight, mo=True ) constraintMethod( controls[-1], ctrlParent, w=baseWeight, mo=True ) ctrlParent = listRelatives( halfWayControl, p=True, pa=True )[0] baseWeight = halfWayKnotValue / float( knots[-1] ) constraintMethod( controls[0], ctrlParent, w=1-baseWeight, mo=True ) constraintMethod( controls[-1], ctrlParent, w=baseWeight, mo=True ) else: lengths = [ betweenVector( controls[0], c ).get_magnitude() for c in controls[ 1: ] ] lengthSum = sum( lengths ) midControls = controls[ 1:-1 ] for length, ctrl in zip( lengths, midControls ): ctrlParent = listRelatives( ctrl, p=True, pa=True )[0] baseWeight = length / lengthSum constraintMethod( controls[0], ctrlParent, w=1-baseWeight, mo=True ) constraintMethod( controls[-1], ctrlParent, w=baseWeight, mo=True ) for knot, j, proxy in zip( knots, objs, proxies ): pointConstraint( proxy, j, mo=True ) mpath = createNode( 'pointOnCurveInfo' ) #connect axes individually so they can be broken easily if we need to... connectAttr( '%s.worldSpace' % fittedCurveShape, '%s.inputCurve' % mpath ) for ax in AXES: connectAttr( '%s.p%s' % (mpath, ax), '%s.t%s' % (proxy, ax) ) #were using (knot / unitComp) but it seems this is buggy - invalid knot values are returned for a straight curve... so it seems assuming knot is valid works in all test cases I've tried... setAttr( '%s.parameter' % mpath, knot ) #setup aim constraints to control twisting and orientation along the spline for n in range( numObjs - 1 ): obj, nextObj = objs[n], proxies[n + 1] v = betweenVector( obj, nextObj ) #now get all the axis information to build an aim constraint aimAxis = getObjectAxisInDirection( obj, v ) otherAxes = aimAxis.otherAxes() upAxis = otherAxes[0] upVector = getObjectBasisVectors( obj )[ upAxis ] upObj = controls[n] upObjAxis = getObjectAxisInDirection( upObj, upVector ) aimConstraint( nextObj, obj, aim=aimAxis.asVector(), upVector=upAxis.asVector(), wuo=upObj, wut='objectrotation', worldUpVector=upObjAxis.asVector(), mo=True ) orientConstraint( controls[-1], objs[-1], mo=True ) #now skin the linear curve to the controls and setup skinning lineCluster = skinCluster( controls, linearCurve, tsb=True )[0] for cvIdx, ctrl in enumerate( controls ): skinPercent( lineCluster, '%s.cv[%d]' % (linearCurve, cvIdx), transformValue=(ctrl, 1) ) #turn off inherit transforms for the proxy objects and curves so the user can parent them to whatever is needed for node in proxies: setAttr( '%s.inheritsTransform' % node, False ) setAttr( '%s.inheritsTransform' % linearCurve, False ) setAttr( '%s.inheritsTransform' % fittedCurve, False ) #now that we've setup the stretchy controls, lets add a splineIK version to blend between fixedLengthProxies = [] splineIkHandle = None if allowFixedLength: for j in proxies: fixedJ = createJoint( '%s_fixedLength' % j ) delete( parentConstraint( j, fixedJ ) ) if fixedLengthProxies: parent( fixedJ, fixedLengthProxies[-1] ) fixedLengthProxies.append( fixedJ ) splineIkHandle = cmd.ikHandle( startJoint=fixedLengthProxies[0], endEffector=fixedLengthProxies[-1], curve=fittedCurveShape, createCurve=False, solver='ikSplineSolver' )[0] addAttr( controls[0], ln='fixedLength', at='double', dv=0, min=0, max=1 ) setAttr( '%s.fixedLength' % controls[0], k=True ) rev = createNode( 'reverse' ) connectAttr( '%s.fixedLength' % controls[0], '%s.inputX' % rev, f=True ) for obj, fixedJ in zip( objs, fixedLengthProxies ): constraint = pointConstraint( fixedJ, obj, w=0 )[0] attrs = listAttr( constraint, ud=True ) connectAttr( '%s.outputX' % rev, '%s.%s' % (constraint, attrs[0]), f=True ) connectAttr( '%s.fixedLength' % controls[0], '%s.%s' % (constraint, attrs[1]), f=True ) #hide the joints setAttr( '%s.v' % obj, False ) setAttr( '%s.v' % fixedJ, False ) attrState( fixedLengthProxies, ('t', 'r', 's'), *LOCK_HIDE ) attrState( fixedLengthProxies, 'v', *HIDE ) attrState( proxies, ('t', 'r', 's'), *LOCK_HIDE ) attrState( proxies, 'v', *HIDE ) return fittedCurve, linearCurve, proxies, fixedLengthProxies, controls, splineIkHandle, halfIdx def buildNumControls( objs, numControls=3, **kw ): scale = kw.get( 'scale', 15 ) fittedCurve, linearCurve, proxies = buildCurveThroughObjs( objs ) fittedCurveShape = listRelatives( fittedCurve, s=True, pa=True )[0] #make sure the numControls is properly bounded: 3 <= numControls <= numObjects numControls = min( numControls, len( objs ) ) numControls = max( numControls, 3 ) partParent = listRelatives( objs, p=True, pa=True )[0] #build the spline ik node ikHandle, ikEffector = cmd.ikHandle( sj=proxies[0], ee=proxies[-1], sol='ikSplineSolver', curve=fittedCurve, createCurve=False ) setAttr( '%s.dTwistControlEnable' % ikHandle, True ) setAttr( '%s.dWorldUpType' % ikHandle, 4 ) connectAttr( '%s.worldMatrix' % partParent, '%s.dWorldUpMatrix' % ikHandle, f=True ) # halfWayPath = createNode( 'pointOnCurveInfo' ) halfWayPos = group( em=True, n="half" ) arcLength = getAttr( '%s.maxValue' % fittedCurveShape ) - getAttr( '%s.minValue' % fittedCurveShape ) connectAttr( '%s.worldSpace' % fittedCurveShape, '%s.inputCurve' % halfWayPath ) connectAttr( '%s.p' % halfWayPath, '%s.t' % halfWayPos ) maxParam = getAttr( '%s.spans' % fittedCurveShape ) paramInc = maxParam / float( numControls-1 ) #now build the controls controls = [] controlParent = None for n in range( numControls ): setAttr( '%s.parameter' % halfWayPath, n * paramInc ) nControl = buildControl( "control_%d" % n, halfWayPos, PivotModeDesc.MID, 'sphere', ColourDesc( 'darkblue' ), constrain=False, parent=controlParent, scale=scale, asJoint=True ) controlParent = nControl controls.append( nControl ) connectAttr( '%s.worldMatrix' % controls[-1], '%s.dWorldUpMatrixEnd' % ikHandle, f=True ) orientConstraint( controls[-1], objs[-1], mo=True ) #now skin the linear curve to the controls and setup skinning lineCluster = skinCluster( controls, linearCurve, tsb=True )[0] cvIdxs = range( len( objs ) ) #there is one cv per input object cvsPerControl = float( len( objs ) ) / (numControls - 1) #there is one cv per input object for n in range( numControls-1 ): cvsForThisControl = int( round( cvsPerControl * n ) ) weightInc = 1.0 / (cvsForThisControl - 1) c1, c2 = controls[n], controls[n+1] cvIdxs = range( n * cvsForThisControl, (n + 1) * cvsForThisControl ) for i, cvIdx in enumerate( cvIdxs ): weight = 1 - (i * weightInc) skinPercent( lineCluster, '%s.cv[%d]' % (linearCurve, cvIdx), transformValue=((c1, weight), (c2, 1.0-weight)) ) #now delete the nodes for the motion path - we're done with them delete( halfWayPath, halfWayPos ) def setupSquish( curve, joints ): #scaling? create a network to dynamically scale the objects based on the length #of the segment. there are two curve segments - start to mid, mid to end. this #scaling is done via SDK so we get control over the in/out of the scaling """squishNodes = [] if squish: curveInfo = createNode( 'curveInfo' ) scaleFac = shadingNode( n='squishCalculator', asUtility='multiplyDivide' ) adder = shadingNode( n='now_add_one', asUtility='plusMinusAverage' ) sdkScaler = createNode( 'animCurveUU', n='squish_sdk' ) initialLength = 0 maxScale = 2.0 minScale = 0.25 addAttr -k 1 -ln length -at double -min 0 -max 1 -dv 1 $deformJoints[0]; addAttr -k 1 -ln squishFactor -at double -min 0 -max 1 -dv 0 $deformJoints[0]; setAttr -k 1 ( $deformJoints[0] +".length" ); setAttr -k 1 ( $deformJoints[0] +".squishFactor" ); connectAttr -f ( $curveShape +".worldSpace[0]" ) ( $curveInfo +".inputCurve" ); initialLength = `getAttr ( $curveInfo +".arcLength" )`; setAttr ( $adder +".input1D[0]" ) 1; select -cl; setKeyframe -f $initialLength -v 0 $sdkScaler; setKeyframe -f( $initialLength/100 ) -v( $maxScale-1 ) $sdkScaler; setKeyframe -f( $initialLength*2 ) -v( $minScale-1 ) $sdkScaler; keyTangent -in 0 -itt flat -ott flat $sdkScaler; keyTangent -in 2 -itt flat -ott flat $sdkScaler; connectAttr -f ( $curveInfo +".arcLength" ) ( $sdkScaler +".input" ); connectAttr -f ( $scaleFac +".outputX" ) ( $adder +".input1D[1]" ); connectAttr -f ( $sdkScaler +".output" ) ( $scaleFac +".input1X" ); connectAttr -f ( $deformJoints[0] +".squishFactor" ) ( $scaleFac +".input2X" ); for( $n=0; $n<$numObjs; $n++ ) for( $ax in {"x","y","z"} ) connectAttr -f ( $adder +".output1D" ) ( $objs[$n] +".s"+ $ax ); lengthMults = [] for n in range( numObjs, 1 ): posOnCurve = getAttr( '%s.parameter' % mpaths[ n ] ) lengthMults[$n] = `shadingNode -n( "length_multiplier"+ $n ) -asUtility multiplyDivide`; setAttr ( $lengthMults[$n] +".input1X" ) $posOnCurve; connectAttr -f ( $deformJoints[0] +".length" ) ( $lengthMults[$n] +".input2X" ); connectAttr -f ( $lengthMults[$n] +".outputX" ) ( $mpaths[$n] +".parameter" ); $squishNodes = [ curveInfo, scaleFac, adder, sdkScaler} $lengthMults`;""" def buildCurveThroughObjs( objs, parentProxies=True ): #first we need to build a curve - we build an ep curve so that it goes exactly through the joint pivots numObjs = len( objs ) cmdKw = { 'd': 1 } cmdKw[ 'p' ] = tuple( xform( obj, q=True, ws=True, rp=True ) for obj in objs ) cmdKw[ 'k' ] = range( numObjs ) baseCurve = curve( **cmdKw ) fittedCurve = fitBspline( baseCurve, ch=True, tol=0.005 )[ 0 ] curveShape = listRelatives( fittedCurve, s=True, pa=True )[ 0 ] infoNode = createNode( 'curveInfo' ) connectAttr( '%s.worldSpace[ 0 ]' % curveShape, '%s.inputCurve' % infoNode, f=True ) knots = getAttr( '%s.knots' % infoNode )[ 0 ][ 2:-2 ] #now build the actual motion path nodes that keep the joints attached to the curve #there is one proxy for each joint. the original joints get constrained to #the proxies, which in turn get stuck to the motion path and oriented properly #then three joints get created, which are used to deform the motion path mpaths = {} proxies = {} unitComp = 1.0 if currentUnit( q=True, l=True ) == "m": unitComp = 100.0 for n, obj in enumerate( objs ): select( cl=True ) j = joint( n='%s_proxy' % objs[ n ] ) delete( parentConstraint( obj, j ) ) proxies[ obj ] = j proxiesList = [ proxies[obj] for obj in objs ] for n, j in enumerate( proxiesList ): if n == 0: continue if parentProxies: parent( j, proxiesList[n-1] ) makeIdentity( j, a=True, r=True ) #build a motionpath to get positions along the path - mainly useful for finding the half way mark halfWayPath = createNode( 'pointOnCurveInfo' ) halfWayPos = group( em=True, n="half" ) arcLength = getAttr( '%s.maxValue' % curveShape ) - getAttr( '%s.minValue' % curveShape ) connectAttr( '%s.worldSpace' % curveShape, '%s.inputCurve' % halfWayPath ) connectAttr( '%s.p' % halfWayPath, '%s.t' % halfWayPos ) setAttr( '%s.parameter' % halfWayPath, knots[ -1 ] / 2.0 ) delete( halfWayPos ) delete( infoNode ) baseCurve = rename( baseCurve, "pointCurve#" ) fittedCurve = rename( fittedCurve, "mPath#" ) return fittedCurve, baseCurve, proxiesList #end
Python
from math import sqrt class _Node(list): ''' simple wrapper around tree nodes - mainly to make the code a little more readable (although members are generally accessed via indices because its faster) ''' @property def point( self ): return self[0] @property def left( self ): return self[1] @property def right( self ): return self[2] def is_leaf( self ): return self[1] is None and self[2] is None class ExactMatch(Exception): pass class KdTree(): ''' simple, fast python kd-tree implementation thanks to: http://en.wikipedia.org/wiki/Kd-tree ''' DIMENSION = 3 #dimension of points in the tree def __init__( self, data=() ): self.performPopulate( data ) def performPopulate( self, data ): dimension = self.DIMENSION def populateTree( points, depth ): if not points: return None axis = depth % dimension #NOTE: this is slower than a DSU sort, but its a bit more readable, and the difference is only a few percent... points.sort( key=lambda point: point[ axis ] ) #find the half way point half = len( points ) / 2 node = _Node( [ points[ half ], populateTree( points[ :half ], depth+1 ), populateTree( points[ half+1: ], depth+1 ) ] ) return node self.root = populateTree( data, 0 ) def getClosest( self, queryPoint, returnDistances=False ): ''' Returns the closest point in the tree to the given point NOTE: see the docs for getWithin for info on the returnDistances arg ''' dimension = self.DIMENSION distBest = (self.root[0] - queryPoint).get_magnitude() ** 2 bestList = [ (distBest, self.root[0]) ] def search( node, depth ): nodePoint = node[0] axis = depth % dimension if queryPoint[axis] < nodePoint[axis]: nearNode = node[1] farNode = node[2] else: nearNode = node[2] farNode = node[1] #start the search if nearNode is not None: search( nearNode, depth+1 ) #get the squared distance sd = 0 for v1, v2 in zip( nodePoint, queryPoint ): sd += (v1 - v2)**2 curBest = bestList[0][0] #if the point is closer than the currently stored one, insert it at the head if sd < curBest: bestList.insert( 0, (sd, nodePoint) ) #if its an exact match, bail if not sd: raise ExactMatch else: bestList.append( (sd, nodePoint) ) # check whether there could be any points on the other side of the # splitting plane that are closer to the query point than the current best if farNode is not None: if (nodePoint[ axis ] - queryPoint[ axis ])**2 < curBest: search( farNode, depth+1 ) try: search( self.root, 0 ) except ExactMatch: pass if returnDistances: return bestList[0] return bestList[0][1] def getWithin( self, queryPoint, threshold=1e-6, returnDistances=False ): ''' Returns all points that fall within the radius of the queryPoint within the tree. NOTE: if returnDistances is True then the squared distances between the queryPoint and the points in the return list are returned. This means the return list looks like this: [ (sqDistToPoint, point), ... ] This can be useful if you need to do more work on the results afterwards - just be aware that the distances in the list are squares of the actual distance between the points ''' dimension = self.DIMENSION axisRanges = axRangeX, axRangeY, axRangeZ = ( (queryPoint[0]-threshold, queryPoint[0]+threshold), (queryPoint[1]-threshold, queryPoint[1]+threshold), (queryPoint[2]-threshold, queryPoint[2]+threshold) ) sqThreshold = threshold ** 2 matches = [] def search( node, depth ): nodePoint = node[0] axis = depth % dimension if queryPoint[axis] < nodePoint[axis]: nearNode = node[1] farNode = node[2] else: nearNode = node[2] farNode = node[1] #start the search if nearNode is not None: search( nearNode, depth+1 ) #test this point if axRangeX[0] <= nodePoint[ 0 ] <= axRangeX[1]: if axRangeY[0] <= nodePoint[ 1 ] <= axRangeY[1]: if axRangeZ[0] <= nodePoint[ 2 ] <= axRangeZ[1]: sd = 0 for v1, v2 in zip( nodePoint, queryPoint ): sd += (v1 - v2)**2 if sd <= sqThreshold: matches.append( (sd, nodePoint) ) if farNode is not None: if (nodePoint[ axis ] - queryPoint[ axis ])**2 < sqThreshold: search( farNode, depth+1 ) search( self.root, 0 ) matches.sort() #the best is guaranteed to be at the head of the list, but consequent points might be out of order - so order them now if returnDistances: return matches return [ m[1] for m in matches ] def getDistanceRatioWeightedVector( self, queryPoint, ratio=2, returnDistances=False ): ''' Finds the closest point to the queryPoint in the tree and returns all points within a distance of ratio*<closest point distance>. This is generally more useful that using getWithin because getWithin could return an exact match along with a bunch of points at the outer search limit and thus heavily bias the results. NOTE: see docs for getWithin for details on the returnDistance arg ''' assert ratio > 1 closestDist, closest = self.getClosest( queryPoint, returnDistances=True ) if closestDist == 0: if returnDistances: return [ (0, closest) ] return [ closest ] closestDist = sqrt( closestDist ) maxDist = closestDist * ratio return self.getWithin( queryPoint, maxDist, returnDistances=returnDistances ) #end
Python
from maya.cmds import * import maya.cmds as cmd import vectors import re Vector = vectors.Vector Colour = Color = vectors.Colour def setShaderColour( shader, colour ): if not isinstance( colour, Colour ): colour = Colour( colour ) setAttr( '%s.outColor' % shader, *colour ) if colour[ 3 ]: a = colour[ 3 ] setAttr( '%s.outTransparency' % shader, a, a, a ) def setObjShader( obj, shader ): SG = listConnections( '%s.outColor' % shader, s=False, type='shadingEngine' )[ 0 ] shapes = listRelatives( obj, pa=True, s=True ) or [] for shape in shapes: if nodeType( shape ) == 'nurbsCurve': continue sets( shape, e=True, forceElement=SG ) def getObjColour( obj ): shader = getObjShader( obj ) if shader: return getAttr( '%s.outColor' % shader )[0] return None def getObjShader( obj ): ''' returns the shader currently assigned to the given object ''' shapes = listRelatives( obj, s=True, pa=True ) or [] if not shapes: return None cons = listConnections( shapes, s=False, type='shadingEngine' ) or [] for c in cons: shaders = listConnections( '%s.surfaceShader' % c, d=False ) or [] if shaders: return shaders[ 0 ] def getShader( colour, forceCreate=True ): ''' given a colour, this proc will either return an existing shader with that colour or it will create a new shader (if forceCreate is true) if an existing one isn't found NOTE - this proc will look for a shader that has a similar colour to the one specified - so the colour may not always be totally accurate if a shader exists with a similar colour - the colour/alpha threshold is 0.05 ''' if not isinstance( colour, Colour ): colour = Colour( colour ) shaders = ls( type='surfaceShader' ) or [] for shader in shaders: thisColour = list( getAttr( '%s.outColor' % shader )[ 0 ] ) alpha = getAttr( '%s.outTransparency' % shader )[ 0 ][ 0 ] thisColour.append( alpha ) thisColour = Colour( thisColour ) if thisColour == colour: return shader if forceCreate: return createShader( colour ) return None def createShader( colour ): ''' creates a shader of a given colour - always creates a new shader ''' name = 'rigShader_%s' % Colour.ColourToName( colour ) shader = shadingNode( 'surfaceShader', name=name, asShader=True ) SG = sets( name='%s_SG' % name, renderable=True, noSurfaceShader=True, empty=True ) connectAttr( '%s.outColor' % shader, '%s.surfaceShader' % SG, f=True ) setAttr( '%s.outColor' % shader, *colour[ :3 ] ) a = colour[ 3 ] setAttr( '%s.outTransparency' % shader, a, a, a ) shadingConnection( '%s.surfaceShader' % SG, e=True, cs=False ) return shader def setDrawOverrideColor( obj, color=17 ): """ edit the given object's shape node override color """ shapes = [] if not cmd.objectType( obj, i='nurbsCurve' ) or not cmd.objectType( obj, i='nurbsSurface' ) or not cmd.objectType( obj, i='mesh' ): shapes.append( obj ) for s in listRelatives( obj, s=True, pa=True ) or []: shapes.append( s ) if shapes: for s in shapes: conns = cmd.listConnections( '%s.drawOverride' % s, s=True ) if not conns: if not color == 0: cmd.setAttr ('%s.overrideEnabled' % s, e=True, l=False ) cmd.setAttr ('%s.overrideEnabled' % s, 1 ) cmd.setAttr ('%s.overrideColor' % s, e=True, l=False ) cmd.setAttr ('%s.overrideColor' % s, color ) else: cmd.color( s ) cmd.setAttr ('%s.overrideColor' % s, e=True, l=False ) cmd.setAttr ('%s.overrideColor' % s, color ) cmd.setAttr ('%s.overrideEnabled' % s, e=True, l=False ) cmd.setAttr ('%s.overrideEnabled' % s, 0 ) #end
Python
from baseMelUI import * from animLib import * import presetsUI import xferAnimUI __author__ = 'mel@macaronikazoo.com' def getSelectedChannelBoxAttrNames(): attrNames = cmd.channelBox( 'mainChannelBox', q=True, sma=True ) or [] attrNames += cmd.channelBox( 'mainChannelBox', q=True, ssa=True ) or [] attrNames += cmd.channelBox( 'mainChannelBox', q=True, sha=True ) or [] return attrNames class AnimLibClipLayout(MelForm): SLIDER_VISIBLE = { kPOSE: True, kANIM: False } def __new__( cls, parent, library, locale, clipPreset ): return MelHLayout.__new__( cls, parent ) def __init__( self, parent, library, locale, clipPreset ): MelForm.__init__( self, parent ) self.clipPreset = clipPreset self.name = self.clipPreset.niceName self.isActive = False self.preClip = {} self.objs = [] self.mapping = {} self.type = self.clipPreset.getType() self.optionsLayout = self.getParentOfType( AnimLibLayout ) #cache the apply method locally - mainly for brevity in subsequent code... self.apply = clipPreset.apply #read the clip and cache some data... self.blended = None self.build() def build( self ): ''' populates the top level form with ui widgets ''' self.UI_icon = MelIconButton( self, l=self.name(), image=str(self.clipPreset.icon.resolve()), w=kICON_W_H[0], h=kICON_W_H[1], c=self.onApply, sourceType='python', ann="click the icon to apply the clip, or use the slider to partially apply it. if you don't like the icon, right click and choose re-generate icon" ) typeLbl = ClipPreset.TYPE_LABELS[ self.clipPreset.getType() ] self.UI_lbl = MelLabel( self, l='%s clip: %s' % (typeLbl, self.name()), font='boldLabelFont', ann="this is the clip's name. right click and choose rename to change the clip's name" ) #setup the slider self.UI_slider = MelFloatSlider( self, v=0, min=0, max=1, ann='use the slider to partially apply a clip, or click the icon to apply it completely' ) self.UI_slider.setPreChangeCB( self.preDrag ) self.UI_slider.setChangeCB( self.onDrag ) self.UI_slider.setPostChangeCB( self.postDrag ) self.UI_slider.DISABLE_UNDO_ON_DRAG = True self.UI_slider.setVisibility( self.SLIDER_VISIBLE[ self.type ] ) MelPopupMenu( self, pmc=self.buildMenu ) #do layout self( e=True, af=((self.UI_icon, 'left', 0), (self.UI_lbl, 'top', 2), (self.UI_lbl, 'right', 0), (self.UI_slider, 'top', 20), (self.UI_slider, 'right', 0)), ac=((self.UI_lbl, 'left', 10, self.UI_icon), (self.UI_slider, 'left', 0, self.UI_icon)) ) def unpickle( self ): return self.clipPreset.unpickle() @property def clipObjs( self ): return self.unpickle()[ 'objects' ] @property def clipInstance( self ): return self.unpickle()[ 'clip' ] def onApply( self, slam=False ): opts = self.optionsLayout.getOptions() opts[ 'slam' ] = slam if opts[ 'attrSelection' ]: attributes = cmd.channelBox( 'mainChannelBox', q=True, sma=True ) or cmd.channelBox( 'mainChannelBox', q=True, sha=True ) or None else: attributes = None self.apply( cmd.ls(sl=True), attributes, **opts ) def buildMenu( self, parent, *args ): cmd.setParent( parent, m=True ) cmd.menu( parent, e=True, dai=True ) cmd.menuItem( l=self.name(), boldFont=True ) if self.clipPreset.locale == LOCAL: cmd.menuItem( l='publish to global -->', c=self.onPublish ) def onIcon(*x): generateIcon(self.clipPreset) self.refreshIcon() cmd.menuItem( l='re-generate icon', c=onIcon ) cmd.menuItem( d=True ) cmd.menuItem( l='delete', c=lambda *x: self.delete() ) cmd.menuItem( l='rename', c=self.onRename ) cmd.menuItem( d=True ) cmd.menuItem( l='slam clip into scene', c=self.onSlam ) cmd.menuItem( l='select items in clip', c=self.onSelect ) cmd.menuItem( l='map names manually', c=self.onMapping ) cmd.menuItem( d=True ) cmd.menuItem( l='edit clip', c=self.onEdit ) cmd.menuItem( d=True ) api.addExploreToMenuItems(self.clipPreset) def onPublish( self, *args ): movedPreset = self.clipPreset.move() self.delete() self.sendEvent( 'populateClips' ) def onSelect( self, arg ): objs = self.clipPreset.getClipObjects() existingObjs = [] sceneTransforms = cmd.ls( typ='transform' ) for o in objs: if not cmd.objExists( o ): newO = names.matchNames( [o], sceneTransforms, threshold=kDEFAULT_MAPPING_THRESHOLD )[ 0 ] if not cmd.objExists( newO ): print 'WARNING :: %s NOT FOUND IN SCENE!!!' % o continue existingObjs.append( newO ) print 'WARNING :: re-mapping %s to %s' % (o, newO) else: existingObjs.append( o ) cmd.select( existingObjs ) def onSlam( self, arg ): self.onApply( True ) def onMapping( self, *args ): mapping = Mapping( cmd.ls(sl=True), self.clipObjs ) #convert the mapping to the type of mapping expected by the xfer anim editor - ie a single source maps to a list of targets instead of a single target... xferAnimMapping = {} for src, tgt in mapping.iteritems(): xferAnimMapping[ src ] = [ tgt ] xferAnimUI.XferAnimWindow( mapping=xferAnimMapping, clipPreset=self.clipPreset ) def onEdit( self, *args ): AnimClipChannelEditorWindow( self.clipPreset ) def onRename( self, *args ): ans, name = api.doPrompt(t='new name', m='enter new name', tx=self.name()) if ans != api.OK: return self.clipPreset = self.clipPreset.rename( name ) self.clear() self.populateUI() def preDrag( self ): self.autoKeyBeginState = cmd.autoKeyframe( q=True, state=True ) cmd.autoKeyframe( e=True, state=False ) opts = self.optionsLayout.getOptions() if opts[ 'attrSelection' ]: attributes = cmd.channelBox( 'mainChannelBox', q=True, sma=True ) or cmd.channelBox( 'mainChannelBox', q=True, sha=True ) or None else: attributes = None self.objs = objs = cmd.ls( sl=True ) tgts = names.matchNames( self.clipObjs, objs, threshold=kDEFAULT_MAPPING_THRESHOLD ) self.mapping = mapping = Mapping( tgts, self.clipObjs ) self.preClip = self.clipInstance.__class__( objs, *self.clipInstance.generatePreArgs() ) self.blended = self.clipInstance.blender( self.preClip, self.clipInstance, mapping, attributes ) def onDrag( self, value ): value = float( value ) self.blended( value ) def postDrag( self, value ): cmd.autoKeyframe( e=True, state=self.autoKeyBeginState ) value = float( value ) self.blended( value ) self.reset() def refreshIcon( self ): self.UI_icon.refresh() def delete( self ): self.clipPreset.delete() MelForm.delete( self ) def reset( self ): self.UI_slider.reset( False ) class AnimClipChannelEditorLayout(MelVSingleStretchLayout): def __init__( self, parent, clipPreset ): MelVSingleStretchLayout.__init__( self, parent ) self.clipPreset = clipPreset self.presetDict = presetDict = clipPreset.unpickle() self.clipDict = clipDict = presetDict[ 'clip' ] self._dirty = False #build the UI hLayout = MelHLayout( self ) vLayout = MelVSingleStretchLayout( hLayout ) self.UI_objList = UI_objList = MelObjectScrollList( vLayout ) UI_removeObjs = MelButton( vLayout, l='Remove Selected Objects' ) vLayout.setStretchWidget( UI_objList ) vLayout.layout() vLayout = MelVSingleStretchLayout( hLayout ) self.UI_attrList = UI_attrList = MelObjectScrollList( vLayout ) UI_removeAttrs = MelButton( vLayout, l='Remove Selected Attributes' ) vLayout.setStretchWidget( UI_attrList ) vLayout.layout() UI_objList.allowMultiSelect( True ) UI_attrList.allowMultiSelect( True ) hLayout.expand = True hLayout.layout() self.setStretchWidget( hLayout ) #populate the object list for obj in clipDict: UI_objList.append( obj ) #build callbacks for the lists def objSelected(): objs = UI_objList.getSelectedItems() if not objs: return UI_attrList.clear() attrsAlreadyAdded = set() for obj in objs: attrDict = clipDict[ obj ] for attrName, attrValue in attrDict.iteritems(): if attrName in attrsAlreadyAdded: continue self.UI_attrList.append( attrName ) attrsAlreadyAdded.add( attrName ) if attrDict: self.UI_attrList.selectByIdx( 0, True ) UI_objList.setChangeCB( objSelected ) def removeObjs( *a ): objs = UI_objList.getSelectedItems() if not objs: return performUpdate = False for obj in objs: if obj in clipDict: self._dirty = True performUpdate = True clipDict.pop( obj ) if performUpdate: UI_objList.clear() UI_attrList.clear() for obj in clipDict: UI_objList.append( obj ) if clipDict: UI_objList.selectByIdx( 0, True ) UI_removeObjs.setChangeCB( removeObjs ) def removeAttrs( *a ): objs = UI_objList.getSelectedItems() if not objs: return attrs = UI_attrList.getSelectedItems() if not attrs: return performUpdate = False for obj in objs: subDict = clipDict[ obj ] for attr in attrs: self._dirty = True performUpdate = True if attr in subDict: subDict.pop( attr ) if performUpdate: objSelected() UI_removeAttrs.setChangeCB( removeAttrs ) #set the initial state if len( self.UI_objList ): UI_objList.selectByIdx( 0, True ) #build the save/cancel UI... hLayout = MelHLayout( self ) MelButton( hLayout, l='Save', c=self.on_save ) MelButton( hLayout, l='Cancel', c=lambda *a: self.sendEvent( 'delete' ) ) hLayout.layout() self.setDeletionCB( self.on_cancel ) self.layout() def askToSave( self ): #check to see if changes were made, and if so, ask if the user wants to save them... if self._dirty: BUTTONS = YES, NO, CANCEL = 'Yes', 'No', 'Cancel' ret = cmd.confirmDialog( t='Overwrite Clip?', m='Are you sure you want to overwrite the %s clip called %s?' % (ClipPreset.TYPE_LABELS[ self.clipPreset.getType() ], self.clipPreset.name().split( '.' )[0]), b=BUTTONS, db=CANCEL ) if ret == CANCEL: return False elif ret == YES: self.clipPreset.pickle( self.presetDict ) self._dirty = False return True ### EVENT HANDLERS ### def on_cancel( self, *a ): self.askToSave() def on_save( self, *a ): if self.askToSave(): self.sendEvent( 'delete' ) class AnimClipChannelEditorWindow(BaseMelWindow): WINDOW_NAME = 'animClipEditor' WINDOW_TITLE = 'Anim Clip Editor' DEFAULT_MENU = None DEFAULT_SIZE = 400, 250 FORCE_DEFAULT_SIZE = False def __init__( self, clipPreset ): BaseMelWindow.__init__( self ) AnimClipChannelEditorLayout( self, clipPreset ) self.show() class AnimLibLocaleLayout(MelVSingleStretchLayout): def __init__( self, parent, clipManager, locale ): MelVSingleStretchLayout.__init__( self, parent ) self._locale = locale self._clipManager = clipManager self._filterStr = None self._libraries = None if locale == GLOBAL: hLayout = MelHLayout( self ) MelLabel( hLayout, l='global clips' ) MelButton( hLayout, l='sync global clips', c=self.on_sync ) hLayout.layout() else: MelLabel( self, l='local clips' ) scroll = MelScrollLayout( self ) self.UI_clips = MelColumnLayout( scroll ) self.setStretchWidget( scroll ) self.layout() MelPopupMenu( self, pmc=self.buildMenu ) def setLibraries( self, libraries ): self._libraries = libraries self.populate() def getClips( self ): clips = {} for library in self._libraries: clips[ library ] = self._clipManager.getLibraryClips( library )[ self._locale ] return clips def populate( self ): self.UI_clips.clear() filterStr = self._filterStr clips = self.getClips() for library, clips in clips.iteritems(): for clip in clips: clipName = clip.niceName() addClip = False if filterStr: if filterStr in clipName: addClip = True else: addClip = True if addClip: AnimLibClipLayout( self.UI_clips, library, self._locale, clip ) def getFilter( self ): return self._filterStr def setFilter( self, filterStr ): self._filterStr = filterStr self.populate() def buildMenu( self, parent, *args ): cmd.setParent( parent, m=True ) cmd.menu( parent, e=True, dai=True ) cmd.menuItem( l='new pose clip', c=lambda *x: self.sendEvent( 'newClip', kPOSE ) ) cmd.menuItem( l='new anim clip', c=lambda *x: self.sendEvent( 'newClip', kANIM ) ) def on_sync( self, *a ): #p4run( 'sync', *self._clipManager.getPresetDirs( GLOBAL ) ) self.populate() self.sendEvent( 'populateLibraries' ) class AnimLibLayout(MelHSingleStretchLayout): def __init__( self, parent ): MelHSingleStretchLayout.__init__( self, parent ) AnimClipChannelEditorWindow.Close() self._clipManager = clipManager = ClipManager() vLayout = MelVSingleStretchLayout( self ) MelLabel( vLayout, l='clip libraries' ) hLayout = MelHSingleStretchLayout( vLayout ) MelLabel( hLayout, l='filter' ) self.UI_filter = MelTextField( hLayout, cc=self.on_filter ) MelButton( hLayout, l='clear', c=lambda *a: self.UI_filter.clear() ) hLayout.setStretchWidget( self.UI_filter ) hLayout.layout() self.UI_libraries = MelObjectScrollList( vLayout, ams=True ) self.UI_libraries.setChangeCB( self.on_selectLibrary ) self.UI_newLibrary = MelButton( vLayout, l='new library', w=150, c=self.on_newLibrary ) vLayout.setStretchWidget( self.UI_libraries ) vLayout.layout() #this is the layout for everything on the right side of the library list paneLayout = MelVSingleStretchLayout( self ) #add clip filter UI hLayout = MelHSingleStretchLayout( paneLayout ) MelSpacer( hLayout ) MelLabel( hLayout, l='filter clips' ) self.UI_filterClips = MelTextField( hLayout, cc=self.on_filterClips ) MelButton( hLayout, l='clear', c=lambda *a: self.UI_filterClips.clear() ) hLayout.setStretchWidget( self.UI_filterClips ) hLayout.layout() #add the libraries self.UI_panes = MelHLayout( paneLayout ) self.UI_panes.expand = True self.UI_local = AnimLibLocaleLayout( self.UI_panes, clipManager, LOCAL ) self.UI_global = AnimLibLocaleLayout( self.UI_panes, clipManager, GLOBAL ) self.UI_panes.layout() #add the load options hLayout = MelHRowLayout( paneLayout ) self.UI_opt_currentTime = MelCheckBox( hLayout, l='load clip at current time', v=True ) self.UI_opt_additive = MelCheckBox( hLayout, l='load additively' ) #self.UI_opt_currentTime = MelCheckBox( hLayout, l='load additively in world', en=False ) self.UI_opt_attrSelection = MelCheckBox( hLayout, l='use attribute selection', v=BaseClip.kOPT_DEFAULTS[ BaseClip.kOPT_ATTRSELECTION ] ) hLayout.layout() #add the "new" buttons hLayout = MelHLayout( paneLayout ) MelButton( hLayout, l='new pose clip', c=self.on_newPose ) MelButton( hLayout, l='new anim clip', c=self.on_newAnim ) hLayout.layout() paneLayout.setStretchWidget( self.UI_panes ) paneLayout.layout() self.setStretchWidget( paneLayout ) self.setExpand( True ) self.layout() self.populateLibraries() self.setDeletionCB( self.on_close ) def populateLibraries( self ): UI_libraries = self.UI_libraries UI_libraries.clear() libraryNames = self._clipManager.getLibraryNames() for library in libraryNames: UI_libraries.append( library ) if libraryNames: self.UI_libraries.selectByIdx( 0, True ) self.UI_libraries.setFocus() def populateClips( self ): self.UI_local.populate() self.UI_global.populate() def getOptions( self ): opts = {} opts[ BaseClip.kOPT_OFFSET ] = cmd.currentTime( q=True ) if self.UI_opt_currentTime.getValue() else 0 opts[ BaseClip.kOPT_ADDITIVE ] = self.UI_opt_additive.getValue() opts[ BaseClip.kOPT_ATTRSELECTION ] = self.UI_opt_attrSelection.getValue() return opts def getLocalVisibility( self ): return self.UI_local.getVisibility() def setLocalVisibility( self, showState ): #if the global is currently invisible, turn it on - no point having neither local or global invisible... if not self.UI_global.getVisibility(): self.setGlobalVisibility( True ) self.UI_local.setVisibility( showState ) self.UI_panes.setWeight( self.UI_local, int( showState ) ) self.UI_panes.layout() def getGlobalVisibility( self ): return self.UI_global.getVisibility() def setGlobalVisibility( self, showState ): #if the local is currently invisible, turn it on - no point having neither local or global invisible... if not self.UI_local.getVisibility(): self.setLocalVisibility( True ) self.UI_global.setVisibility( showState ) self.UI_panes.setWeight( self.UI_global, int( showState ) ) self.UI_panes.layout() def newClip( self, clipType ): theLibrary = self.UI_libraries.getSelectedItems() if not theLibrary: return theLibrary = theLibrary[0] BUTTONS = OK, CANCEL = 'OK', 'Cancel' typeLabel = ClipPreset.TYPE_LABELS[ clipType ] ans = cmd.promptDialog( t='enter %s name' % typeLabel, m='enter the %s name:' % typeLabel, b=BUTTONS, db=OK ) if ans == CANCEL: return kwargs = {} opts = self.getOptions() if opts.get( 'attrSelection', False ): kwargs[ 'attrs' ] = getSelectedChannelBoxAttrNames() or None if clipType == kANIM: kwargs = { 'startFrame': cmd.playbackOptions( q=True, min=True ), 'endFrame': cmd.playbackOptions( q=True, max=True ) } objs = cmd.ls( sl=True ) name = cmd.promptDialog( q=True, tx=True ) newClip = ClipPreset( LOCAL, theLibrary, name, clipType ) newClip.write( objs, **kwargs ) #add the clip to the UI self.UI_local.populate() ### EVENT HANDLERS ### def on_close( self, *a ): AnimClipChannelEditorWindow.Close() def on_selectLibrary( self, *a ): sel = self.UI_libraries.getSelectedItems() if sel: self.UI_local.setLibraries( sel ) self.UI_global.setLibraries( sel ) def on_newLibrary( self, *a ): BUTTONS = OK, CANCEL = 'OK', 'Cancel' ans = cmd.promptDialog( t='enter library name', m='enter the library name:', b=BUTTONS, db=OK ) if ans == CANCEL: return name = cmd.promptDialog( q=True, tx=True ) self._clipManager.createLibrary( name ) self.populateLibraries() self.UI_libraries.clearSelection() self.UI_libraries.selectByValue( name ) self.UI_local.setLibraries( name ) self.UI_global.setLibraries( name ) def on_newPose( self, *args ): self.newClip( kPOSE ) def on_newAnim( self, *args ): self.newClip( kANIM ) def on_filter( self, *a ): self.UI_libraries.setFilter( self.UI_filter.getValue() ) #if there are no selected items, check to see if there are any items and if so select the first one if not self.UI_libraries.getSelectedIdxs(): if self.UI_libraries.getItems(): self.UI_libraries.selectByIdx( 0, True ) def on_filterClips( self, *a ): filterStr = self.UI_filterClips.getValue() self.UI_local.setFilter( filterStr ) self.UI_global.setFilter( filterStr ) class AnimLibWindow(BaseMelWindow): WINDOW_NAME = 'animLibraryWindow' WINDOW_TITLE = 'Animation Library' DEFAULT_SIZE = 750, 400 FORCE_DEFAULT_SIZE = True DEFAULT_MENU = 'Show' HELP_MENU = TOOL_NAME, __author__, None def __init__( self ): BaseMelWindow.__init__( self ) showMenu = self.getMenu( self.DEFAULT_MENU ) showMenu( e=True, pmc=self.buildShowMenu ) self.UI_editor = AnimLibLayout( self ) self.show() def buildShowMenu( self, *w ): showMenu = self.getMenu( self.DEFAULT_MENU ) showMenu.clear() MelMenuItem( showMenu, l='Show Local Clips', cb=self.UI_editor.getLocalVisibility(), c=self.on_showLocal ) MelMenuItem( showMenu, l='Show Global Clips', cb=self.UI_editor.getGlobalVisibility(), c=self.on_showGlobal ) def on_showLocal( self, *a ): state = int( a[0] ) self.UI_editor.setLocalVisibility( state ) def on_showGlobal( self, *a ): state = int( a[0] ) self.UI_editor.setGlobalVisibility( state ) AnimLibUI = AnimLibWindow def load(): #first make sure there is a default library... tmp = ClipManager().createLibrary( 'default' ) AnimLibUI() #end
Python
from vectors import Matrix, Vector, Axis import maya.cmds as cmd import maya.OpenMaya as OpenMaya import maya.OpenMayaMPx as OpenMayaMPx import vectors import apiExtensions from maya.OpenMaya import MObject, MFnMatrixAttribute, MFnCompoundAttribute, MFnMessageAttribute, MGlobal, \ MFnEnumAttribute, MFnNumericAttribute, MFnNumericData, MFnUnitAttribute, MFnDependencyNode, \ MPoint, MVector, MSyntax, MArgDatabase from maya.OpenMayaMPx import MPxNode MPxCommand = OpenMayaMPx.MPxCommand kUnknownParameter = OpenMaya.kUnknownParameter #this list simply maps the rotation orders as found on the rotateOrder enum attribute, to the matrix methods responsible for converting a rotation matrix to euler values mayaRotationOrders = Matrix.ToEulerXYZ, Matrix.ToEulerYZX, Matrix.ToEulerZXY, Matrix.ToEulerXZY, Matrix.ToEulerYXZ, Matrix.ToEulerZYX assert len( mayaRotationOrders ) == len( set( mayaRotationOrders ) ) #sanity check class MirrorNode(MPxNode): NODE_ID = OpenMaya.MTypeId( 0x00115940 ) NODE_TYPE_NAME = "rotationMirror" inWorldMatrix = MObject() #this is the input world matrix; the one we want mirrored inParentMatrixInv = MObject() #this is the input parent inverse matrix. ie the parent inverse matrix of the transform we want mirrored mirrorAxis = MObject() #which axis are we mirroring on? mirrorTranslation = MObject() #boolean to determine whether translation mirroring happens in world space or local space targetJointOrient = MObject() #this is the joint orient attribute for the target joint - so it can be compensated for targetJointOrientX = MObject() targetJointOrientY = MObject() targetJointOrientZ = MObject() targetParentMatrixInv = MObject() #this is the parent inverse matrix for the target transform targetRotationOrder = MObject() #the rotation order on the target outTranslate = MObject() #the output translation outTranslateX = MObject() outTranslateY = MObject() outTranslateZ = MObject() outRotate = MObject() #the output rotation outRotateX = MObject() outRotateY = MObject() outRotateZ = MObject() MIRROR_MODES = M_COPY, M_INVERT, M_MIRROR = range( 3 ) MIRROR_MODE_NAMES = 'copy', 'invert', 'mirror' MIRROR_DEFAULT = M_MIRROR @classmethod def Creator( cls ): return OpenMayaMPx.asMPxPtr( cls() ) @classmethod def Init( cls ): attrInWorldMatrix = MFnMatrixAttribute() attrInParentMatrixInv = MFnMatrixAttribute() attrMirrorAxis = MFnEnumAttribute() attrMirrorTranslation = MFnEnumAttribute() attrTargetParentMatrixInv = MFnMatrixAttribute() targetRotationOrder = MFnNumericAttribute() attrOutTranslate = MFnNumericAttribute() attrOutTranslateX = MFnUnitAttribute() attrOutTranslateY = MFnUnitAttribute() attrOutTranslateZ = MFnUnitAttribute() attrOutRotate = MFnNumericAttribute() attrOutRotateX = MFnUnitAttribute() attrOutRotateY = MFnUnitAttribute() attrOutRotateZ = MFnUnitAttribute() attrTargetJointOrient = MFnNumericAttribute() attrTargetJointOrientX = MFnUnitAttribute() attrTargetJointOrientY = MFnUnitAttribute() attrTargetJointOrientZ = MFnUnitAttribute() #create the world matrix cls.inWorldMatrix = attrInWorldMatrix.create( "inWorldMatrix", "iwm" ) cls.addAttribute( cls.inWorldMatrix ) #create the local matrix cls.inParentMatrixInv = attrInWorldMatrix.create( "inParentInverseMatrix", "ipmi" ) cls.addAttribute( cls.inParentMatrixInv ) #create the mirror axis cls.mirrorAxis = attrMirrorAxis.create( "mirrorAxis", "m" ) attrMirrorAxis.addField( 'x', 0 ) attrMirrorAxis.addField( 'y', 1 ) attrMirrorAxis.addField( 'z', 2 ) attrMirrorAxis.setDefault( 'x' ) attrMirrorAxis.setKeyable( False ) attrMirrorAxis.setChannelBox( True ) cls.addAttribute( cls.mirrorAxis ) #create the mirror axis cls.mirrorTranslation = attrMirrorTranslation.create( "mirrorTranslation", "mt" ) for modeName, modeIdx in zip( cls.MIRROR_MODE_NAMES, cls.MIRROR_MODES ): attrMirrorTranslation.addField( modeName, modeIdx ) attrMirrorTranslation.setDefault( cls.MIRROR_DEFAULT ) attrMirrorTranslation.setKeyable( False ) attrMirrorTranslation.setChannelBox( True ) cls.addAttribute( cls.mirrorTranslation ) #create the out world matrix inverse cls.targetParentMatrixInv = attrTargetParentMatrixInv.create( "targetParentInverseMatrix", "owm" ) cls.addAttribute( cls.targetParentMatrixInv ) #create the target rotation order attribute cls.targetRotationOrder = targetRotationOrder.create( "targetRotationOrder", "troo", MFnNumericData.kInt ) cls.addAttribute( cls.targetRotationOrder ) #create the joint orient compensation attributes cls.targetJointOrientX = attrTargetJointOrientX.create( "targetJointOrientX", "tjox", MFnUnitAttribute.kAngle ) cls.targetJointOrientY = attrTargetJointOrientY.create( "targetJointOrientY", "tjoy", MFnUnitAttribute.kAngle ) cls.targetJointOrientZ = attrTargetJointOrientZ.create( "targetJointOrientZ", "tjoz", MFnUnitAttribute.kAngle ) cls.targetJointOrient = attrTargetJointOrient.create( "targetJointOrient", "tjo", cls.targetJointOrientX, cls.targetJointOrientY, cls.targetJointOrientZ ) cls.addAttribute( cls.targetJointOrient ) #create the out translate attributes cls.outTranslateX = attrOutTranslateX.create( "outTranslateX", "otx", MFnUnitAttribute.kDistance ) cls.outTranslateY = attrOutTranslateY.create( "outTranslateY", "oty", MFnUnitAttribute.kDistance ) cls.outTranslateZ = attrOutTranslateZ.create( "outTranslateZ", "otz", MFnUnitAttribute.kDistance ) cls.outTranslate = attrOutTranslate.create( "outTranslate", "ot", cls.outTranslateX, cls.outTranslateY, cls.outTranslateZ ) cls.addAttribute( cls.outTranslate ) #create the out rotation attributes cls.outRotateX = attrOutRotateX.create( "outRotateX", "orx", MFnUnitAttribute.kAngle ) cls.outRotateY = attrOutRotateY.create( "outRotateY", "ory", MFnUnitAttribute.kAngle ) cls.outRotateZ = attrOutRotateZ.create( "outRotateZ", "orz", MFnUnitAttribute.kAngle ) cls.outRotate = attrOutRotate.create( "outRotate", "or", cls.outRotateX, cls.outRotateY, cls.outRotateZ ) cls.addAttribute( cls.outRotate ) #setup attribute dependency relationships cls.attributeAffects( cls.inWorldMatrix, cls.outTranslate ) cls.attributeAffects( cls.inWorldMatrix, cls.outRotate ) cls.attributeAffects( cls.inParentMatrixInv, cls.outTranslate ) cls.attributeAffects( cls.inParentMatrixInv, cls.outRotate ) cls.attributeAffects( cls.mirrorAxis, cls.outTranslate ) cls.attributeAffects( cls.mirrorAxis, cls.outRotate ) cls.attributeAffects( cls.mirrorTranslation, cls.outTranslate ) cls.attributeAffects( cls.mirrorTranslation, cls.outRotate ) cls.attributeAffects( cls.targetParentMatrixInv, cls.outTranslate ) cls.attributeAffects( cls.targetParentMatrixInv, cls.outRotate ) cls.attributeAffects( cls.targetRotationOrder, cls.outTranslate ) cls.attributeAffects( cls.targetRotationOrder, cls.outRotate ) cls.attributeAffects( cls.targetJointOrient, cls.outRotate ) def compute( self, plug, dataBlock ): dh_mirrorTranslation = dataBlock.inputValue( self.mirrorTranslation ) mirrorTranslation = Axis( dh_mirrorTranslation.asShort() ) inWorldMatrix = dataBlock.inputValue( self.inWorldMatrix ).asMatrix() inParentInvMatrix = dataBlock.inputValue( self.inParentMatrixInv ).asMatrix() dh_mirrorAxis = dataBlock.inputValue( self.mirrorAxis ) axis = Axis( dh_mirrorAxis.asShort() ) ### DEAL WITH ROTATION AND POSITION SEPARATELY ### R, S = inWorldMatrix.asPy( 3 ).decompose() #this gets just the 3x3 rotation and scale matrices x, y, z = R #extract basis vectors #mirror the rotation axes and construct the mirrored rotation matrix idxA, idxB = axis.otherAxes() x[ idxA ] = -x[ idxA ] x[ idxB ] = -x[ idxB ] y[ idxA ] = -y[ idxA ] y[ idxB ] = -y[ idxB ] z[ idxA ] = -z[ idxA ] z[ idxB ] = -z[ idxB ] #factor scale back into the matrix mirroredMatrix = Matrix( x + y + z, 3 ) * S mirroredMatrix = mirroredMatrix.expand( 4 ) #now put the rotation matrix in the space of the target object dh_targetParentMatrixInv = dataBlock.inputValue( self.targetParentMatrixInv ) tgtParentMatrixInv = dh_targetParentMatrixInv.asMatrix() matInv = tgtParentMatrixInv.asPy() #put the rotation in the space of the target's parent mirroredMatrix = mirroredMatrix * matInv #if there is a joint orient, make sure to compensate for it tgtJoX = dataBlock.inputValue( self.targetJointOrientX ).asDouble() tgtJoY = dataBlock.inputValue( self.targetJointOrientY ).asDouble() tgtJoZ = dataBlock.inputValue( self.targetJointOrientZ ).asDouble() jo = Matrix.FromEulerXYZ( tgtJoX, tgtJoY, tgtJoZ ) joInv = jo.inverse() joInv = joInv.expand( 4 ) mirroredMatrix = mirroredMatrix * joInv #grab the rotation order of the target rotOrderIdx = dataBlock.inputValue( self.targetRotationOrder ).asInt() #grab euler values R, S = mirroredMatrix.decompose() #we need to decompose again to extract euler angles... eulerXYZ = outX, outY, outZ = mayaRotationOrders[ rotOrderIdx ]( R ) #R.ToEulerYZX() dh_outRX = dataBlock.outputValue( self.outRotateX ) dh_outRY = dataBlock.outputValue( self.outRotateY ) dh_outRZ = dataBlock.outputValue( self.outRotateZ ) #set the rotation dh_outRX.setDouble( outX ) dh_outRY.setDouble( outY ) dh_outRZ.setDouble( outZ ) dataBlock.setClean( plug ) ### NOW DEAL WITH POSITION ### #set the position if mirrorTranslation == self.M_COPY: inLocalMatrix = inWorldMatrix * inParentInvMatrix pos = MPoint( inLocalMatrix(3,0), inLocalMatrix(3,1), inLocalMatrix(3,2) ) elif mirrorTranslation == self.M_INVERT: inLocalMatrix = inWorldMatrix * inParentInvMatrix pos = MPoint( -inLocalMatrix(3,0), -inLocalMatrix(3,1), -inLocalMatrix(3,2) ) elif mirrorTranslation == self.M_MIRROR: pos = MPoint( inWorldMatrix(3,0), inWorldMatrix(3,1), inWorldMatrix(3,2) ) pos = [ pos.x, pos.y, pos.z ] pos[ axis ] = -pos[ axis ] pos = MPoint( *pos ) pos = pos * tgtParentMatrixInv else: return dh_outTX = dataBlock.outputValue( self.outTranslateX ) dh_outTY = dataBlock.outputValue( self.outTranslateY ) dh_outTZ = dataBlock.outputValue( self.outTranslateZ ) dh_outTX.setDouble( pos[0] ) dh_outTY.setDouble( pos[1] ) dh_outTZ.setDouble( pos[2] ) class ControlPairNode(MPxNode): ''' is used by the poseSym tool for storing control pair relationships ''' NODE_ID = OpenMaya.MTypeId( 0x00115941 ) NODE_TYPE_NAME = "controlPair" controlA = MObject() controlB = MObject() axis = MObject() #this is the axis which things get mirrored across flipAxes = MObject() neverDoT = MObject() #if this is true then translation won't get mirrored/swapped neverDoR = MObject() #if this is true then rotation won't get mirrored/swapped neverDoOther = MObject() #if this is true then other keyable attributes won't get mirrored/swapped worldSpace = MObject() #if this is true mirroring is done in world space - otherwise local spaces #these are the values for the flip axes FLIP_AXES = (), (vectors.AX_X, vectors.AX_Y), (vectors.AX_X, vectors.AX_Z), (vectors.AX_Y, vectors.AX_Z) @classmethod def Creator( cls ): return OpenMayaMPx.asMPxPtr( cls() ) @classmethod def Init( cls ): attrMsg = MFnMessageAttribute() cls.controlA = attrMsg.create( "controlA", "ca" ) cls.controlB = attrMsg.create( "controlB", "cb" ) cls.addAttribute( cls.controlA ) cls.addAttribute( cls.controlB ) attrEnum = MFnEnumAttribute() cls.axis = attrEnum.create( "axis", "ax" ) attrEnum.addField( 'x', 0 ) attrEnum.addField( 'y', 1 ) attrEnum.addField( 'z', 2 ) attrEnum.setDefault( 'x' ) attrEnum.setKeyable( False ) attrEnum.setChannelBox( True ) cls.addAttribute( cls.axis ) cls.axis = attrEnum.create( "flipAxes", "flax" ) for n, thisAxes in enumerate( cls.FLIP_AXES ): if thisAxes: enumStr = ''.join( [ ax.asName() for ax in thisAxes ] ) else: enumStr = 'none' attrEnum.addField( enumStr, n ) attrEnum.setKeyable( False ) attrEnum.setChannelBox( True ) cls.addAttribute( cls.axis ) numAttr = MFnNumericAttribute() cls.neverDoT = numAttr.create( "neverDoT", "nvt", MFnNumericData.kBoolean ) cls.neverDoR = numAttr.create( "neverDoR", "nvr", MFnNumericData.kBoolean ) cls.neverDoOther = numAttr.create( "neverDoOther", "nvo", MFnNumericData.kBoolean ) cls.addAttribute( cls.neverDoT ) cls.addAttribute( cls.neverDoR ) cls.addAttribute( cls.neverDoOther ) cls.worldSpace = numAttr.create( "worldSpace", "ws", MFnNumericData.kBoolean, True ) cls.addAttribute( cls.worldSpace ) class CreateMirrorNode(MPxCommand): CMD_NAME = 'rotationMirror' _ARG_SPEC = [ ('-h', '-help', MSyntax.kNoArg, 'prints help'), ('-ax', '-axis', MSyntax.kString, 'the axis to mirror across (defaults to x)'), ('-m', '-translationMode', MSyntax.kString, 'the mode in which translation is mirrored - %s (defaults to %s)' % (' '.join( MirrorNode.MIRROR_MODE_NAMES ), MirrorNode.MIRROR_MODE_NAMES[ MirrorNode.MIRROR_DEFAULT ])), ('-d', '-dummy', MSyntax.kNoArg, "builds the node but doesn't hook it up to the target - this can be useful if you want to query what would be mirrored transform"), #('-s', '-space', MSyntax.kString, 'which space to mirror in - world or local (defaults to world)') ] ] kFlagHelp = _ARG_SPEC[ 0 ][ 0 ] kFlagAxis = _ARG_SPEC[ 1 ][ 0 ] kFlagMode = _ARG_SPEC[ 2 ][ 0 ] kFlagDummy = _ARG_SPEC[ 3 ][ 0 ] @classmethod def SyntaxCreator( cls ): syntax = OpenMaya.MSyntax() for shortFlag, longFlag, syntaxType, h in cls.IterArgSpec(): syntax.addFlag( shortFlag, longFlag, syntaxType ) syntax.useSelectionAsDefault( True ) syntax.setObjectType( MSyntax.kSelectionList, 1, 3 ) syntax.enableQuery( True ) syntax.enableEdit( True ) return syntax @classmethod def Creator( cls ): return OpenMayaMPx.asMPxPtr( cls() ) @classmethod def IterArgSpec( cls ): for data in cls._ARG_SPEC: if len( data ) != 4: yield data + ('<no help available>',) else: yield data def grabArgDb( self, mArgs ): try: argData = MArgDatabase( self.syntax(), mArgs ) except RuntimeError: return True, None if argData.isFlagSet( self.kFlagHelp ): self.printHelp() return True, None return False, argData def printHelp( self ): longestFlag = 5 for shortFlag, longFlag, syntaxType, h in self.IterArgSpec(): longestFlag = max( longestFlag, len(longFlag) ) self.displayInfo( '%s - USAGE' % self.CMD_NAME ) printStr = '*%5s %'+ str( longestFlag ) +'s: %s' for shortFlag, longFlag, syntaxType, h in self.IterArgSpec(): self.displayInfo( printStr % (shortFlag, longFlag, h) ) def doIt( self, mArgs ): ret, argData = self.grabArgDb( mArgs ) if ret: return sel = OpenMaya.MSelectionList() argData.getObjects( sel ) objs = [] for n in range( sel.length() ): obj = MObject() sel.getDependNode( n, obj ) objs.append( obj ) # if argData.isQuery(): rotNode = objs[0] if argData.isFlagSet( self.kFlagAxis ): self.setResult( cmd.getAttr( '%s.mirrorAxis' % rotNode ) ) elif argData.isFlagSet( self.kFlagMode ): self.setResult( cmd.getAttr( '%s.mirrorTranslation' % rotNode ) ) return #if we're in edit mode, find the node elif argData.isEdit(): rotNode = objs[0] #otherwise we're in creation mode - so build the node and connect things up else: obj, tgt = objs #is dummy mode set? isDummyMode = argData.isFlagSet( self.kFlagDummy ) or argData.isFlagSet( self.kFlagDummy ) #see if there is already a node connected existing = cmd.listConnections( '%s.t' % tgt, '%s.r' % tgt, type=MirrorNode.NODE_TYPE_NAME ) if existing: self.displayWarning( "There is a %s node already connected - use edit mode!" % MirrorNode.NODE_TYPE_NAME ) self.setResult( existing[ 0 ] ) return else: rotNode = cmd.createNode( 'rotationMirror' ) cmd.connectAttr( '%s.worldMatrix' % obj, '%s.inWorldMatrix' % rotNode ) cmd.connectAttr( '%s.parentInverseMatrix' % obj, '%s.inParentInverseMatrix' % rotNode ) cmd.connectAttr( '%s.parentInverseMatrix' % tgt, '%s.targetParentInverseMatrix' % rotNode ) joAttrpath = '%s.jo' % tgt if cmd.objExists( joAttrpath ): cmd.connectAttr( joAttrpath, '%s.targetJointOrient' % rotNode ) cmd.connectAttr( '%s.rotateOrder' % tgt, '%s.targetRotationOrder' % rotNode ) if not isDummyMode: cmd.connectAttr( '%s.outTranslate' % rotNode, '%s.t' % tgt ) cmd.connectAttr( '%s.outRotate' % rotNode, '%s.r' % tgt ) cmd.select( obj ) #set the result to the node created... self.setResult( rotNode ) #set any attributes passed in from the command-line if argData.isFlagSet( self.kFlagAxis ): axisInt = Axis.FromName( argData.flagArgumentString( self.kFlagAxis, 0 ) ) cmd.setAttr( '%s.mirrorAxis' % rotNode, axisInt ) if argData.isFlagSet( self.kFlagMode ): modeStr = argData.flagArgumentString( self.kFlagMode, 0 ) modeIdx = list( MirrorNode.MIRROR_MODE_NAMES ).index( modeStr ) cmd.setAttr( '%s.mirrorTranslation' % rotNode, modeIdx ) def undoIt( self ): pass def isUndoable( self ): return True def initializePlugin( mobject ): mplugin = OpenMayaMPx.MFnPlugin( mobject, 'macaronikazoo', '1' ) try: mplugin.registerNode( MirrorNode.NODE_TYPE_NAME, MirrorNode.NODE_ID, MirrorNode.Creator, MirrorNode.Init ) mplugin.registerNode( ControlPairNode.NODE_TYPE_NAME, ControlPairNode.NODE_ID, ControlPairNode.Creator, ControlPairNode.Init ) mplugin.registerCommand( CreateMirrorNode.CMD_NAME, CreateMirrorNode.Creator, CreateMirrorNode.SyntaxCreator ) mplugin.registerCommand( CreateMirrorNode.CMD_NAME.lower(), CreateMirrorNode.Creator, CreateMirrorNode.SyntaxCreator ) except: MGlobal.displayError( "Failed to load zooMirror plugin:" ) raise def uninitializePlugin( mobject ): mplugin = OpenMayaMPx.MFnPlugin( mobject ) try: mplugin.deregisterNode( MirrorNode.NODE_ID ) mplugin.deregisterNode( ControlPairNode.NODE_ID ) mplugin.deregisterCommand( CreateMirrorNode.CMD_NAME ) mplugin.deregisterCommand( CreateMirrorNode.CMD_NAME.lower() ) except: MGlobal.displayError( "Failed to unload zooMirror plugin:" ) raise #end
Python
import maya.OpenMaya as OpenMaya import maya.OpenMayaMPx as OpenMayaMPx AUTHOR = '-:macaroniKazoo:-' VERSION = '1.0' NODE_NAME = 'twister' ID = OpenMaya.MTypeId( 0x43899 ) class twister( OpenMayaMPx.MPxNode ): aInWorldMatrixA = OpenMaya.MObject() aInWorldMatrixB = OpenMaya.MObject() aAxisA = OpenMaya.MObject() aAxisB = OpenMaya.MObject() aDivider = OpenMaya.MObject() aOutRotate = OpenMaya.MObject() aOutRotateX = OpenMaya.MObject() aOutRotateY = OpenMaya.MObject() aOutRotateZ = OpenMaya.MObject() def __init__( self ): OpenMayaMPx.MPxNode.__init__(self) def compute( self, plug, data ): if plug == self.aOutRotate or plug == self.aOutRotateX or plug == self.aOutRotateY or plug == self.aOutRotateZ: #get handles to the attributes hInWorldMatrixA = data.inputValue(self.aInWorldMatrixA) matWorldA = hInWorldMatrixA.asMatrix() matWorldAinv = matWorldA.inverse() hInWorldMatrixB = data.inputValue(self.aInWorldMatrixB) matWorldB = hInWorldMatrixB.asMatrix() hAxisA = data.inputValue(self.aAxisA) nAxisA = hAxisA.asShort() hAxisB = data.inputValue(self.aAxisB) nAxisB = hAxisB.asShort() hDivider = data.inputValue(self.aDivider) dDivider = hDivider.asDouble() #build the vectors to compare axes = OpenMaya.MVector(1,0,0),OpenMaya.MVector(0,1,0),OpenMaya.MVector(0,0,1) #any index above 2 is just one of the first 3 axes negated - so deal with it vVecA = OpenMaya.MVector( axes[nAxisA%3] ) #make a copy of the vectors vVecB = OpenMaya.MVector( axes[nAxisB%3] ) if nAxisA > 2: vVecA *= -1 if nAxisB > 2: vVecB *= -1 #put the B vector into the space of inputA so we can meaningfully compare them to get an angle between vVecB *= matWorldB vVecB *= matWorldAinv #finally grab the rotation between them and push it out to outRotate qRotBetween = OpenMaya.MQuaternion(vVecA,vVecB,(1/dDivider)) asEuler = qRotBetween.asEulerRotation() #grab the output attribute handles and set their values hOutRotateX = data.outputValue( self.aOutRotateX ) hOutRotateY = data.outputValue( self.aOutRotateY ) hOutRotateZ = data.outputValue( self.aOutRotateZ ) hOutRotateX.setDouble( asEuler.x ) hOutRotateY.setDouble( asEuler.y ) hOutRotateZ.setDouble( asEuler.z ) #mark all attributes as clean data.setClean(self.aOutRotate) data.setClean(self.aOutRotateX) data.setClean(self.aOutRotateY) data.setClean(self.aOutRotateZ) else: return OpenMaya.MStatus.kUnknownParameter return OpenMaya.MStatus.kSuccess def initializePlugin( mObject ): mPlugin = OpenMayaMPx.MFnPlugin( mObject, AUTHOR, VERSION, "Any" ) mPlugin.registerNode( NODE_NAME, ID, nodeCreator, nodeInitializer ) def uninitializePlugin( mObject ): plugin = OpenMayaMPx.MFnPlugin( mObject ) plugin.deregisterNode( ID ) def nodeCreator(): return OpenMayaMPx.asMPxPtr( twister() ) def nodeInitializer(): nAttr = OpenMaya.MFnNumericAttribute() mAttr = OpenMaya.MFnMatrixAttribute() eAttr = OpenMaya.MFnEnumAttribute() cAttr = OpenMaya.MFnCompoundAttribute() twister.aInWorldMatrixA = mAttr.create( "inWorldMatrixA", "iwma" ) twister.aInWorldMatrixB = mAttr.create( "inWorldMatrixB", "iwmb" ) twister.aAxisA = eAttr.create("axisA", "axa", 0 ) eAttr.setChannelBox(True) eAttr.setKeyable(True) eAttr.addField( "X", 0 ) eAttr.addField( "Y", 1 ) eAttr.addField( "Z", 2 ) eAttr.addField( "-X", 3 ) eAttr.addField( "-Y", 4 ) eAttr.addField( "-Z", 5 ) twister.aAxisB = eAttr.create("axisB", "axb", 0 ) eAttr.setChannelBox(True) eAttr.setKeyable(True) eAttr.addField( "X", 0 ) eAttr.addField( "Y", 1 ) eAttr.addField( "Z", 2 ) eAttr.addField( "-X", 3 ) eAttr.addField( "-Y", 4 ) eAttr.addField( "-Z", 5 ) twister.aDivider = nAttr.create( "divider", "div", OpenMaya.MFnNumericData.kDouble, 1 ) nAttr.setMin(0.001) nAttr.setChannelBox(True) nAttr.setKeyable(True) twister.aOutRotateX = nAttr.create( "outRotateX", "orx", OpenMaya.MFnNumericData.kDouble, 0.0 ) twister.aOutRotateY = nAttr.create( "outRotateY", "ory", OpenMaya.MFnNumericData.kDouble, 0.0 ) twister.aOutRotateZ = nAttr.create( "outRotateZ", "orz", OpenMaya.MFnNumericData.kDouble, 0.0 ) twister.aOutRotate = cAttr.create( "outRotate", "or") cAttr.addChild( twister.aOutRotateX ) cAttr.addChild( twister.aOutRotateY ) cAttr.addChild( twister.aOutRotateZ ) twister.addAttribute( twister.aInWorldMatrixA ) twister.addAttribute( twister.aInWorldMatrixB ) twister.addAttribute( twister.aAxisA ) twister.addAttribute( twister.aAxisB ) twister.addAttribute( twister.aDivider ) twister.addAttribute( twister.aOutRotate ) #setup dependency relationships twister.attributeAffects( twister.aInWorldMatrixA, twister.aOutRotate ) twister.attributeAffects( twister.aInWorldMatrixB, twister.aOutRotate ) twister.attributeAffects( twister.aDivider, twister.aOutRotate ) twister.attributeAffects( twister.aAxisB, twister.aOutRotate ) twister.attributeAffects( twister.aAxisB, twister.aOutRotate )
Python
from maya.cmds import * from maya import cmds as cmd from filesystem import Path from baseMelUI import * import os import api import names import skeletonBuilderPresets import rigPrimitives import baseRigPrimitive import rigUtils import control import meshUtils import baseMelUI import presetsUI import skinWeightsUI import spaceSwitchingUI Axis = rigUtils.Axis class Callback(object): ''' stupid little callable object for when you need to "bake" temporary args into a callback - useful mainly when creating callbacks for dynamicly generated UI items ''' def __init__( self, func, *args, **kwargs ): self.func = func self.args = args self.kwargs = kwargs def __call__( self, *args ): return self.func( *self.args, **self.kwargs ) #stores UI build methods keyed by arg name UI_FOR_NAMED_RIG_ARGS = {} SkeletonPart = rigPrimitives.SkeletonPart ShapeDesc = control.ShapeDesc class ListEditor(BaseMelWindow): WINDOW_NAME = 'parentsEditor' WINDOW_TITLE = 'Edit Custom Parents' DEFAULT_SIZE = 275, 300 DEFAULT_MENU = None FORCE_DEFAULT_SIZE = True def __new__( self, theList, changeCB ): return BaseMelWindow.__new__( self ) def __init__( self, theList, storage ): BaseMelWindow.__init__( self ) f = MelForm( self ) self.add = MelButton( f, l='add selected item', c=self.on_add ) self.rem = MelButton( f, l='remove highlighted items', c=self.on_rem ) self.scroll = MelTextScrollList( f ) self.scroll.setItems( theList ) self.storage = storage f( e=True, af=((self.add, 'top', 0), (self.add, 'left', 0), (self.rem, 'top', 0), (self.rem, 'right', 0), (self.scroll, 'left', 0), (self.scroll, 'right', 0), (self.scroll, 'bottom', 0)), ap=((self.add, 'right', 0, 45), (self.rem, 'left', 0, 45)), ac=((self.scroll, 'top', 0, self.add)) ) ### EVENT HANDLERS ### def on_add( self, *a ): sel = cmd.ls( sl=True ) if sel: self.scroll.appendItems( sel ) self.storage.setValue( self.scroll.getItems() ) self.storage.cb() def on_rem( self, *a ): self.scroll.removeSelectedItems() self.storage.setValue( self.scroll.getItems() ) self.storage.cb() class MelListEditorButton(MelButton): def __init__( self, parent, *a, **kw ): MelButton.__init__( self, parent, *a, **kw ) self.setChangeCB( self.openEditor ) self.setLabel( 'define parents' ) def setValue( self, value, executeChangeCB=False ): self.value = value def getValue( self ): return self.value def setChangeCB( self, cb ): self.cb = cb def openEditor( self, *a ): win = ListEditor( self.value, self ) win.show() #hook up list/tuple types to a button - we don't want a text scroll list showing up in the part UI, but a button to bring up said editor is fine UI_FOR_PY_TYPES[ list ] = MelListEditorButton UI_FOR_PY_TYPES[ tuple ] = MelListEditorButton class MelFileBrowser(MelHLayout): def __init__( self, parent, *a, **kw ): self.UI_filepath = MelTextField( self ) self.UI_browse = MelButton( self, l='browse', c=self.on_browse, w=50 ) self.setWeight( self.UI_browse, 0 ) self.layout() def enable( self, state ): self.UI_filepath.enable( state ) self.UI_browse.enable( state ) def setValue( self, value, executeChangeCB=False ): ''' the value we recieve should be a fullpath - but we want to store is as a scene relative path ''' value = Path( value ) #make sure it is actually an absolute path... if value.isAbs(): curSceneDir = Path( cmd.file( q=True, sn=True ) ).up() value = value - curSceneDir self.UI_filepath.setValue( value, executeChangeCB ) def getValue( self ): ''' return as an absolute path ''' return Path( cmd.file( q=True, sn=True ) ).up() / self.UI_filepath.getValue() def setChangeCB( self, cb ): self.UI_filepath.setChangeCB( cb ) ### EVENT HANDLERS ### def on_browse( self, *a ): curValue = self.getValue() ext = curValue.getExtension() or 'txt' if curValue.isFile(): curValue = curValue.up() elif not curValue.isDir(): curValue = Path( cmd.file( q=True, sn=True ) ).up( 2 ) if not curValue.exists(): curValue = Path( '' ) filepath = cmd.fileDialog( directoryMask=curValue / ("/*.%s" % ext) ) if filepath: self.setValue( filepath, True ) baseMelUI.UI_FOR_PY_TYPES[ Path ] = MelFileBrowser class MelOptionMenu_SkeletonPart(MelOptionMenu): PART_CLASS = SkeletonPart def __new__( cls, parent, *a, **kw ): self = MelOptionMenu.__new__( cls, parent, *a, **kw ) self.populate() return self def populate( self ): self.clear() for part in self.PART_CLASS.IterAllParts(): self.append( part.end ) def setValue( self, value, executeChangeCB=True ): if type( value ) is type: return return MelOptionMenu.setValue( self, value, executeChangeCB ) def getValue( self ): value = MelOptionMenu.getValue( self ) return self.PART_CLASS.InitFromItem( value ) class MelOptionMenu_Arm(MelOptionMenu_SkeletonPart): PART_CLASS = rigPrimitives.SkeletonPart.GetNamedSubclass( 'Arm' ) class MelOptionMenu_Shape(MelOptionMenu): def __new__( cls, parent, *a, **kw ): self = MelOptionMenu.__new__( cls, parent, *a, **kw ) self.populate() return self def populate( self ): self.clear() for shapeName in sorted( rigPrimitives.CONTROL_SHAPE_DICT.keys() ): self.append( shapeName ) def setValue( self, value, executeChangeCB=True ): if type( value ) is type: return if isinstance( value, ShapeDesc ): value = value.surfaceType return MelOptionMenu.setValue( self, value, executeChangeCB ) def getValue( self ): value = MelOptionMenu.getValue( self ) return ShapeDesc( value ) class MelOptionMenu_Axis(MelOptionMenu): def __new__( cls, parent, *a, **kw ): self = MelOptionMenu.__new__( cls, parent, *a, **kw ) self.populate() return self def populate( self ): self.clear() for shapeName in sorted( Axis.AXES ): self.append( shapeName ) def setValue( self, value, executeChangeCB=True ): if type( value ) is type: return if isinstance( value, Axis ): value = value.asName() return MelOptionMenu.setValue( self, value, executeChangeCB ) #define some UI mappings based on arg types/names... baseMelUI.UI_FOR_PY_TYPES[ rigPrimitives.SkeletonPart ] = MelOptionMenu_SkeletonPart baseMelUI.UI_FOR_PY_TYPES[ MelOptionMenu_Arm.PART_CLASS ] = MelOptionMenu_Arm baseMelUI.UI_FOR_PY_TYPES[ ShapeDesc ] = MelOptionMenu_Shape UI_FOR_NAMED_RIG_ARGS[ 'axis' ] = MelOptionMenu_Axis UI_FOR_NAMED_RIG_ARGS[ 'direction' ] = MelOptionMenu_Axis setParent = cmd.setParent class SeparatorLabelLayout(MelForm): def __init__( self, parent, label ): MelForm.__init__( self, parent ) self.UI_label = MelLabel( self, label=label, align='left' ) setParent( self ) self.UI_separator = cmd.separator( horizontal=True ) self( e=True, af=((self.UI_label, 'left', 0), (self.UI_separator, 'top', 6), (self.UI_separator, 'right', 0)), ac=((self.UI_separator, 'left', 5, self.UI_label)) ) class SkeletonPresetWindow(presetsUI.PresetWindow): def __init__( self ): presetsUI.PresetWindow.__init__( self, rigPrimitives.TOOL_NAME, ext=skeletonBuilderPresets.XTN ) def presetsCopied( self, presets ): for layout in BuildingLayout.IterInstances(): layout.rePopulatePresets() def presetsDeleted( self, presets ): for layout in BuildingLayout.IterInstances(): layout.rePopulatePresets() def presetsMoved( self, presets ): for layout in BuildingLayout.IterInstances(): layout.rePopulatePresets() def presetRenamed( self, preset, renamedPreset ): for layout in BuildingLayout.IterInstances(): layout.rePopulatePresets() class SkeletonPresetLayout(MelHSingleStretchLayout): BUTTON_LBL_TEMPLATE = 'Build a %s Preset' def __new__( cls, parent, preset ): return MelHSingleStretchLayout.__new__( cls, parent ) def __init__( self, parent, preset ): MelHSingleStretchLayout.__init__( self, parent ) self.preset = preset MelButton( self, l=names.camelCaseToNice( preset.name() ), c=self.on_load, w=160 ) spac = MelSpacer( self ) MelButton( self, l='Overwrite', c=self.on_overwrite, w=100 ) if preset.locale == presetsUI.LOCAL: self.UI_publish = MelButton( self, l='Publish', c=self.on_publish, w=100 ) #MelButton( self, l='Delete', c=self.on_remove, w=100 ) self.setStretchWidget( spac ) self.layout() def on_load( self, *a ): skeletonBuilderPresets.loadPresetFile( self.preset ) def on_overwrite( self, *a ): BUTTONS = OK, CANCEL = 'Ok', 'Cancel' ret = confirmDialog( t='Are You Sure?', m='Are you sure you want to overwrite the preset %s?' % self.preset.name(), b=BUTTONS, db=CANCEL ) if ret == CANCEL: return skeletonBuilderPresets.writePresetToFile( self.preset ) def on_publish( self, *a ): raise NotImplemented( "you need to define this yourself!" ) #movedPreset = self.preset.move() #self.preset = movedPreset #self.UI_publish.delete() #self.layout() #p4 = P4File() #change = p4.getChangeNumFromDesc( '%s skeleton builder preset publish submission' % movedPreset.name() ) #p4.setChange( change, movedPreset ) #p4.submit( change ) #print 'submitted %s' % movedPreset def on_remove( self, *a ): pass class SkeletonPartOptionMenu(MelOptionMenu): DYNAMIC = False STATIC_CHOICES = [ partCls.__name__ for partCls in SkeletonPart.GetSubclasses() if partCls.AVAILABLE_IN_UI ] class ManualPartCreationLayout(MelHSingleStretchLayout): def __init__( self, parent, *a, **kw ): MelHSingleStretchLayout.__init__( self, parent, *a, **kw ) self.UI_partType = SkeletonPartOptionMenu( self ) self.UI_convert = MelButton( self, l='Convert Selection To Skeleton Part', c=self.on_convert ) self.setSelectionChangeCB( self.on_selectionChange ) self.setStretchWidget( self.UI_convert ) self.layout() self.on_selectionChange() ### EVENT HANDLERS ### def on_convert( self, *a ): partTypeStr = self.UI_partType.getValue() partType = SkeletonPart.GetNamedSubclass( partTypeStr ) sel = cmd.ls( sl=True ) newPart = partType( rigPrimitives.buildSkeletonPartContainer( partType, {}, sel ) ) newPart.convert( {} ) self.sendEvent( 'manualPartCreated', newPart ) def on_selectionChange( self, *a ): sel = cmd.ls( sl=True ) if not sel: self.UI_convert.disable() else: self.UI_convert.enable() class CommonButtonsLayout(MelColumn): def __init__( self, parent ): MelColumn.__init__( self, parent, rowSpacing=4, adj=True ) ### SETUP PART DRIVING RELATIONSHIPS SeparatorLabelLayout( self, 'Part Connection Controls' ) buttonForm = MelHLayout( self ) MelButton( buttonForm, l='Drive All Parts', c=self.on_allDrive ) MelButton( buttonForm, l='Drive Parts With First Selected', c=self.on_drive ) MelButton( buttonForm, l='Break Driver For Selected', c=self.on_breakDrive ) MelButton( buttonForm, l='Break All Drivers', c=self.on_breakAllDrive ) buttonForm.layout() ### SETUP VISUALIZATION CONTROLS SeparatorLabelLayout( self, 'Visualization' ) buttonForm = MelHLayout( self ) MelButton( buttonForm, l='Visualization ON', c=self.on_visOn ) MelButton( buttonForm, l='Visualization OFF', c=self.on_visOff ) buttonForm.layout() ### SETUP ALIGNMENT CONTROL BUTTONS SeparatorLabelLayout( self, 'Part Alignment' ) buttonForm = MelHLayout( self ) MelButton( buttonForm, l='Re-Align Selected Part', c=self.on_reAlign ) MelButton( buttonForm, l='Re-Align ALL Parts', c=self.on_reAlignAll ) MelButton( buttonForm, l='Finalize Alignment', c=self.on_finalize ) buttonForm.layout() ### SETUP SKINNING CONTROL BUTTONS skinFrame = MelFrameLayout( self, l='Skinning Tools', cl=True, cll=True, bs='etchedOut' ) skinCol = MelColumnLayout( skinFrame ) buttonForm = MelHLayout( skinCol ) self.UI_skinOff = MelButton( buttonForm, l='Turn Skinning Off', c=self.on_skinOff ) self.UI_skinOn = MelButton( buttonForm, l='Turn Skinning On', c=self.on_skinOn ) MelButton( buttonForm, l='Reset All Skin Clusters', c=self.on_resetSkin ) buttonForm.layout() self.updateSkinButtons() ### SETUP VOLUME BUILDER CONTROL BUTTONS SeparatorLabelLayout( skinCol, 'Volume Tools' ) buttonForm = MelHLayout( skinCol ) MelButton( buttonForm, l='Create Volumes', c=self.on_buildVolumes ) MelButton( buttonForm, l='Extract Selected To Volume', c=self.on_extractSelected ) MelButton( buttonForm, l='Fit Selected Volumes', c=self.on_fitVolumes ) MelButton( buttonForm, l='Remove Volumes', c=self.on_removeVolumes ) buttonForm.layout() buttonForm = MelHLayout( skinCol ) MelButton( buttonForm, l='Open Skin Weights Tool', c=lambda *a: skinWeightsUI.SkinWeightsWindow() ) MelButton( buttonForm, l='Generate Skin Weights', c=self.on_generateWeights ) buttonForm.layout() self.setSceneChangeCB( self.on_sceneOpen ) def updateSkinButtons( self ): state = rigUtils.getSkinClusterEnableState() self.UI_skinOn( e=True, en=not state ) self.UI_skinOff( e=True, en=state ) def on_allDrive( self, e=None ): rigPrimitives.setupAutoMirror() def on_drive( self, e=None ): selParts = rigPrimitives.getPartsFromObjects( cmd.ls( sl=True ) ) if len( selParts ) <= 1: print 'WARNING :: please select two or more parts - the first part selected will drive consequent parts' return firstPart = selParts.pop( 0 ) for p in selParts: firstPart.driveOtherPart( p ) def on_breakDrive( self, e=None ): for p in rigPrimitives.getPartsFromObjects( cmd.ls( sl=True ) ): p.breakDriver() def on_breakAllDrive( self, e=None ): for p in rigPrimitives.SkeletonPart.IterAllParts(): p.breakDriver() def on_reAlign( self, e=None ): rigPrimitives.realignSelectedParts() def on_reAlignAll( self, e=None ): rigPrimitives.realignAllParts() def on_finalize( self, e=None ): rigPrimitives.finalizeAllParts() def on_visOn( self, e=None ): for p in rigPrimitives.SkeletonPart.IterAllParts(): p.visualize() def on_visOff( self, e=None ): for p in rigPrimitives.SkeletonPart.IterAllParts(): p.unvisualize() def on_skinOff( self, e=None ): rigUtils.disableSkinClusters() self.updateSkinButtons() def on_skinOn( self, e=None ): rigUtils.enableSkinClusters() self.updateSkinButtons() @api.d_showWaitCursor def on_resetSkin( self, e=None ): for sc in ls( typ='skinCluster' ): rigUtils.resetSkinCluster( sc ) def on_buildVolumes( self, e=None ): rigPrimitives.buildAllVolumes() def on_fitVolumes( self, e=None ): rigPrimitives.shrinkWrapSelection() def on_removeVolumes( self, e=None ): rigPrimitives.removeAllVolumes() def on_extractSelected( self, e=None ): cmd.select( meshUtils.extractFaces( cmd.ls( sl=True, fl=True ) ) ) api.mel.setSelectMode( "objects", "Objects" ) def on_generateWeights( self, e=None ): rigPrimitives.volumesToSkinning() def on_sceneOpen( self, *a ): self.updateSkinButtons() class BuildPartLayout(MelForm): ''' ui for single skeleton part creation ''' ABBRVS_TO_EXPAND = names.ABBRVS_TO_EXPAND.copy() ABBRVS_TO_EXPAND[ 'idx' ] = 'index' BUTTON_LBL_TEMPLATE = 'Create %s' def __new__( cls, parent, partClass ): return MelForm.__new__( cls, parent ) def __init__( self, parent, partClass ): MelForm.__init__( self, parent ) self.partClass = partClass self.UI_create = cmd.button( l=self.BUTTON_LBL_TEMPLATE % names.camelCaseToNice( partClass.GetPartName() ), c=self.on_create, w=160 ) #now populate the ui for the part's args self.kwarg_UIs = {} #keyed by arg name kwargList = partClass.GetDefaultBuildKwargList() self.UI_argsLayout = MelForm( self ) #everything has a parent attribute, so build it first prevUI = None for arg, default in kwargList: #skip UI for parent - assume selection always if arg == 'parent': continue setParent( self.UI_argsLayout ) lbl = cmd.text( l=names.camelCaseToNice( arg, self.ABBRVS_TO_EXPAND ) ) #determine the function to use for building the UI for the arg buildMethodFromName = UI_FOR_NAMED_RIG_ARGS.get( arg, None ) buildMethodFromType = getBuildUIMethodForObject( default ) or MelTextField buildMethod = buildMethodFromName or buildMethodFromType self.kwarg_UIs[ arg ] = argUI = buildMethod( self.UI_argsLayout ) argUI.setValue( default ) #perform layout if prevUI is None: self.UI_argsLayout( e=True, af=((lbl, 'left', 15)) ) else: self.UI_argsLayout( e=True, ac=((lbl, 'left', 15, prevUI)) ) if isinstance( argUI, MelCheckBox ): self.UI_argsLayout( e=True, af=((argUI, 'top', 3)) ) self.UI_argsLayout( e=True, af=((lbl, 'top', 3)), ac=((argUI, 'left', 5, lbl)) ) prevUI = argUI setParent( self ) self( e=True, af=((self.UI_create, 'left', 0), (self.UI_argsLayout, 'right', 0)), ac=((self.UI_argsLayout, 'left', 0, self.UI_create)) ) def getKwargDict( self ): kwargs = {} for arg, ui in self.kwarg_UIs.iteritems(): kwargs[ arg ] = ui.getValue() if kwargs.has_key( 'parent' ): if not kwargs[ 'parent' ]: kwargs[ 'parent' ] = None kwargs[ 'partScale' ] = rigPrimitives.getScaleFromSkeleton() return kwargs def rePopulate( self ): for argName, ui in self.kwarg_UIs.iteritems(): if isinstance( ui, MelOptionMenu_SkeletonPart ): ui.populate() def on_create( self, e ): kwargs = self.getKwargDict() self.partClass.Create( **kwargs ) self.sendEvent( 'rePopulate' ) class BuildingLayout(MelScrollLayout): ''' ui for skeleton part creation ''' def __init__( self, parent ): MelScrollLayout.__init__( self, parent, childResizable=True ) self.UI_col = col = MelColumnLayout( self, rowSpacing=4, adj=True ) MelLabel( col, l='Create Skeleton from Preset', align='left' ) MelLabel( col, l='', height=5 ) ### BUILD THE PRESET CREATION BUTTONS ### self.UI_presetsCol = MelColumnLayout( col ) self.rePopulatePresets() hLayout = MelHLayout( col ) MelButton( hLayout, l='Create Preset', c=self.on_createPreset ) MelButton( hLayout, l='Manage Presets', c=self.on_managePresets ) hLayout.layout() MelSeparator( col, horizontal=True ) MelLabel( col, l='Build Individual Parts', align='left' ) MelLabel( col, l='', height=5 ) ### BUILD THE PART CREATION BUTTONS ### self.UI_list = [] parts = SkeletonPart.GetSubclasses() for part in parts: if part.AVAILABLE_IN_UI: self.UI_list.append( BuildPartLayout( col, part ) ) #### BUILD UI FOR MANUAL PART CREATION ### #MelSeparator( self.UI_col ) #MelLabel( self.UI_col, l='Manually Create Part From Existing Joints', align='left' ) #MelLabel( self.UI_col, l='', height=2 ) #ManualPartCreationLayout( self.UI_col ) def rePopulate( self ): for ui in self.UI_list: ui.rePopulate() def rePopulatePresets( self ): self.UI_presetsCol.clear() for locale, presets in skeletonBuilderPresets.listPresets().iteritems(): for preset in presets: SkeletonPresetLayout( self.UI_presetsCol, preset ) def on_createPreset( self, *a ): BUTTONS = OK, CANCEL = 'Ok', 'Cancel' ret = promptDialog( t='Preset Name', m='Enter the name for the preset', b=BUTTONS, db=OK ) if ret == OK: name = promptDialog( q=True, tx=True ) assert name, "Please enter a name!" preset = skeletonBuilderPresets.writePreset( name ) SkeletonPresetLayout( self.UI_presetsCol, preset ) def on_managePresets( self, *a ): SkeletonPresetWindow() class EditPartLayout(MelForm): ARGS_TO_HIDE = [ 'parent', 'partScale', 'idx' ] def __new__( cls, parent, part ): return MelForm.__new__( cls, parent ) def __init__( self, parent, part ): MelForm.__init__( self, parent ) self.part = part self.argUIs = {} self.populate() def clear( self ): MelForm.clear( self ) self.argUIs = {} def populate( self ): #remove any existing children self.clear() part = self.part assert isinstance( part, SkeletonPart ) #pimp out the UI lbl = MelButton( self, l=part.getPartName(), w=140, c=self.on_select ) #grab the args the rigging method takes argsForm = MelForm( self ) argsUIs = [] buildKwargs = part.getBuildKwargs() for arg in self.ARGS_TO_HIDE: buildKwargs.pop( arg, None ) for arg, argValue in buildKwargs.iteritems(): argLbl = MelLabel( argsForm, label=names.camelCaseToNice( arg ) ) #determine the function to use for building the UI for the arg buildMethodFromName = UI_FOR_NAMED_RIG_ARGS.get( arg, None ) buildMethodFromType = getBuildUIMethodForObject( argValue ) or MelTextField buildMethod = buildMethodFromName or buildMethodFromType #prioritize the method from name over the method from type argWidget = buildMethod( argsForm ) argWidget.setValue( argValue ) argsUIs.append( argLbl ) argsUIs.append( argWidget ) self.argUIs[ arg ] = argWidget try: inc = 1.0 / len( argsUIs ) except ZeroDivisionError: inc = 1.0 for n, ui in enumerate( argsUIs ): p = n*inc if n: argsForm( e=True, ac=((ui, 'left', 5, argsUIs[ n-1 ])) ) else: argsForm( e=True, af=((ui, 'left', 0)) ) #finally build the "rebuild" button reButt = MelButton( self, l="rebuild", c=self.on_rebuild, w=100 ) #perform layout... self.setWidth( 50 ) argsForm.setWidth( 50 ) self( e=True, af=((lbl, 'left', 0), (reButt, 'right', 0)), ac=((argsForm, 'left', 5, lbl), (argsForm, 'right', 0, reButt)) ) def getBuildKwargs( self ): kwargs = {} for argName, widget in self.argUIs.iteritems(): kwargs[ argName ] = widget.getValue() return kwargs def on_rebuild( self, e ): self.part.rebuild( **self.getBuildKwargs() ) self.populate() def on_select( self, e=None ): cmd.select( self.part.items ) class EditingLayout(MelScrollLayout): def __init__( self, parent ): MelScrollLayout.__init__( self, parent, childResizable=True ) def populate( self ): self.clear() col = MelColumn( self, rowSpacing=4, adj=True ) self.UI_partForms = [] for part in SkeletonPart.IterAllPartsInOrder(): partRigForm = EditPartLayout( col, part ) self.UI_partForms.append( partRigForm ) class RigPartLayout(MelForm): ''' ui for single rig primitive ''' def __new__( cls, parent, part ): return MelForm.__new__( cls, parent ) def __init__( self, parent, part ): MelForm.__init__( self, parent ) self.part = part self.argUIs = {} lbl = MelButton( self, l=part.getPartName(), w=140, c=self.on_select ) rigKwargs = part.getRigKwargs() #build the disable and optionbox for the rig method disableState = rigKwargs.get( 'disable', False ) disable = self.UI_disable = MelCheckBox( self, l='disable' ) rigTypes = self.rigTypes = [ rigType for rigType in part.RigTypes if rigType.CanRigThisPart( part ) ] if len( rigTypes ) > 1: opts = MelOptionMenu( self, cc=self.on_rigMethodCB ) opts.enable( not disableState ) for method in rigTypes: opts.append( method.__name__ ) rigMethodName = rigKwargs.get( 'rigMethodName', rigTypes[ 0 ].__name__ ) if rigMethodName in opts.getItems(): opts.selectByValue( rigMethodName, False ) else: opts = MelLabel( self, l='' ) self.UI_options = opts argsForm = self.UI_argsForm = MelHRowLayout( self ) self.UI_manualRig = manRig = MelButton( self ) self.updateBuildRigButton() #perform layout... self( e=True, af=((lbl, 'left', 0), (manRig, 'right', 0)), ac=((disable, 'left', 3, lbl), (opts, 'left', 0, disable), (argsForm, 'left', 0, opts), (argsForm, 'right', 0, manRig)) ) #set initial UI state disable.setChangeCB( self.on_argCB ) disable.setValue( disableState, False ) self.populate() def clearArgs( self ): self.UI_argsForm.clear() self.argUIs = {} def populate( self ): if not bool( self.rigTypes ): self.setVisibility( False ) return #remove any existing children self.clearArgs() part = self.part rigKwargs = part.getRigKwargs() #build the disable and optionbox for the rig method disableState = rigKwargs.get( 'disable', False ) #grab the args the rigging method takes argsForm = self.UI_argsForm argsUIs = [] rigMethodName = rigKwargs.get( 'rigMethodName', self.rigTypes[ 0 ].__name__ ) rigClass = rigPrimitives.RigPart.GetNamedSubclass( rigMethodName ) if rigClass is None: rigClass = part.RigTypes[ 0 ] zeroWeightTypes = MelCheckBox, MelOptionMenu argNamesAndDefaults = rigClass.GetDefaultBuildKwargList() for arg, default in argNamesAndDefaults: argValue = rigKwargs.get( arg, default ) argLbl = MelLabel( argsForm, label=names.camelCaseToNice( arg ) ) #determine the function to use for building the UI for the arg buildMethodFromName = UI_FOR_NAMED_RIG_ARGS.get( arg, None ) buildMethodFromType = getBuildUIMethodForObject( default ) or MelTextField buildMethod = buildMethodFromName or buildMethodFromType argWidget = buildMethod( argsForm ) argWidget.setValue( argValue, False ) argWidget.setChangeCB( self.on_argCB ) argLbl.enable( not disableState ) argWidget.enable( not disableState ) argsUIs.append( argLbl ) argsUIs.append( argWidget ) self.argUIs[ arg ] = argWidget #if there are no args - create an empty text widget otherwise maya will crash. yay! argsUIs.append( MelLabel( argsForm, label='' ) ) argsForm.layout() def getRigKwargs( self ): disableState = self.UI_disable.getValue() kwargs = { 'disable': disableState, } if isinstance( self.UI_options, MelOptionMenu ): rigMethod = self.UI_options.getValue() if rigMethod: kwargs[ 'rigMethodName' ] = rigMethod for argName, widget in self.argUIs.iteritems(): kwargs[ argName ] = widget.getValue() self.UI_options.enable( not disableState ) for child in self.UI_argsForm.getChildren(): child.enable( not disableState ) return kwargs def updateBuildRigButton( self ): if self.part.isRigged(): self.UI_manualRig.setLabel( 'Delete Rig' ) self.UI_manualRig.setChangeCB( self.on_deleteRig ) else: self.UI_manualRig.setLabel( 'Build This Rig Only' ) self.UI_manualRig.setChangeCB( self.on_manualRig ) self.UI_manualRig.setWidth( 120 ) rigKwargs = self.part.getRigKwargs() self.UI_manualRig.setEnabled( not rigKwargs.get( 'disable', False ) ) ### EVENT HANDLERS ### def on_rigMethodCB( self, e ): #set the rig kwargs based on the current UI - it may be wrong however, because the new rig method may have different calling args self.part.setRigKwargs( self.getRigKwargs() ) #rebuild the UI to reflect the possibly new options for the changed rig method self.populate() #now store the rig kwargs again based on the correct UI self.part.setRigKwargs( self.getRigKwargs() ) def on_argCB( self, e=None ): self.part.setRigKwargs( self.getRigKwargs() ) self.updateBuildRigButton() def on_select( self, e=None ): cmd.select( self.part.items ) def on_manualRig( self, e=None ): self.part.finalize() self.part.rig() self.updateBuildRigButton() def on_deleteRig( self, e=None ): self.part.deleteRig() self.updateBuildRigButton() class RiggingLayout(MelForm): ''' ui for rig primitive creation ''' def __init__( self, parent ): MelForm.__init__( self, parent ) scroll = MelScrollLayout( self, cr=True ) self.UI_parts = MelColumn( scroll, rowSpacing=4, adj=True ) self.UI_buttons = MelColumn( self, rowSpacing=4, adj=True ) ### BUILD STATIC BUTTONS buttonParent = self.UI_buttons setParent( buttonParent ) optsLbl = MelLabel( buttonParent, label='Rig Build Options', align='left' ) buildRigLayout = MelHLayout( buttonParent ) self.UI_reference = MelCheckBox( buildRigLayout, label='reference model' ) self.UI_reference.setValue( False ) buildRigLayout.layout() setParent( buttonParent ) sep = cmd.separator( horizontal=True ) but = MelButton( buttonParent, l='BUILD RIG', c=self.on_buildRig, height=35 ) self( e=True, af=((scroll, 'top', 0), (scroll, 'left', 0), (scroll, 'right', 0), (self.UI_buttons, 'left', 0), (self.UI_buttons, 'right', 0), (self.UI_buttons, 'bottom', 0)), ac=((scroll, 'bottom', 3, self.UI_buttons)) ) def populate( self ): self.UI_parts.clear() col = self.UI_parts self.UI_partForms = [] for part in SkeletonPart.IterAllPartsInOrder(): partRigForm = RigPartLayout( col, part ) self.UI_partForms.append( partRigForm ) def on_buildRig( self, e=None ): curScene = Path( cmd.file( q=True, sn=True ) ) referenceModel = self.UI_reference.getValue() if referenceModel: if not curScene: cmd.confirmDialog( t='Scene not saved!', m="Looks like your current scene isn't saved\n\nPlease save it first so I know where to save the rig. thanks!", b=('OK',), db='OK' ) return rigPrimitives.buildRigForModel( referenceModel=referenceModel, deletePlacers=False ) #if the model is being referenced run populate to update the rig part instances - container names will have changed because they're now referenced if referenceModel: self.populate() #if we're not referencing the model however, its safe to just run the updateBuildRigButton method on all rig part UI instances else: for partUI in self.UI_partForms: partUI.updateBuildRigButton() class CreateEditRigTabLayout(MelTabLayout): def __init__( self, parent, *a, **kw ): MelTabLayout.__init__( self, parent, *a, **kw ) ### THE SKELETON CREATION TAB insetForm = self.SZ_skelForm = MelForm( self ) self.UI_builder = ed = BuildingLayout( insetForm ) self.UI_commonButtons = bts = CommonButtonsLayout( insetForm ) insetForm( e=True, af=((ed, 'top', 7), (ed, 'left', 5), (ed, 'right', 5), (bts, 'left', 5), (bts, 'right', 5), (bts, 'bottom', 5)), ac=((ed, 'bottom', 5, bts)) ) ### THE EDITING FORM insetForm = self.SZ_editForm = MelForm( self ) self.UI_editor = ed = EditingLayout( insetForm ) self.UI_commonButtons = bts = CommonButtonsLayout( insetForm ) insetForm( e=True, af=((ed, 'top', 7), (ed, 'left', 5), (ed, 'right', 5), (bts, 'left', 5), (bts, 'right', 5), (bts, 'bottom', 5)), ac=((ed, 'bottom', 5, bts)) ) ### THE RIGGING TAB insetForm = self.SZ_rigForm = MelForm( self ) self.UI_rigger = ed = RiggingLayout( insetForm ) insetForm( e=True, af=((ed, 'top', 7), (ed, 'left', 5), (ed, 'right', 5), (ed, 'bottom', 5)) ) self.setLabel( 0, 'create skeleton' ) self.setLabel( 1, 'edit skeleton' ) self.setLabel( 2, 'create rig' ) self.setSceneChangeCB( self.on_sceneOpen ) #rigPrimitives.skeletonBuilderConversion.convertOldParts() self.setChangeCB( self.on_change ) ### EVENT HANDLERS ### def on_change( self ): if self.getSelectedTab() == self.SZ_editForm: self.UI_editor.populate() elif self.getSelectedTab() == self.SZ_rigForm: self.UI_rigger.populate() def on_sceneOpen( self, *a ): self.setSelectedTabIdx( 0 ) #rigPrimitives.skeletonBuilderConversion.convertOldParts() class SkeletonBuilderWindow(BaseMelWindow): WINDOW_NAME = 'skeletonBuilder' WINDOW_TITLE = 'Skeleton Builder' DEFAULT_SIZE = 700, 700 DEFAULT_MENU = 'Tools' HELP_MENU = rigPrimitives.TOOL_NAME, rigPrimitives.__author__, None FORCE_DEFAULT_SIZE = True def __init__( self ): self.editor = CreateEditRigTabLayout( self ) tMenu = self.getMenu( 'Tools' ) cmd.menu( tMenu, e=True, pmc=self.buildToolsMenu ) dMenu = self.getMenu( 'Dev' ) cmd.menu( dMenu, e=True, pmc=self.buildDevMenu ) #close related windows... RigBuilderWindow.Close() ControlBuildingWindow.Close() UserAlignListerWindow.Close() PartExplorerWindow.Close() self.show() def buildToolsMenu( self, *a ): menu = self.getMenu( 'Tools' ) menu.clear() MelMenuItem( menu, l='Bone Count HUD', cb=headsUpDisplay( rigPrimitives.HUD_NAME, ex=True ), c=lambda *a: rigPrimitives.setupSkeletonBuilderJointCountHUD() ) MelMenuItem( menu, l='Pose Mirroring Tool', c=self.on_loadMirrorTool ) MelMenuItemDiv( menu ) enableState = rigUtils.getSkinClusterEnableState() MelMenuItem( menu, l='Space Switching Tool', c=lambda *a: spaceSwitchingUI.SpaceSwitchingWindow() ) MelMenuItem( menu, l='Stand Alone Rig Builder Tool', c=lambda *a: RigBuilderWindow() ) MelMenuItem( menu, l='Control Creation Tool', c=lambda *a: ControlBuildingWindow() ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='Mark Selected As User Aligned', c=self.on_markUserAligned ) MelMenuItem( menu, l='Clear User Aligned On Selected', c=self.on_clearUserAligned ) MelMenuItem( menu, l='User Aligned Editor', c=lambda *a: UserAlignListerWindow() ) #MelMenuItemDiv( menu ) #MelMenuItem( menu, l='Clean My Huge Rig', c=lambda *a: rigPrimitives.cleanMeshControls() ) def buildDevMenu( self, *a ): menu = self.getMenu( 'Dev' ) menu.clear() MelMenuItem( menu, l='Skeleton Part Code Explorer', c=lambda *a: PartExplorerWindow() ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='Reboot Tool', c=self.on_reboot ) ### EVENT HANDLERS ### def on_markUserAligned( self, *a ): for j in cmd.ls( sl=True, type='joint' ) or []: rigPrimitives.setAlignSkipState( j, True ) def on_clearUserAligned( self, *a ): for j in cmd.ls( sl=True, type='joint' ) or []: rigPrimitives.setAlignSkipState( j, False ) def on_reboot( self, *a ): self.close() import mayaDependencies mayaDependencies.flush() import skeletonBuilderUI skeletonBuilderUI.SkeletonBuilderWindow() def on_loadMirrorTool( self, *a ): #check the rig to see if its been setup for pose mirroring #rigPrimitives.setupMirroring() import poseSymUI poseSymUI.PoseSymWindow() SkeletonBuilderUI = SkeletonBuilderWindow class PartExplorerLayout(MelTabLayout): def __init__( self, parent ): MelTabLayout.__init__( self, parent ) #do skeleton parts skeletonPartScroll = MelScrollLayout( self ) theCol = MelColumnLayout( skeletonPartScroll ) def getFile( cls ): clsFile = Path( inspect.getfile( cls ) ) if clsFile.setExtension( 'py' ).exists(): return clsFile.setExtension( 'py' ) return clsFile for cls in SkeletonPart.IterSubclasses(): clsFile = getFile( cls ) col = MelColumnLayout( theCol ) MelSeparator( col, h=5 ) hLayout = MelHSingleStretchLayout( col ) MelLabel( hLayout, l=cls.GetPartName(), align='left' ).bold( True ) MelSpacer( hLayout, w=10 ) lbl = MelLabel( hLayout, l=clsFile, align='left' ) hLayout.setStretchWidget( lbl ) hLayout.layout() hLayout = MelHLayout( col ) MelButton( hLayout, l='Explore To', c=Callback( api.mel.zooExploreTo, clsFile ), h=20 ) MelButton( hLayout, l='Edit', c=Callback( os.system, 'start %s' % clsFile ), h=20 ) hLayout.layout() #do rig parts rigPartScroll = MelScrollLayout( self ) theCol = MelColumnLayout( rigPartScroll ) for cls in rigPrimitives.RigPart.IterSubclasses(): clsFile = getFile( cls ) col = MelColumnLayout( theCol ) MelSeparator( col, h=5 ) hLayout = MelHSingleStretchLayout( col ) MelLabel( hLayout, l=cls.GetPartName(), align='left' ).bold( True ) MelSpacer( hLayout, w=10 ) lbl = MelLabel( hLayout, l=clsFile, align='left' ) hLayout.setStretchWidget( lbl ) hLayout.layout() hLayout = MelHLayout( col ) MelButton( hLayout, l='Explore To', c=Callback( api.mel.zooExploreTo, clsFile ), h=20 ) MelButton( hLayout, l='Edit', c=Callback( os.system, 'start %s' % clsFile ), h=20 ) hLayout.layout() #setup labels self.setLabel( 0, 'Skeleton Parts' ) self.setLabel( 1, 'Rig Parts' ) def on_change( self ): self.sendEvent( 'layout' ) class PartExplorerWindow(BaseMelWindow): WINDOW_NAME = 'skeletonBuilderPartExplorer' WINDOW_TITLE = '%s: Part Code Explorer' % SkeletonBuilderWindow.WINDOW_TITLE DEFAULT_MENU = None DEFAULT_SIZE = 450, 250 FORCE_DEFAULT_SIZE = True def __init__( self ): PartExplorerLayout( self ) self.show() self.layout() class UserAlignListerLayout(MelVSingleStretchLayout): def __init__( self, parent ): def itemAsStr( item ): if rigPrimitives.getAlignSkipState( item ): return '* %s' % item return ' %s' % item UI_itemList = MelObjectScrollList( self ) UI_itemList.itemAsStr = itemAsStr for part in SkeletonPart.IterAllPartsInOrder(): for item in part: UI_itemList.append( item ) hLayout = MelHLayout( self ) MelButton( hLayout, l='Mark As User Aligned' ) MelButton( hLayout, l='Clear User Aligned' ) hLayout.layout() self.setStretchWidget( UI_itemList ) self.layout() class UserAlignListerWindow(BaseMelWindow): WINDOW_NAME = 'skeletonBuilderUserAlignedJointsWindow' WINDOW_TITLE = '%s: User Aligned Joints' % SkeletonBuilderWindow.WINDOW_TITLE DEFAULT_MENU = None DEFAULT_SIZE = 350, 200 def __init__( self ): self.setSceneChangeCB( lambda: self.close() ) #close on scene load... UserAlignListerLayout( self ) self.show() def load(): global ui ui = SkeletonBuilderWindow() ############################## ### STANDALONE RIG BUILDER ### ############################## class RigBuilderLayout(MelVSingleStretchLayout): def __init__( self, parent, *a, **kw ): MelVSingleStretchLayout.__init__( self, parent, *a, **kw ) MelLabel( self, l="""Select the part's joints in hierarchical order, choose the part type, and hit the convert button.""" ) ManualPartCreationLayout( self ) scroll = MelScrollLayout( self ) self.UI_remove = MelButton( self, l='Remove Skeleton Builder Markup From Selection', c=self.on_remove ) self.setStretchWidget( scroll ) self.layout() self.UI_partLayouts = [] self.SZ_partLayout = col = MelColumnLayout( scroll, rowSpacing=3 ) self.populate() self.setSelectionChangeCB( self.on_select ) self.setSceneChangeCB( self.on_scene ) def populate( self ): self.SZ_partLayout.clear() for part in SkeletonPart.IterAllPartsInOrder(): self.appendNewPart( part ) def appendNewPart( self, newPart ): partLayout = RigPartLayout( self.SZ_partLayout, newPart ) self.UI_partLayouts.append( partLayout ) def manualPartCreated( self, newPart ): self.appendNewPart( newPart ) self.sendEvent( 'layout' ) ### EVENT HANDLERS ### def on_remove( self, *a ): for item in cmd.ls( sl=True ): for attrName in listAttr( item, ud=True ): if attrName.startswith( '_skeletonPart' ) or attrName.startswith( '_skeletonFinalize' ): cmd.deleteAttr( '%s.%s' % (item, attrName) ) self.populate() def on_select( self, *a ): sel = cmd.ls( sl=True ) if sel: self.UI_remove.enable() else: self.UI_remove.disable() def on_scene( self, *a ): self.populate() class RigBuilderWindow(BaseMelWindow): WINDOW_NAME = 'rigBuilderTool' WINDOW_TITLE = '%s: Manual Rig Builder Tool' % SkeletonBuilderWindow.WINDOW_TITLE DEFAULT_SIZE = 475, 300 DEFAULT_MENU = None def __init__( self ): BaseMelWindow.__init__( self ) padding = MelSingleLayout( self, 5 ) RigBuilderLayout( padding ) padding.layout() self.show() ############################### ### CONTROL BUILDING WINDOW ### ############################### class ControlBuildingLayout(MelForm): def __init__( self, parent, *a, **kw ): width = 60 self.UI_place = UI_place = MelObjectSelector( self, label='place at->', labelWidth=width ) self.UI_parent = UI_parent = MelObjectSelector( self, label='parent to->', labelWidth=width ) self.UI_align = UI_align = MelObjectSelector( self, label='align to->', labelWidth=width ) self.UI_pivot = UI_pivot = MelObjectSelector( self, label='pivot to->', labelWidth=width ) self.UI_build = UI_build = MelButton( self, l='build control', c=self.on_build ) self( e=True, af=( (UI_place, 'left', 0), (UI_parent, 'right', 0), (UI_align, 'left', 0), (UI_pivot, 'right', 0), (UI_build, 'left', 0), (UI_build, 'right', 0), (UI_build, 'bottom', 0), ), ac=( (UI_align, 'top', 0, UI_place), (UI_pivot, 'top', 0, UI_place), ), ap=( (UI_place, 'right', 0, 50), (UI_parent, 'left', 0, 50), (UI_align, 'right', 0, 50), (UI_pivot, 'left', 0, 50), ) ) def on_build( self, *a ): place = self.UI_place.getValue() parent = self.UI_parent.getValue() align = self.UI_align.getValue() pivot = self.UI_pivot.getValue() args = [] if place: args.append( place ) if align: args.append( align ) if pivot: args.append( pivot ) control.buildControl( '%sControl' % place, control.PlaceDesc( *args ) ) class ControlBuildingWindow(BaseMelWindow): WINDOW_NAME = 'controlBuildingWindow' WINDOW_TITLE = '%s: Control Builder' % SkeletonBuilderWindow.WINDOW_TITLE DEFAULT_SIZE = 450, 350 DEFAULT_MENU = 'Help' DEFAULT_MENU_IS_HELP = True HELP_MENU = rigPrimitives.TOOL_NAME, rigPrimitives.__author__, None FORCE_DEFAULT_SIZE = True def __init__( self ): self.editor = ControlBuildingLayout( self ) self.show() #end
Python
''' This module abstracts and packages up the maya UI that is available to script in a more object oriented fashion. For the most part the framework tries to make working with maya UI a bit more like proper UI toolkits where possible. For more information there is some high level documentation on how to use this code here: http://www.macaronikazoo.com/?page_id=311 ''' import re import maya import names import common import inspect import maya.cmds as cmd import filesystem import typeFactories from maya.OpenMaya import MGlobal mayaVer = int( maya.mel.eval( 'getApplicationVersionAsFloat' ) ) removeDupes = filesystem.removeDupes _DEBUG = True #try to import wing... try: import wingdbstub except: _DEBUG = False class MelUIError(Exception): pass def iterBy( iterable, count ): ''' returns an generator which will yield "chunks" of the iterable supplied of size "count". eg: for chunk in iterBy( range( 7 ), 3 ): print chunk results in the following output: [0, 1, 2] [3, 4, 5] [6] ''' cur = 0 i = iter( iterable ) while True: try: toYield = [] for n in range( count ): toYield.append( i.next() ) yield toYield except StopIteration: if toYield: yield toYield break class Callback(object): ''' stupid little callable object for when you need to "bake" temporary args into a callback - useful mainly when creating callbacks for dynamicly generated UI items ''' def __init__( self, func, *a, **kw ): self.f = func self.a = a self.kw = kw def __call__( self, *a, **kw ): args = self.a + a kw.update( self.kw ) return self.f( *args, **kw ) #this maps ui type strings to actual command objects - they're not always called the same TYPE_NAMES_TO_CMDS = { u'staticText': cmd.text, u'field': cmd.textField, u'cmdScrollField': cmd.scrollField, u'commandMenuItem': cmd.menuItem, u'dividorMenuItem': cmd.menuItem } #stores a list of widget cmds that don't have docTag support - classes that wrap this command need to skip encoding the classname into the docTag. obviously. WIDGETS_WITHOUT_DOC_TAG_SUPPORT = [ cmd.popupMenu ] class BaseMelUI(typeFactories.trackableClassFactory( unicode )): ''' This is a wrapper class for a mel widget to make it behave a little more like an object. It inherits from str because thats essentially what a mel widget is - a name coupled with a mel command. To interact with the widget the mel command is called with the UI name as the first arg. As a shortcut objects of this type are callable - the args taken depend on the specific command, and can be found in the mel docs. example: class AButtonClass(BaseMelUI): WIDGET_CMD = cmd.button aButton = AButtonClass( parentName, label='hello' ) aButton( edit=True, label='new label!' ) ''' #this should be set to the mel widget command used by this widget wrapped - ie cmd.button, or cmd.formLayout WIDGET_CMD = cmd.control #if not None, this is used to set the default width of the widget when created DEFAULT_WIDTH = None #default heights in 2011 aren't consistent - buttons are 24 pixels high by default (this is a minimum possible value too) while input fields are 20 DEFAULT_HEIGHT = None if mayaVer < 2011 else 24 #this is the name of the kwarg used to set and get the "value" of the widget - most widgets use the "value" or "v" kwarg, but others have special names. three cheers for mel! KWARG_VALUE_NAME = 'v' KWARG_VALUE_LONG_NAME = 'value' #populate this dictionary with variable names you want created on instances. values are default values. having this dict saves having to override __new__ and __init__ methods on subclasses just to create instance variables on creation #the variables are also popped out of the **kw arg by both __new__ and __init__, so specifying variable names and default values here is the equivalent of making them available on the constructor method _INSTANCE_VARIABLES = {} #this is the name of the "main" change command kwarg. some widgets have multiple change callbacks that can be set, and they're not abstracted, but this is the name of the change cb name you want to be referenced by the setChangeCB method KWARG_CHANGE_CB_NAME = 'cc' #track instances so we can send them update messages - _INSTANCE_LIST = [] @classmethod def Exists( cls, theControl ): if isinstance( theControl, BaseMelUI ): return theControl.exists() return cmd.control( theControl, q=True, exists=True ) @classmethod def IterWidgetClasses( cls, widgetCmd ): if widgetCmd is None: return for subCls in BaseMelUI.IterSubclasses(): if subCls.WIDGET_CMD is widgetCmd: yield subCls def __new__( cls, parent, *a, **kw ): WIDGET_CMD = cls.WIDGET_CMD kw.pop( 'p', None ) #pop any parent specified in teh kw dict - set it explicitly to the parent specified if parent is not None: kw[ 'parent' ] = parent #pop out any instance variables defined in the _INSTANCE_VARIABLES dict instanceVariables = {} for attrName, attrDefaultValue in cls._INSTANCE_VARIABLES.iteritems(): instanceVariables[ attrName ] = kw.pop( attrName, attrDefaultValue ) #set default sizes if applicable width = kw.pop( 'w', kw.pop( 'width', cls.DEFAULT_WIDTH ) ) if isinstance( width, int ): kw[ 'width' ] = width height = kw.pop( 'h', kw.pop( 'height', cls.DEFAULT_HEIGHT ) ) if isinstance( height, int ): kw[ 'height' ] = height #not all mel widgets support docTags... :( if WIDGET_CMD not in WIDGETS_WITHOUT_DOC_TAG_SUPPORT: #store the name of this class in the widget's docTag - we can use this to re-instantiate the widget once it's been created kw.pop( 'dtg', kw.pop( 'docTag', None ) ) kw[ 'docTag' ] = docTag=cls.__name__ #pop out the change callback if its been passed in with the kw dict, and run it through the setChangeCB method so it gets registered appropriately changeCB = kw.pop( cls.KWARG_CHANGE_CB_NAME, None ) #get the leaf name for the parent parentNameTok = str( parent ).split( '|' )[-1] #this has the potential to be slow: it generates a unique name for the widget we're about to create, the benefit of doing this is that we're #guaranteed the widget LEAF name will be unique. I'm assuming maya also does this, but I'm unsure. if there are weird ui naming conflicts #it might be nessecary to uncomment this code formatStr = '%s%d__'#+ parentNameTok baseName, n = cls.__name__, len( cls._INSTANCE_LIST ) uniqueName = formatStr % (baseName, n) while WIDGET_CMD( uniqueName, q=True, exists=True ): n += 1 uniqueName = formatStr % (baseName, n) WIDGET_CMD( uniqueName, **kw ) new = unicode.__new__( cls, uniqueName ) new.parent = parent new._cbDict = cbDict = {} cls._INSTANCE_LIST.append( new ) #add the instance variables to the instance for attrName, attrValue in instanceVariables.iteritems(): new.__dict__[ attrName ] = attrValue #if the changeCB is valid, add it to the cd dict if changeCB: new.setCB( cls.KWARG_CHANGE_CB_NAME, changeCB ) return new def __init__( self, parent, *a, **kw ): pass def __call__( self, *a, **kw ): return self.WIDGET_CMD( unicode( self ), *a, **kw ) def setChangeCB( self, cb ): self.setCB( self.KWARG_CHANGE_CB_NAME, cb ) def getChangeCB( self ): return self.getCB( self.KWARG_CHANGE_CB_NAME ) def setCB( self, cbFlagName, cb ): if cb is None: if cbFlagName in self._cbDict: self._cbDict.pop( cbFlagName ) else: self.WIDGET_CMD( self, **{ 'e': True, cbFlagName: cb } ) self._cbDict[ cbFlagName ] = cb def getCB( self, cbFlagName ): return self._cbDict.get( cbFlagName, None ) def _executeCB( self, cbFlagName=None ): if cbFlagName is None: cbFlagName = self.KWARG_CHANGE_CB_NAME cb = self.getCB( cbFlagName ) if cb is None: return if callable( cb ): try: cb() except Exception, x: common.printErrorStr( "The %s callback failed" % cbFlagName ) def getFullName( self ): ''' returns the fullname to the UI widget ''' parents = list( self.iterParents() ) parents.reverse() parents.append( self ) parents = [ uiFullName.split( '|' )[ -1 ] for uiFullName in parents ] return '|'.join( parents ) def sendEvent( self, methodName, *methodArgs, **methodKwargs ): ''' events are nothing more than a tuple containing a methodName, argument list and keyword dict that gets propagated up the UI hierarchy. Each widget in the hierarchy is asked whether it has a method of the given name, and if it does, the method is called with the argumentList and keywordDict and propagation ends. ''' self.parent.processEvent( methodName, methodArgs, methodKwargs ) def processEvent( self, methodName, methodArgs, methodKwargs ): method = getattr( self, methodName, None ) if callable( method ): #run the method in the buff if we're in debug mode if _DEBUG: method( *methodArgs, **methodKwargs ) else: try: method( *methodArgs, **methodKwargs ) except: common.printErrorStr( 'Event Failed: %s, %s, %s' % (methodName, methodArgs, methodKwargs) ) else: self.parent.processEvent( methodName, methodArgs, methodKwargs ) def getVisibility( self ): return self( q=True, vis=True ) def setVisibility( self, visibility=True ): ''' hides the widget ''' self( e=True, vis=visibility ) def hide( self ): self.setVisibility( False ) def show( self ): self.setVisibility( True ) def setWidth( self, width ): self( e=True, width=width ) def getWidth( self ): return self( q=True, width=True ) def setHeight( self, height ): self( e=True, height=height ) def getHeight( self ): return self( q=True, height=True ) def setSize( self, widthHeight ): self( e=True, w=widthHeight[ 0 ], h=widthHeight[ 1 ] ) def getSize( self ): w = self( q=True, w=True ) h = self( q=True, h=True ) return w, h def getColour( self ): return self( q=True, bgc=True ) getColor = getColour def setColour( self, colour ): initialVis = self( q=True, vis=True ) self( e=True, bgc=colour, vis=False ) if initialVis: self( e=True, vis=True ) setColor = setColour def resetColour( self ): self( e=True, enableBackground=False ) resetColor = resetColour def getParent( self ): ''' returns the widget's parent. NOTE: its not possible to change a widget's parent once its been created ''' return self.parent #cmd.control( self, q=True, parent=True ) def iterParents( self ): ''' returns a generator that walks up the widget hierarchy ''' try: parent = self.parent while True: yield parent #if the parent isn't an instance of BaseMelUI (the user has mixed baseMelUI and plain old mel) this should throw an attribute error try: parent = parent.parent #in which case, try to cast the widget as a BaseMelUI instance and yield that instead except AttributeError: parent = BaseMelUI.FromStr( cmd.control( parent, q=True, parent=True ) ) except RuntimeError: return def getTopParent( self ): ''' returns the top widget at the top of this widget's hierarchy ''' parent = self.parent while True: try: parent = parent.parent except AttributeError: return parent def getParentOfType( self, parentClass, exactMatch=False ): ''' if exactMatch is True the class of the parent must be the parentClass, otherwise it checks whether the parent is a subclass of parentClass ''' for parent in self.iterParents(): if exactMatch: if parent.__class__ is parentClass: return parent else: if issubclass( parent.__class__, parentClass ): return parent def exists( self ): return cmd.control( self, ex=True ) def delete( self ): cmd.deleteUI( self ) if self in self._INSTANCE_LIST: self._INSTANCE_LIST.remove( self ) def setSelectionChangeCB( self, cb, compressUndo=True, **kw ): ''' creates a scriptJob to monitor selection, and fires the given callback when the selection changes the scriptJob is parented to this widget so it dies when the UI is closed NOTE: selection callbacks don't take any args ''' return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('SelectionChanged', cb), **kw ) def setSceneChangeCB( self, cb, compressUndo=True, **kw ): ''' creates a scriptJob which will fire when the currently open scene changes the scriptJob is parented to this widget so it dies when the UI is closed NOTE: scene change callbacks don't take any args ''' return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('SceneOpened', cb), **kw ) def setTimeChangeCB( self, cb, compressUndo=True, **kw ): ''' creates a scriptJob which will fire when the current time changes the scriptJob is parented to this widget so it dies when the UI is closed NOTE: time change callbacks don't take any args ''' return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('timeChanged', cb), **kw ) def setAttributeChangeCB( self, attrpath, cb, compressUndo=True, allChildren=False, disregardIndex=False, **kw ): ''' creates a scriptjob which will fire when the given attribute gets changed ''' return cmd.scriptJob( compressUndo=compressUndo, parent=self, attributeChange=(attrpath, cb), allChildren=allChildren, disregardIndex=disregardIndex, **kw ) def setDeletionCB( self, cb, compressUndo=True, **kw ): ''' define a callback that gets triggered when this piece of UI gets deleted ''' return cmd.scriptJob( compressUndo=compressUndo, uiDeleted=(self, cb), **kw ) def setUndoCB( self, cb, compressUndo=True, **kw ): ''' define a callback that gets triggered when an undo event is issued ''' return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('Undo', cb), **kw ) @classmethod def FromStr( cls, theStr ): ''' given a ui name, this will cast the string as a widget instance ''' #if the instance is in the instance list, return it if theStr in cls._INSTANCE_LIST: idx = cls._INSTANCE_LIST.index( theStr ) return cls._INSTANCE_LIST[ idx ] else: theStrLeaf = theStr.split( '|' )[-1] if theStrLeaf in cls._INSTANCE_LIST: idx = cls._INSTANCE_LIST.index( theStrLeaf ) return cls._INSTANCE_LIST[ idx ] try: uiTypeStr = cmd.objectTypeUI( theStr ) except RuntimeError: try: uiTypeStr = cmd.objectTypeUI( theStr.split( '|' )[ -1 ] ) except RuntimeError: uiTypeStr = '' uiCmd = TYPE_NAMES_TO_CMDS.get( uiTypeStr, getattr( cmd, uiTypeStr, cmd.control ) ) theCls = None if uiCmd not in WIDGETS_WITHOUT_DOC_TAG_SUPPORT: #see if the data stored in the docTag is a valid class name - it might not be if teh user has used the docTag for something (why would they? there is no need, but still check...) try: possibleClassName = uiCmd( theStr, q=True, docTag=True ) #menu item dividers have a weird type name when queried - "dividorMenuItem", which is a menuItem technically, but you can't query its docTag, so this catch statement is exclusively for this case as far as I know... except RuntimeError: pass else: theCls = BaseMelUI.GetNamedSubclass( possibleClassName ) #if the data stored in the docTag doesn't map to a subclass, then we'll have to guess at the best class... if theCls is None: #common.printInfoStr( cmd.objectTypeUI( theStr ) ) ##NOTE: the typestr isn't ALWAYS the same name as the function used to interact with said control, so this debug line can be useful for spewing object type names... theCls = BaseMelUI #at this point default to be an instance of the base widget class candidates = list( BaseMelUI.IterWidgetClasses( uiCmd ) ) if candidates: theCls = candidates[ 0 ] new = unicode.__new__( theCls, theStr ) #we don't want to run initialize on the object - just cast it appropriately new._cbDict = cbDict = {} cls._INSTANCE_LIST.append( new ) #try to grab the parent... try: new.parent = cmd.control( theStr, q=True, parent=True ) except RuntimeError: new.parent = None return new @classmethod def ValidateInstanceList( cls ): control = cmd.control _INSTANCE_LIST = cls._INSTANCE_LIST cls._INSTANCE_LIST = [ ui for ui in _INSTANCE_LIST if control( ui, exists=True ) ] @classmethod def IterInstances( cls ): existingInstList = [] for inst in cls._INSTANCE_LIST: if not isinstance( inst, cls ): continue if cls.WIDGET_CMD( inst, q=True, exists=True ): existingInstList.append( inst ) yield inst cls._INSTANCE_LIST = existingInstList class BaseMelLayout(BaseMelUI): ''' base class for layout UI ''' WIDGET_CMD = cmd.layout DEFAULT_WIDTH = None DEFAULT_HEIGHT = None def getChildren( self ): ''' returns a list of all children UI items ''' children = self( q=True, ca=True ) or [] children = [ BaseMelUI.FromStr( c ) for c in children ] return children def getNumChildren( self ): return len( self.getChildren() ) def printUIHierarchy( self ): def printChildren( children, depth ): for child in children: common.printInfoStr( '%s%s' % (' ' * depth, child) ) if isinstance( child, BaseMelLayout ): printChildren( child.getChildren(), depth+1 ) common.printInfoStr( self ) printChildren( self.getChildren(), 1 ) def clear( self ): ''' deletes all children from the layout ''' for childUI in self.getChildren(): cmd.deleteUI( childUI ) class MelFormLayout(BaseMelLayout): WIDGET_CMD = cmd.formLayout ALL_EDGES = 'top', 'left', 'right', 'bottom' def getOtherEdges( self, edges ): otherEdges = list( self.ALL_EDGES ) for edge in edges: if edge in otherEdges: otherEdges.remove( edge ) return otherEdges MelForm = MelFormLayout class MelSingleLayout(MelForm): ''' Simple layout that causes the child to stretch to the extents of the layout in all directions. NOTE: make sure to call layout() after the child has been created to setup the layout data ''' _INSTANCE_VARIABLES = { 'padding': 0 } def __init__( self, parent, padding=0, *a, **kw ): MelForm.__init__( self, parent, *a, **kw ) self._padding = padding def getPadding( self ): return self._padding def setPadding( self, padding ): self._padding = padding self.layout() def layout( self ): children = self.getChildren() assert len( children ) == 1, "Can only support one child!" padding = self._padding theChild = children[ 0 ] self( e=True, af=((theChild, 'top', padding), (theChild, 'left', padding), (theChild, 'right', padding), (theChild, 'bottom', padding)) ) class _AlignedFormLayout(MelForm): _EDGES = 'left', 'right' def getOtherEdges( self ): return MelFormLayout.getOtherEdges( self, self._EDGES ) def layoutExpand( self, children ): edge1, edge2 = self._EDGES try: padding = self.padding except AttributeError: padding = 0 otherEdges = self.getOtherEdges() otherEdge1, otherEdge2 = otherEdges for child in children: self( e=True, af=((child, otherEdge1, padding), (child, otherEdge2, padding)) ) class MelHLayout(_AlignedFormLayout): ''' emulates a horizontal layout sizer - the only caveat is that you need to explicitly call the layout method to setup sizing. NOTE: you need to call layout() once the children have been created to initialize the layout relationships example: row = MelHLayout( self ) MelButton( row, l='apples' ) MelButton( row, l='bananas' ) MelButton( row, l='oranges' ) row.layout() ''' _INSTANCE_VARIABLES = { '_weights': {}, 'padding': 0, #if True the layout will expand to fill the layout in the "other" direction. Ie HLayouts will expand vertically and VLayouts will expand horizontally to the extents of the layout 'expand': False } def setWeight( self, widget, weight=1 ): self._weights[ widget ] = weight def getHeight( self ): return max( [ ui.getHeight() for ui in self.getChildren() ] ) def getWidth( self ): return sum( [ ui.getWidth() for ui in self.getChildren() ] ) def layout( self, expand=None ): if expand is not None: self.expand = expand padding = self.padding children = self.getChildren() weightsDict = self._weights weightsList = [] for child in children: weight = weightsDict.get( child, 1 ) weightsList.append( weight ) weightSum = float( sum( weightsList ) ) #if not weightSum: #return weightAccum = 0 positions = [] for weight in weightsList: actualWeight = 100 * weightAccum / weightSum weightAccum += weight positions.append( actualWeight ) edge1, edge2 = self._EDGES positions.append( 100 ) for n, child in enumerate( children ): self( e=True, ap=((child, edge1, padding, positions[n]), (child, edge2, padding, positions[n+1])) ) #if any children have a weight of zero, set the next item in the list to attach to the widget instead of a position for n, weight in enumerate( weightsList ): if weight == 0: thisW = children[ n ] try: nextW = children[ n+1 ] self( e=True, ac=(nextW, edge1, padding, thisW), an=(thisW, edge2) ) except IndexError: prevW = children[ n-1 ] self( e=True, ac=(prevW, edge2, padding, thisW), an=(thisW, edge1) ) if self.expand: self.layoutExpand( children ) class MelVLayout(MelHLayout): _EDGES = 'top', 'bottom' def getHeight( self ): return sum( [ ui.getHeight() for ui in self.getChildren() ] ) def getWidth( self ): return max( [ ui.getWidth() for ui in self.getChildren() ] ) class MelHRowLayout(_AlignedFormLayout): ''' Simple row layout - the rowLayout mel command isn't so hot because you have to know ahead of time how many columns to build, and dynamic sizing is rubbish. This makes writing a simple row of widgets super easy. NOTE: like all subclasses of MelFormLayout, make sure to call .layout() after children have been built ''' _INSTANCE_VARIABLES = { 'padding': 5, #if True the layout will expand to fill the layout in the "other" direction. Ie HLayouts will expand vertically and VLayouts will expand horizontally to the extents of the layout 'expand': False } def layout( self, expand=None ): if expand is not None: self.expand = expand padding = self.padding children = self.getChildren() edge1, edge2 = self._EDGES for n, child in enumerate( children ): if n: self( e=True, ac=(child, edge1, padding, children[ n-1 ]) ) else: self( e=True, af=(child, edge1, 0) ) if self.expand: self.layoutExpand( children ) class MelVRowLayout(MelHRowLayout): _EDGES = 'top', 'bottom' class MelHSingleStretchLayout(_AlignedFormLayout): ''' Provides an easy interface to a common layout pattern where a single widget in the row/column is stretchy and the others are statically sized. Make sure to call setStretchWidget() before calling layout() ''' _stretchWidget = None _INSTANCE_VARIABLES = { 'padding': 5, #if True the layout will expand to fill the layout in the "other" direction. Ie HLayouts will expand vertically and VLayouts will expand horizontally to the extents of the layout 'expand': False } def setPadding( self, padding ): self.padding = padding def setExpand( self, expand ): ''' make sure to call layout() after changing the expand value ''' self.expand = expand def setStretchWidget( self, widget ): if not isinstance( widget, BaseMelUI ): widget = BaseMelUI.FromStr( widget ) self._stretchWidget = widget self.layout() def layout( self, expand=None ): if expand is not None: self.expand = expand padding = self.padding children = self.getChildren() stretchWidget = self._stretchWidget if stretchWidget is None: stretchWidget = children[ 0 ] idx = children.index( stretchWidget ) leftChildren = children[ :idx ] rightChildren = children[ idx+1: ] edge1, edge2 = self._EDGES for n, child in enumerate( leftChildren ): if n: self( e=True, ac=(child, edge1, padding, children[ n-1 ]) ) else: self( e=True, af=(child, edge1, 0) ) if rightChildren: self( e=True, af=(rightChildren[-1], edge2, 0) ) for n, child in enumerate( rightChildren[ :-1 ] ): self( e=True, ac=(child, edge2, padding, rightChildren[ n+1 ]) ) if leftChildren and rightChildren: self( e=True, ac=((stretchWidget, edge1, padding, leftChildren[-1]), (stretchWidget, edge2, padding, rightChildren[0])) ) elif leftChildren and not rightChildren: self( e=True, ac=(stretchWidget, edge1, padding, leftChildren[-1]), af=(stretchWidget, edge2, 0) ) elif not leftChildren and rightChildren: self( e=True, af=(stretchWidget, edge1, 0), ac=(stretchWidget, edge2, padding, rightChildren[0]) ) if self.expand: self.layoutExpand( children ) class MelVSingleStretchLayout(MelHSingleStretchLayout): _EDGES = 'top', 'bottom' _INSTANCE_VARIABLES = { 'padding': 5, 'expand': True } class MelColumnLayout(BaseMelLayout): WIDGET_CMD = cmd.columnLayout STRETCHY = True def __new__( cls, parent, *a, **kw ): stretchy = kw.pop( 'adjustableColumn', kw.pop( 'adj', cls.STRETCHY ) ) kw.setdefault( 'adjustableColumn', stretchy ) return BaseMelLayout.__new__( cls, parent, *a, **kw ) MelColumn = MelColumnLayout class MelRowLayout(BaseMelLayout): WIDGET_CMD = cmd.rowLayout MelRow = MelRowLayout class MelGridLayout(BaseMelLayout): WIDGET_CMD = cmd.gridLayout AUTO_GROW = True def __new__( cls, parent, **kw ): autoGrow = kw.pop( 'autoGrow', self.AUTO_GROW ) kw.setdefault( 'ag', autoGrow ) return BaseMelLayout.__new__( cls, parent, **kw ) MelGrid = MelGridLayout class MelScrollLayout(BaseMelLayout): WIDGET_CMD = cmd.scrollLayout def __new__( cls, parent, *a, **kw ): kw.setdefault( 'childResizable', kw.pop( 'cr', True ) ) return BaseMelLayout.__new__( cls, parent, *a, **kw ) MelScroll = MelScrollLayout class MelHScrollLayout(MelScrollLayout): _ORIENTATION_ATTR = 'verticalScrollBarThickness' def __new__( cls, parent, *a, **kw ): kw[ cls._ORIENTATION_ATTR ] = 0 return MelScrollLayout.__new__( cls, parent, *a, **kw ) class MelVScrollLayout(MelHScrollLayout): _ORIENTATION_ATTR = 'horizontalScrollBarThickness' class MelTabLayout(BaseMelLayout): WIDGET_CMD = cmd.tabLayout def __init__( self, parent, *a, **kw ): BaseMelLayout.__init__( self, parent, *a, **kw ) ccCB = kw.get( 'changeCommand', kw.get( 'cc', None ) ) self.setChangeCB( ccCB ) pscCB = kw.get( 'preSelectCommand', kw.get( 'psc', None ) ) self.setPreSelectCB( pscCB ) dccCB = kw.get( 'doubleClickCommand', kw.get( 'dcc', None ) ) self.setDoubleClickCB( dccCB ) def numTabs( self ): return self( q=True, numberOfChildren=True ) __len__ = numTabs def setLabel( self, idx, label ): self( e=True, tabLabelIndex=(idx+1, label) ) def getLabel( self, idx ): self( q=True, tabLabelIndex=idx+1 ) def getSelectedTab( self ): return self( q=True, selectTab=True ) def setSelectedTab( self, child, executeChangeCB=True ): self( e=True, selectTab=child ) if executeChangeCB: self._executeCB( 'selectCommand' ) def getSelectedTabIdx( self ): return self( q=True, selectTabIndex=True )-1 #indices are 1-based... fuuuuuuu alias! def setSelectedTabIdx( self, idx, executeChangeCB=True ): self( e=True, selectTabIndex=idx+1 ) #indices are 1-based... fuuuuuuu alias! if executeChangeCB: self._executeCB( 'selectCommand' ) def setChangeCB( self, cb ): self.setCB( 'selectCommand', cb ) def setPreSelectCB( self, cb ): self.setCB( 'preSelectCommand', cb ) def setDoubleClickCB( self, cb ): self.setCB( 'doubleClickCommand', cb ) class MelPaneLayout(BaseMelLayout): WIDGET_CMD = cmd.paneLayout PREF_OPTION_VAR = None POSSIBLE_CONFIGS = \ CFG_SINGLE, CFG_HORIZ2, CFG_VERT2, CFG_HORIZ3, CFG_VERT3, CFG_TOP3, CFG_LEFT3, CFG_BOTTOM3, CFG_RIGHT3, CFG_HORIZ4, CFG_VERT4, CFG_TOP4, CFG_LEFT4, CFG_BOTTOM4, CFG_RIGHT4, CFG_QUAD = \ "single", "horizontal2", "vertical2", "horizontal3", "vertical3", "top3", "left3", "bottom3", "right3", "horizontal4", "vertical4", "top4", "left4", "bottom4", "right4", "quad" CONFIG = CFG_VERT2 KWARG_CHANGE_CB_NAME = 'separatorMovedCommand' def __init__( self, parent, configuration=None, *a, **kw ): kw.setdefault( 'separatorMovedCommand', self.on_resize ) if configuration is None: assert self.CONFIG in self.POSSIBLE_CONFIGS configuration = self.CONFIG kw[ 'configuration' ] = configuration kw.pop( 'cn', None ) BaseMelLayout.__init__( self, parent, *a, **kw ) self( e=True, **kw ) if self.PREF_OPTION_VAR: if cmd.optionVar( ex=self.PREF_OPTION_VAR ): storedSize = cmd.optionVar( q=self.PREF_OPTION_VAR ) for idx, size in enumerate( filesystem.iterBy( storedSize, 2 ) ): self.setPaneSize( idx, size ) def __getitem__( self, idx ): idx += 1 #indices are 1-based... fuuuuuuu alias! kw = { 'q': True, 'pane%d' % idx: True } return BaseMelUI.FromStr( self( **kw ) ) def __setitem__( self, idx, ui ): idx += 1 #indices are 1-based... fuuuuuuu alias! return self( e=True, setPane=(ui, idx) ) def getConfiguration( self ): return self( q=True, configuration=True ) def setConfiguration( self, ui ): return self( e=True, configuration=ui ) def getPaneUnderPointer( self ): return BaseMelUI.FromStr( self( q=True, paneUnderPointer=True ) ) def getPaneActive( self ): return BaseMelUI.FromStr( self( q=True, activePane=True ) ) def getPaneActiveIdx( self ): return self( q=True, activePaneIndex=True ) - 1 #indices are 1-based... def getPaneSize( self, idx ): idx += 1 return self( q=True, paneSize=idx ) def setPaneSize( self, idx, size ): idx += 1 size = idx, size[0], size[1] return self( e=True, paneSize=size ) def setPaneWidth( self, idx, size ): idx += 1 curSize = self.getPaneSize( idx ) return self( e=True, paneSize=(idx, curSize[0], size) ) def setPaneHeight( self, idx, size ): idx += 1 curSize = self.getPaneSize( idx ) return self( e=True, paneSize=(idx, size, curSize[1]) ) ### EVENT HANDLERS ### def on_resize( self, *a ): if self.PREF_OPTION_VAR: size = self.getPaneSize( 0 ) cmd.optionVar( clearArray=self.PREF_OPTION_VAR ) for i in size: cmd.optionVar( iva=(self.PREF_OPTION_VAR, i) ) class MelFrameLayout(BaseMelLayout): WIDGET_CMD = cmd.frameLayout def setCollapseCB( self, cb ): BaseMelLayout.setChangeCB( self, cb ) def getCollapseCB( self ): return BaseMelLayout.getChangeCB( self ) def setExpandCB( self, cb ): self.setCB( 'expandCommand', cb ) def getExpandCB( self ): return self.getCB( 'expandCommand' ) def getCollapse( self ): return self( q=True, collapse=True ) def setCollapse( self, state, executeChangeCB=True ): self( e=True, collapse=state ) if executeChangeCB: if state: collapseCB = self.getCollapseCB() if callable( collapseCB ): collapseCB() else: expandCB = self.getExpandCB() if callable( expandCB ): expandCB() class BaseMelWidget(BaseMelUI): def setValue( self, value, executeChangeCB=True ): try: kw = { 'e': True, self.KWARG_VALUE_NAME: value } self.WIDGET_CMD( self, **kw ) except TypeError, x: common.printErrorStr( 'Running setValue method using %s command' % self.WIDGET_CMD ) raise if executeChangeCB: self._executeCB() def getValue( self ): kw = { 'q': True, self.KWARG_VALUE_NAME: True } return self.WIDGET_CMD( self, **kw ) def enable( self, state=True ): try: self( e=True, enable=bool( state ) ) #explicitly cast here in case we've been passed a non-bool. the maya.cmds binding interprets any non-boolean object as True it seems... except: pass def disable( self ): self.enable( False ) def getAnnotation( self ): return self( q=True, ann=True ) def setAnnotation( self, annotation ): self( e=True, ann=annotation ) setEnabled = enable def getEnabled( self ): try: return self( q=True, enable=True ) except: return True def editable( self, state=True ): try: self( e=True, editable=bool( state ) ) except: pass def setEditable( self, state ): self.editable( state ) def getEditable( self ): return bool( self( q=True, ed=True ) ) def setFocus( self ): cmd.setFocus( self ) class MelLabel(BaseMelWidget): WIDGET_CMD = cmd.text KWARG_VALUE_NAME = 'l' KWARG_VALUE_LONG_NAME = 'label' def bold( self, state=True ): self( e=True, font='boldLabelFont' if state else 'plainLabelFont' ) getLabel = BaseMelWidget.getValue setLabel = BaseMelWidget.setValue class MelSpacer(MelLabel): def __new__( cls, parent, w=1, h=1 ): w = max( w, 1 ) h = max( h, 1 ) return MelLabel.__new__( cls, parent, w=w, h=h, l='' ) class MelButton(BaseMelWidget): WIDGET_CMD = cmd.button KWARG_CHANGE_CB_NAME = 'c' def bold( self, state=True ): self( e=True, font='boldLabelFont' if state else 'plainLabelFont' ) def getLabel( self ): return self( q=True, l=True ) def setLabel( self, label ): initialWidth = self.getWidth() self( e=True, l=label ) #seems maya screws with the width of the widget when setting the label - yay! self.setWidth( initialWidth ) class MelIconButton(MelButton): WIDGET_CMD = cmd.iconTextButton def setImage( self, imagePath, findInPaths=True ): self( e=True, image=str( imagePath ) ) def getImage( self ): return self( q=True, image=True ) def refresh( self ): img = self.getImage() self.setImage( '' ) self.setImage( img ) class MelIconCheckBox(MelIconButton): WIDGET_CMD = cmd.iconTextCheckBox KWARG_CHANGE_CB_NAME = 'cc' class MelCheckBox(BaseMelWidget): WIDGET_CMD = cmd.checkBox def __new__( cls, parent, *a, **kw ): #this craziness is so we can default the label to nothing instead of the widget's name... dumb, dumb, dumb labelArgs = 'l', 'label' for f in kw.keys(): if f == 'label': kw[ 'l' ] = kw.pop( 'label' ) break kw.setdefault( 'l', '' ) return BaseMelWidget.__new__( cls, parent, *a, **kw ) class MelRadioButton(BaseMelWidget): WIDGET_CMD = cmd.radioButton def getLabel( self ): return self( q=True, label=True ) def setLabel( self, label ): self( e=True, label=label ) def select( self ): self( e=True, select=True ) def isSelected( self ): return self( q=True, select=True ) class MelRadioCollection(unicode): def __new__( self ): new = unicode.__new__( cls, cmd.radioCollection() ) new._items = [] return new def addButton( self, button ): ''' adds the given button to this collection ''' self._items.append( button( e=True, collection=self ) ) def createButton( self, parent, **kw ): ''' creates a new radio button and adds it to the collection ''' button = MelRadioButton( parent, collection=self, **kw ) self._items.append( button ) return button def getItems( self ): ''' returns the radio buttons in the collection ''' return self._items[:] def count( self ): ''' returns the items in the collection ''' return len( self._items ) def getSelected( self ): ''' returns the selected MelRadio button instance ''' selItemStr = self( q=True, sl=True ) for item in self._items: if str( item ) == selItemStr: return item class MelSeparator(BaseMelWidget): WIDGET_CMD = cmd.separator class MelIntField(BaseMelWidget): WIDGET_CMD = cmd.intField DEFAULT_WIDTH = 30 class MelFloatField(BaseMelWidget): WIDGET_CMD = cmd.floatField class MelTextField(BaseMelWidget): WIDGET_CMD = cmd.textField DEFAULT_WIDTH = 150 KWARG_VALUE_NAME = 'tx' KWARG_VALUE_LONG_NAME = 'text' def setValue( self, value, executeChangeCB=True ): if not isinstance( value, unicode ): value = unicode( value ) BaseMelWidget.setValue( self, value, executeChangeCB ) def clear( self, executeChangeCB=True ): self.setValue( '', executeChangeCB ) class MelTextScrollField(MelTextField): WIDGET_CMD = cmd.scrollField class MelScrollField(MelTextField): WIDGET_CMD = cmd.scrollField class MelNameField(MelTextField): WIDGET_CMD = cmd.nameField def getValue( self ): obj = self( q=True, o=True ) if obj: return obj return None getObj = getValue def setValue( self, obj, executeChangeCB=True ): if not isinstance( obj, basestring ): obj = str( obj ) self( e=True, o=obj ) if executeChangeCB: self._executeCB() setObj = setValue def clear( self ): self.setValue( None ) class MelObjectSelector(MelForm): def __new__( cls, parent, label='Node->', obj=None, labelWidth=None ): return MelForm.__new__( cls, parent ) def __init__( self, parent, label='Node->', obj=None, labelWidth=None ): MelForm.__init__( self, parent ) self.UI_label = MelButton( self, l=label, c=self.on_setValue ) self.UI_obj = MelNameField( self ) if labelWidth is not None: self.UI_label.setWidth( labelWidth ) if obj is not None: self.UI_obj.setValue( obj ) self( e=True, af=((self.UI_label, 'left', 0), (self.UI_obj, 'right', 0)), ac=((self.UI_obj, 'left', 0, self.UI_label)) ) self.UI_menu = MelPopupMenu( self.UI_label, pmc=self.buildMenu ) self.UI_menu = MelPopupMenu( self.UI_obj, pmc=self.buildMenu ) def buildMenu( self, menu, menuParent ): cmd.menu( menu, e=True, dai=True ) obj = self.getValue() enabled = cmd.objExists( obj ) if obj else False MelMenuItem( menu, label='select obj', en=enabled, c=self.on_select ) MelMenuItemDiv( menu ) MelMenuItem( menu, label='clear obj', c=self.on_clear ) def getValue( self ): return self.UI_obj.getValue() def setValue( self, value, executeChangeCB=True ): return self.UI_obj.setValue( value, executeChangeCB ) def setChangeCB( self, cb ): return self.UI_obj.setChangeCB( cb ) def getChangeCB( self ): return self.UI_obj.getChangeCB() def clear( self ): self.UI_obj.clear() def getLabel( self ): return self.UI_label.getValue() def setLabel( self, label ): self.UI_label.setValue( label ) ### EVENT HANDLERS ### def on_setValue( self, *a ): sel = cmd.ls( sl=True ) if sel: self.setValue( sel[ 0 ] ) def on_select( self, *a ): cmd.select( self.getValue() ) def on_clear( self, *a ): self.clear() class _BaseSlider(BaseMelWidget): DISABLE_UNDO_ON_DRAG = False def __new__( cls, parent, minValue=0, maxValue=100, defaultValue=None, *a, **kw ): changeCB = kw.pop( 'changeCommand', kw.pop( 'cc', None ) ) dragCB = kw.pop( 'dragCommand', kw.pop( 'dc', None ) ) new = BaseMelWidget.__new__( cls, parent, minValue=minValue, maxValue=maxValue, *a, **kw ) new._isDragging = False new._preChangeCB = None new._postChangeCB = None new._changeCB = changeCB return new def __init__( self, parent, minValue=0, maxValue=100, defaultValue=None, *a, **kw ): BaseMelWidget.__init__( self, parent, *a, **kw ) kw = {} kw[ 'changeCommand' ] = self.on_change kw[ 'dragCommand' ] = self.on_drag self( e=True, **kw ) self._defaultValue = defaultValue self._initialUndoState = cmd.undoInfo( q=True, state=True ) def setPreChangeCB( self, cb ): ''' the callback executed when the slider is first pressed. the preChangeCB should take no args ''' self._preChangeCB = cb def getPreChangeCB( self ): return self._preChangeCB def setChangeCB( self, cb ): ''' the callback that is executed when the value is changed. the changeCB should take a single value arg ''' self._changeCB = cb def getChangeCB( self ): return self._changeCB def setPostChangeCB( self, cb ): ''' the callback executed when the slider is released. the postChangeCB should take a single value arg just like the changeCB ''' self._postChangeCB = cb def getPostChangeCB( self ): return self._postChangeCB def reset( self, executeChangeCB=True ): value = self._defaultValue if value is None: value = self( q=True, min=True ) self.setValue( value, executeChangeCB ) ### EVENT HANDLERS ### def on_change( self, value ): self._isDragging = False #restore undo if thats what we need to do if self.DISABLE_UNDO_ON_DRAG: if self._initialUndoState: cmd.undoInfo( stateWithoutFlush=True ) if callable( self._postChangeCB ): self._postChangeCB( value ) def on_drag( self, value ): if self._isDragging: if callable( self._changeCB ): self._changeCB( value ) else: self._initialUndoState = cmd.undoInfo( q=True, state=True ) if self.DISABLE_UNDO_ON_DRAG: cmd.undoInfo( stateWithoutFlush=False ) if callable( self._preChangeCB ): self._preChangeCB() self._isDragging = True class MelFloatSlider(_BaseSlider): WIDGET_CMD = cmd.floatSlider class MelIntSlider(_BaseSlider): WIDGET_CMD = cmd.intSlider class MelTextScrollList(BaseMelWidget): ''' NOTE: you probably want to use the MelObjectScrollList instead! ''' WIDGET_CMD = cmd.textScrollList KWARG_CHANGE_CB_NAME = 'sc' ALLOW_MULTI_SELECTION = False def __new__( cls, parent, *a, **kw ): if 'ams' not in kw and 'allowMultiSelection' not in kw: kw[ 'ams' ] = cls.ALLOW_MULTI_SELECTION return BaseMelWidget.__new__( cls, parent, *a, **kw ) def __init__( self, parent, *a, **kw ): BaseMelWidget.__init__( self, parent, *a, **kw ) self._appendCB = None def __getitem__( self, idx ): return self.getItems()[ idx ] def __contains__( self, value ): return value in self.getItems() def __len__( self ): return self( q=True, numberOfItems=True ) def setItems( self, items ): self.clear() for i in items: self.append( i ) def getItems( self ): return self( q=True, ai=True ) def getAllItems( self ): return self( q=True, ai=True ) def setAppendCB( self, cb ): self._appendCB = cb def getSelectedItems( self ): return self( q=True, si=True ) or [] def getSelectedIdxs( self ): return [ idx-1 for idx in self( q=True, sii=True ) or [] ] def selectByIdx( self, idx, executeChangeCB=False ): self( e=True, selectIndexedItem=idx+1 ) #indices are 1-based in mel land - fuuuuuuu alias!!! if executeChangeCB: self._executeCB() def attemptToSelect( self, idx, executeChangeCB=False ): ''' attempts to select the item at index idx - if the specific index doesn't exist, it tries to select the closest item to the given index ''' if len( self ) == 0: if executeChangeCB: self._executeCB() return if idx >= len( self ): idx = len( self ) - 1 #set to the end most item if idx < 0: idx = 0 self.selectByIdx( idx, executeChangeCB ) def selectByValue( self, value, executeChangeCB=False ): self( e=True, selectItem=value ) if executeChangeCB: self._executeCB() def append( self, item ): self( e=True, append=item ) def appendItems( self, items ): for i in items: self.append( i ) def removeByIdx( self, idx ): self( e=True, removeIndexedItem=idx+1 ) def removeByValue( self, value ): self( e=True, removeItem=value ) def removeSelectedItems( self ): for idx in self.getSelectedIdxs(): self.removeByIdx( idx ) def allowMultiSelect( self, state ): self( e=True, ams=state ) def clear( self ): self( e=True, ra=True ) def clearSelection( self, executeChangeCB=False ): self( e=True, deselectAll=True ) if executeChangeCB: self._executeCB() def moveSelectedItemsUp( self, count=1 ): ''' moves selected items "up" <count> units ''' #these are the selected items as they appear in the UI - we need to map them to "real" indices selIdxs = self.getSelectedIdxs() selItems = self.getSelectedItems() items = self.getAllItems() realIdxs = [] for selItem in selItems: for n, item in enumerate( items ): if selItem is item: realIdxs.append( n ) break count = min( count, realIdxs[ 0 ] ) #we can't move more units up than the smallest selected index if not count: return realIdxs.sort() for idx in realIdxs: item = items.pop( idx ) items.insert( idx-count, item ) self.setItems( items ) #re-setup selection self.clearSelection() for item in selItems: self.selectByValue( item, False ) def moveSelectedItemsDown( self, count=1 ): ''' moves selected items "down" <count> units ''' #these are the selected items as they appear in the UI - we need to map them to "real" indices selIdxs = self.getSelectedIdxs() selItems = self.getSelectedItems() items = self.getAllItems() realIdxs = [] for selItem in selItems: for n, item in enumerate( items ): if selItem is item: realIdxs.append( n ) break realIdxs.sort() maxIdx = len( items )-1 count = min( count, maxIdx - realIdxs[-1] ) #we can't move more units down than the largest selected index if not count: return realIdxs.reverse() for idx in realIdxs: item = items.pop( idx ) items.insert( idx+count, item ) self.setItems( items ) #re-setup selection self.clearSelection() for item in selItems: self.selectByValue( item, False ) class MelObjectScrollList(MelTextScrollList): ''' Unlike MelTextScrollList, this class will actually store and return python objects and display them using either their native string representation (ie __str__) which is done by passing the object to itemAsStr which is an overridable instance method. It also lets you set selection by passing either python objects, the string representations for those objects or indices. It also provides the ability to set filters on the data. What the widget stores and what it displays can be different, making it easy to write UI to access internal data without having to write glue code to convert to/from UI representation. NOTE: you almost always want to use this class over the MelTextScrollList class... its just better. ''' #if true the objects are displayed without their namespaces DISPLAY_NAMESPACES = False DISPLAY_NICE_NAMES = False #should we perform caseless filtering? FILTER_CASELESS = True def __init__( self, parent, *a, **kw ): MelTextScrollList.__init__( self, parent, *a, **kw ) self._items = [] self._visibleItems = [] self._filterStr = None self._compiledFilter = None def __contains__( self, item ): return item in self._visibleItems def itemAsStr( self, item ): itemStr = str( item ) if not self.DISPLAY_NAMESPACES: withoutNamespace = str( item ).split( ':' )[ -1 ] itemStr = withoutNamespace.split( '|' )[ -1 ] if self.DISPLAY_NICE_NAMES: itemStr = names.camelCaseToNice( itemStr ) return itemStr def getFilter( self ): return self._filterStr def setFilter( self, filterStr, updateUI=True ): if not filterStr: self._filterStr = None self._compiledFilter = None else: self._filterStr = filterStr #build the compiled regular expression reArgs = [ filterStr ] if self.FILTER_CASELESS: reArgs.append( re.IGNORECASE ) self._compiledFilter = re.compile( *reArgs ) #update the UI if updateUI: self.update() def clearFilter( self ): self.setFilter( None ) def doesItemPassFilter( self, item ): return self.doesItemStrPassFilter( self.itemAsStr( item ) ) def doesItemStrPassFilter( self, itemStr ): if not self._filterStr: return True if self.FILTER_CASELESS: itemStr = itemStr.lower() if self._filterStr in itemStr: return True if self._compiledFilter is None: return True try: if self._compiledFilter.match( itemStr ): return True except: return True return False def getItems( self ): ''' returns the list of visible items NOTE: if the widget has a filter set, this won't return ALL items, just the visible ones. To get a list of all items, use getAllItems() ''' return self._visibleItems[:] #return a copy of the visible items list def getAllItems( self ): return self._items[:] #return a copy of the items list def getSelectedItems( self ): selectedIdxs = self.getSelectedIdxs() return [ self._visibleItems[ idx ] for idx in selectedIdxs ] def selectByValue( self, value, executeChangeCB=False ): if value in self._visibleItems: idx = self._visibleItems.index( value ) + 1 #mel indices are 1-based... self( e=True, sii=idx ) else: valueStr = self.itemAsStr( value ) for idx, item in enumerate( self._visibleItems ): if self.itemAsStr( item ) == valueStr: self( e=True, sii=idx+1 ) #mel indices are 1-based... if executeChangeCB: self._executeCB() def selectItems( self, items, executeChangeCB=False ): ''' provides an efficient way of selecting many items at once ''' visibleSet = set( self._visibleItems ) itemsSet = set( items ) #get a list of items that are guaranteed to be in the UI itemsToSelect = itemsSet.intersection( visibleSet ) for idx, item in enumerate( self._visibleItems ): if item in itemsToSelect: self( e=True, sii=idx+1 ) if executeChangeCB: self._executeCB() def append( self, item, executeAppendCB=True ): self._items.append( item ) itemStr = self.itemAsStr( item ) if self.doesItemStrPassFilter( itemStr ): self._visibleItems.append( item ) self( e=True, append=itemStr ) if executeAppendCB: if callable( self._appendCB ): self._appendCB( item ) def removeByIdx( self, idx ): ''' removes an item by its index in the visible list of items ''' #first pop the item out of the list of visible items item = self._visibleItems.pop( idx ) self( e=True, removeIndexedItem=idx+1 ) #now pop the item out of the _items list idx = self._items.index( item ) self._items.pop( idx ) def removeByValue( self, value ): if value in self._items: idx = self._items.index( value ) self._items.pop( idx ) if value in self._visibleItems: idx = self._visibleItems.index( value ) self._visibleItems.pop( idx ) self( e=True, rii=idx+1 ) #mel indices are 1-based... else: valueStr = self.itemAsStr( value ) for itemList in (self._visibleItems, self._items): for idx, item in enumerate( itemList ): if self.itemAsStr( item ) == valueStr: itemList.pop( idx ) self( e=True, rii=idx+1 ) #mel indices are 1-based... def clear( self ): self._items = [] self._visibleItems = [] self( e=True, ra=True ) def update( self, maintainSelection=True ): ''' removes and re-adds the items in the UI ''' selItems = self.getSelectedItems() #remove all items from the list self._visibleItems = [] self( e=True, ra=True ) #now re-generate their string representations for item in self.getAllItems(): itemStr = self.itemAsStr( item ) if self.doesItemStrPassFilter( itemStr ): self._visibleItems.append( item ) self( e=True, append=itemStr ) if maintainSelection: for item in selItems: for idx, visItem in enumerate( self._visibleItems ): if item is visItem: self.selectByIdx( idx, False ) class MelSetMemebershipList(MelObjectScrollList): ALLOWED_NODE_TYPES = None #if None then ANY node type is allowed in the set - otherwise only types in the iterable are allowed to be added to the set ALLOW_MULTI_SELECTION = True def __init__( self, parent, **kw ): MelObjectScrollList.__init__( self, parent, **kw ) self.objectSets = [] self( e=True, dcc=self.on_doubleClickItem ) self.POP_ops = MelPopupMenu( self, pmc=self.buildMenu ) self._addHandler = None def getSets( self ): return self.objectSets[:] def setSets( self, objectSets ): if not isinstance( objectSets, list ): objectSets = [ objectSets ] self.objectSets = objectSets self.update() def getAllItems( self ): items = cmd.sets( self.objectSets, q=True ) or [] items.sort() return removeDupes( items ) def _addItems( self, items ): handler = self._addHandler isHandlerCallable = callable( self._addHandler ) items = self.filterItems( items ) if items: for objectSet in self.objectSets: if isHandlerCallable: handler( objectSet, items ) else: cmd.sets( items, add=objectSet ) self.update() def _setItems( self, items ): items = self.filterItems( items ) if items: for objectSet in self.objectSets: cmd.sets( clear=objectSet ) self._addItems( items ) def _removeItems( self, items ): if items: for objectSet in self.objectSets: cmd.sets( items, remove=objectSet ) self.update() def _removeAllItems( self ): for objectSet in self.objectSets: cmd.sets( clear=objectSet ) self.update() def buildMenu( self, menu, menuParent ): cmd.menu( menu, e=True, dai=True ) MelMenuItem( menu, l='ADD selected objects to set', c=self.on_addItem ) MelMenuItem( menu, l='REPLACE set items with selected objects', c=self.on_replaceItem ) MelMenuItem( menu, l='REMOVE selected objects from set', c=self.on_removeItem ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='remove HIGHLIGHTED objects from set', c=self.on_removeHighlighted ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='SELECT highlighted objects', c=self.on_doubleClickItem ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='update UI', c=self.on_update ) MelMenuItem( menu, cb=self.DISPLAY_NAMESPACES, l='Show Namespaces', c=self.on_showNameSpaces ) MelMenuItem( menu, cb=self.DISPLAY_NICE_NAMES, l='Show Nice Names', c=self.on_showNiceNames ) def removeItems( self, items ): curItems = self.getItems() if curItems: newItems = curItems.difference( items ) if len( curItems ) == len( newItems ): return self.setItems( newItems ) def filterItems( self, items ): if not self.ALLOWED_NODE_TYPES: return items filteredItems = [] for item in items: if nodeType in self.ALLOWED_NODE_TYPES: if cmd.objectType( item, isAType=nodeType ): filteredItems.append( item ) return filteredItems ### EVENT HANDLERS ### def on_doubleClickItem( self, *a ): sel = self.getSelectedItems() if sel: cmd.select( sel ) def on_addItem( self, *a ): self._addItems( cmd.ls( sl=True ) ) def on_replaceItem( self, *a ): self._setItems( cmd.ls( sl=True ) ) def on_removeItem( self, *a ): self._removeItems( cmd.ls( sl=True ) ) def on_removeHighlighted( self, *a ): self._removeItems( self.getSelectedItems() ) def on_update( self, *a ): self.update() def on_showNameSpaces( self, *a ): self.DISPLAY_NAMESPACES = not self.DISPLAY_NAMESPACES self.update() def on_showNiceNames( self, *a ): self.DISPLAY_NICE_NAMES = not self.DISPLAY_NICE_NAMES self.update() class MelTreeView(BaseMelWidget): ''' Thanks to Dave Shaw for the majority of this implementation ''' WIDGET_CMD = cmd.treeView #the valid button "types" BUTTON_TYPES = BT_PUSH_BUTTON, BT_2STATE, BT_3STATE = 'pushButton', '2StateButton', '3StateButton' #the valid button "states" BUTTON_STATES = BS_UP, BS_DOWN, BS_BETWEEN = 'buttonUp', 'buttonDown', 'buttonThirdState' def __init__( self, parent, *a, **kw ): BaseMelWidget.__init__( self, parent, *a, **kw ) self( e=True, **kw ) self._pressCBs = {} def addItem( self, itemName, itemParent=None ): self( edit=True, addItem=(itemName, itemParent) ) def doesItemExist( self, itemName ): return self( q=True, itemExists=itemName ) def getItemIndex( self, itemName ): return self( q=True, itemIndex=itemName ) def getItemParent( self, itemName ): return self( q=True, itemParent=itemName ) def isItemSelected( self, itemName ): return self( q=True, itemSelected=itemName ) def setButtonLabel( self, itemName, buttonIndex, label ): self( e=True, buttonTextIcon=(itemName, buttonIndex, label) ) def setButtonState( self, itemName, buttonIndex, state ): ''' There are only 3 valid states: buttonUp - button is up buttonDown - button is down buttonThirdState - button is in state three (used by the "3StateButton" button style) ''' if state not in self.BUTTON_STATES: raise TypeError( "Invalid button state: %s" % state ) self( e=True, buttonState=(a_item, a_button, a_state) ) def setButtonStyle( self, itemName, buttonIndex, style ): ''' Possible button types: pushButton - two possible states, button is reset to up upon release 2StateButton - two possible states, button changes state on click 3StateButton - three button states, button changes state on click ''' if style not in self.BUTTON_TYPES: raise TypeError( "Invalid button style: %s" % style ) self( e=True, buttonStyle=(itemName, buttonIndex, style) ) def removeAll( self ): self( e=True, removeAll=True ) def setPressCommand( self, buttonIndex, cb ): ''' Sets the python callback function to be invoked when the button at <buttonIndex> is pressed. The callback should take two args - the first is the itemName that the button pressed belongs to, and the second is the button press state that has just been activated ''' #generate a likely unique name for a global proc - treeView press commands have to be mel proc names and can't be python #callbacks. This hack makes it easier to work with tree view callbacks and keep everything in python melCmdName = '__%s_pressCB%d' % (self, buttonIndex) #construct the mel proc melCmd = """global proc %s( string $str, int $index ) { python( "import baseMelUI; baseMelUI.BaseMelUI.FromStr( '%s' )._executePressCB( %d, '"+ $str +"', "+ $index +" );" ); }""" % (melCmdName, self, buttonIndex) #execute the proc we just constructed maya.mel.eval( melCmd ) #store the python function we want to execute - NOTE: the function needs to take 3 args: func( str, int ) - see treeView docs for details self._pressCBs[ buttonIndex ] = cb #tell the widget what its press callback is... self( e=True, pressCommand=(buttonIndex, melCmdName) ) def getPressCommand( self, buttonIndex ): try: return self._pressCBs[ buttonIndex ] except KeyError: return None def _executePressCB( self, a_button, *a ): self._pressCBs[ a_button ]( *a ) def getItemChildren( self, itemName ): return self( q=True, children=itemName ) def clearSelection( self ): self( e=True, clearSelection=True ) class _MelBaseMenu(BaseMelWidget): DYNAMIC = False KWARG_VALUE_NAME = 'l' KWARG_VALUE_LONG_NAME = 'label' KWARG_CHANGE_CB_NAME = 'pmc' DEFAULT_WIDTH = None DEFAULT_HEIGHT = None STATIC_CHOICES = [] #if you populate this variable you'll have the options automatically appear in the list unless its a DYNAMIC menu def __init__( self, parent, *a, **kw ): super( _MelBaseMenu, self ).__init__( parent, *a, **kw ) if self.DYNAMIC: if 'pmc' not in kw and 'postMenuCommand' not in kw: #make sure there isn't a pmc passed in self( e=True, pmc=self._build ) else: for item in self.STATIC_CHOICES: self.append( item ) def __len__( self ): return self( q=True, numberOfItems=True ) def __contains__( self, item ): return item in self.getItems() def _build( self, menu, menuParent ): ''' converts the menu and menuParent args into proper MelXXX instance ''' menu = BaseMelWidget.FromStr( menu ) #this should be the same as "self"... menuParent = BaseMelWidget.FromStr( menuParent ) self.build( menu, menuParent ) def build( self, menu, menuParent ): pass def getMenuItems( self ): itemNames = self( q=True, itemArray=True ) or [] return [ MelMenuItem.FromStr( itemName ) for itemName in itemNames ] def getItems( self ): return [ menuItem.getValue() for menuItem in self.getMenuItems() ] def append( self, strToAppend ): return MelMenuItem( self, label=strToAppend ) def clear( self ): for menuItem in self.getMenuItems(): cmd.deleteUI( menuItem ) class MelMenu(_MelBaseMenu): WIDGET_CMD = cmd.menu DYNAMIC = True def __new__( self, *a, **kw ): return _MelBaseMenu.__new__( self, None, *a, **kw ) def __init__( self, *a, **kw ): super( _MelBaseMenu, self ).__init__( None, *a, **kw ) if self.DYNAMIC: if 'pmc' not in kw and 'postMenuCommand' not in kw: #make sure there isn't a pmc passed in self( e=True, pmc=self._build ) def iterParents( self ): return iter([]) def getFullName( self ): return str( self ) def _build( self, *a ): self.build() def build( self, *a ): pass class MelOptionMenu(_MelBaseMenu): WIDGET_CMD = cmd.optionMenu KWARG_VALUE_NAME = 'v' KWARG_VALUE_LONG_NAME = 'value' KWARG_CHANGE_CB_NAME = 'cc' DYNAMIC = False def __getitem__( self, idx ): return self.getItems()[ idx ] def __setitem__( self, idx, value ): menuItems = self.getMenuItems() menuItems[ idx ].setValue( value ) def getMenuItems( self ): itemNames = self( q=True, itemListShort=True ) or [] return [ MelMenuItem.FromStr( itemName ) for itemName in itemNames ] def selectByIdx( self, idx, executeChangeCB=True ): self( e=True, select=idx+1 ) #indices are 1-based in mel land - fuuuuuuu alias!!! if executeChangeCB: self._executeCB() def selectByValue( self, value, executeChangeCB=True ): idx = self.getItems().index( value ) self.selectByIdx( idx, executeChangeCB ) def setValue( self, value, executeChangeCB=True ): self.selectByValue( value, executeChangeCB ) def getSelectedIdx( self ): return self( q=True, select=True ) - 1 #indices are 1-based in mel land - fuuuuuuu alias!!! class MelObjectMenu(MelOptionMenu): def __new__( cls, parent, *a, **kw ): new = MelOptionMenu.__new__( cls, parent, *a, **kw ) new._objs = [] return new def _itemAsStr( self, item ): return str( item ) def __setitem__( self, idx, value ): menuItems = self.getMenuItems() menuItems[ idx ].setValue( self._itemAsStr( value ) ) def append( self, obj ): MelOptionMenu.append( self, obj ) self._objs.append( obj ) def getItems( self ): return self._objs def clear( self ): MelOptionMenu.clear( self ) self._objs = [] class MelPopupMenu(_MelBaseMenu): WIDGET_CMD = cmd.popupMenu DYNAMIC = True def iterParents( self ): return iter([]) def getFullName( self ): return str( self ) def clear( self ): self( e=True, dai=True ) #clear the menu class MelMenuItem(BaseMelWidget): WIDGET_CMD = cmd.menuItem KWARG_VALUE_NAME = 'l' KWARG_VALUE_LONG_NAME = 'label' KWARG_CHANGE_CB_NAME = 'pmc' DEFAULT_WIDTH = None DEFAULT_HEIGHT = None def iterParents( self ): return iter([]) def getFullName( self ): return str( self ) class MelMenuItemDiv(MelMenuItem): def __new__( cls, parent, *a, **kw ): kw[ 'divider' ] = True super( MelMenuItemDiv, cls ).__new__( cls, parent, *a, **kw ) class MelIteratorUI(object): def __init__( self, iterableObject, maxRange=None, **kw ): self.progress = 0 self.items = iterableObject if maxRange is None: maxRange = len( iterableObject ) self._maxRange = maxRange cmd.progressWindow( progress=0, isInterruptable=True, minValue=0, maxValue=maxRange, **kw ) def __iter__( self ): progressWindow = cmd.progressWindow maxRange = self._maxRange progress = 0 try: for item in self.items: yield item if progressWindow( q=True, ic=True ): return progress += 1 progressWindow( e=True, progress=progress ) finally: self.close() def __del__( self ): self.close() def isCancelled( self ): return cmd.progressWindow( q=True, ic=True ) def close( self ): cmd.progressWindow( e=True, ep=True ) def makePathSceneRelative( filepath ): #make sure it is actually an absolute path... if filepath.isAbs(): curSceneDir = filesystem.Path( cmd.file( q=True, sn=True ) ).up() filepath = filepath - curSceneDir return filepath def buildLabelledWidget( parent, label, labelWidth, WidgetClass, *a, **kw ): layout = MelHSingleStretchLayout( parent ) lblKw = { 'align': 'left' } if label: lblKw[ 'l' ] = label if labelWidth: lblKw[ 'w' ] = labelWidth lbl = MelLabel( layout, **lblKw ) ui = WidgetClass( layout, *a, **kw ) layout.setStretchWidget( ui ) layout.layout() return ui, lbl, layout def labelledUIClassFactory( baseCls ): ''' this class factory creates "labelled" widget classes. a labelled widget class acts just like the baseCls instance except that it has a label NOTE: the following constructor keywords can be used: llabel, ll sets the text label for the widget llabelWidth, llw sets the label width llabelAlign, lla sets the label alignment the keyword "label" isn't used because the class might be wrapping a widget that validly has a label such as MelButton or MelCheckbox ''' clsName = 'Labelled%s' % baseCls.__name__.replace( 'Mel', '' ) class _tmp(MelHSingleStretchLayout): _IS_SETUP = False def __new__( cls, parent, *a, **kw ): #extract any specific keywords from the dict before setting up the instance label = kw.pop( 'llabel', kw.pop( 'll', '<-no label->' ) ) labelWidth = kw.pop( 'llabelWidth', kw.pop( 'llw', None ) ) labelAlign = kw.pop( 'llabelAlign', kw.pop( 'lla', 'left' ) ) self = MelHSingleStretchLayout.__new__( cls, parent ) self.UI_lbl = lbl = MelLabel( self, l=label, align=labelAlign ) if labelWidth: lbl.setWidth( labelWidth ) self.ui = ui = baseCls( self, *a, **kw ) self.setStretchWidget( ui ) self.layout() self( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) ) #these functions are built within the constructor scope for a few reasons #first we get access to the ui object without having to go via a __getattr__ call #second we can't put all the functionality into the __getattr__ and __setattr__ methods on the _tmp class because they will interfere with the super class' constructor (where most of the work is done) #so basically construct these functions here and store them as _get and _set, and have the real __getattr__ and __setattr__ methods look for them once the instance has been properly constructed def _get( self, attr ): if attr in self.__dict__: return self.__dict__[ attr ] val = getattr( ui, attr, None ) if val is None: raise AttributeError( "No attribute '%s' was found on the object or its '%s' widget member" % (attr, baseCls) ) return val def _set( self, attr, value ): if attr in self.__dict__: setattr( self, attr, value ) setattr( ui, attr, value ) self._get = _get self._set = _set self._IS_SETUP = True return self def __getattr__( self, attr ): if self._IS_SETUP: return self._get( self, attr ) return super( MelHSingleStretchLayout, self ).__getattr__( attr ) def __setattr__( self, attr, value ): if self._IS_SETUP: self._set( self, attr, value ) return super( MelHSingleStretchLayout, self ).__setattr__( attr, value ) #add some convenience methods for querying and setting the label and label width - they're named deliberately named awkwardly, see the class doc above for more information def getLlabel( self ): self.UI_lbl.getValue() def setLlabel( self, label ): self.UI_lbl.setValue( label ) def getLlabelWidth( self ): self.UI_lbl.setWidth() def setLlabelWidth( self, width ): self.UI_lbl.setWidth( width ) def getWidget( self ): return self.ui _tmp.__name__ = clsName _tmp.__doc__ = baseCls.__doc__ return _tmp #now construct some Labelled classes LabelledTextField = labelledUIClassFactory( MelTextField ) LabelledIntField = labelledUIClassFactory( MelIntField ) LabelledFloatField = labelledUIClassFactory( MelFloatField ) LabelledFloatSlider = labelledUIClassFactory( MelFloatSlider ) LabelledIntSlider = labelledUIClassFactory( MelIntSlider ) LabelledOptionMenu = labelledUIClassFactory( MelOptionMenu ) class MayaNode(object): pass UI_FOR_PY_TYPES = { bool: MelCheckBox, int: MelIntField, float: MelFloatField, basestring: MelTextField, list: MelTextScrollList, tuple: MelTextScrollList, MayaNode: MelObjectSelector } def getBuildUIMethodForObject( obj, typeMapping=None ): if typeMapping is None: typeMapping = UI_FOR_PY_TYPES objType = obj if type( obj ) is type else type( obj ) #first see if there is an exact type match in the dict buildClass = None try: buildClass = typeMapping[ objType ] except KeyError: #if not, see if there is an inheritance match - its possible there may by multiple matches #however, so we need to check them all and see which is the most appropriate mro = list( inspect.getmro( objType ) ) bestMatch = None for aType, aBuildClass in typeMapping.iteritems(): if aType in mro: bestMatch = mro.index( aType ) if bestMatch: buildClass = aBuildClass break return buildClass def buildUIForObject( obj, parent, typeMapping=None ): ''' ''' buildClass = getBuildUIMethodForObject( obj, typeMapping ) if buildClass is None: raise MelUIError( "there is no build class defined for object's of type %s (%s)" % (type( obj ), obj) ) ui = buildClass( parent ) ui.setValue( obj ) return ui class BaseMelWindow(BaseMelUI): ''' This is a wrapper class for a mel window to make it behave a little more like an object. It inherits from str because thats essentially what a mel widget is. Objects of this class are callable. Calling an object is basically the same as passing the given args to the cmd.window maya command: aWindow = BaseMelWindow() aWindow( q=True, exists=True ) is the same as doing: aWindow = cmd.window() cmd.window( aWindow, q=True, exists=True ) ''' WINDOW_NAME = 'unnamed_window' WINDOW_TITLE = 'Unnamed Tool' RETAIN = False DEFAULT_SIZE = 250, 250 DEFAULT_MENU = 'File' DEFAULT_MENU_IS_HELP = False #set this class variable to a 3-tuple containing toolName, authorEmailAddress, helpPage #if you don't have a help page you can set the third tuple value to None #example: #HELP_MENU = 'testTool', 'mel@macaronikazoo.com', 'http://www.macaronikazoo.com/docs/Space_Switching' HELP_MENU = None FORCE_DEFAULT_SIZE = True @classmethod def Exists( cls ): ''' returns whether there is an instance of this class already open ''' return cmd.window( cls.WINDOW_NAME, ex=True ) @classmethod def Get( cls ): ''' returns the existing instance ''' return cls.FromStr( cls.WINDOW_NAME ) @classmethod def Close( cls ): ''' closes the window (if it exists) ''' if cls.Exists(): cmd.deleteUI( cls.WINDOW_NAME ) @classmethod def FromStr( cls, theStr ): #see if the data stored in the docTag is a valid class name - it might not be if teh user has used the docTag for something (why would they? there is no need, but still check...) possibleClassName = cmd.window( theStr, q=True, docTag=True ) theCls = BaseMelWindow.GetNamedSubclass( possibleClassName ) #if the data stored in the docTag doesn't map to a subclass, then we'll have to guess at the best class... if theCls is None: theCls = BaseMelWindow #at this point default to be an instance of the base widget class new = unicode.__new__( theCls, theStr ) #we don't want to run initialize on the object - just cast it appropriately return new def __new__( cls, *a, **kw ): kw.setdefault( 'title', cls.WINDOW_TITLE ) kw.setdefault( 'widthHeight', cls.DEFAULT_SIZE ) kw.setdefault( 'menuBar', True ) kw.setdefault( 'retain', cls.RETAIN ) if cmd.window( cls.WINDOW_NAME, ex=True ): cmd.deleteUI( cls.WINDOW_NAME ) new = unicode.__new__( cls, cmd.window( cls.WINDOW_NAME, **kw ) ) cmd.window( new, e=True, docTag=cls.__name__ ) #store the classname in the if cls.DEFAULT_MENU is not None: MelMenu( l=cls.DEFAULT_MENU, helpMenu=cls.DEFAULT_MENU_IS_HELP ) if cls.HELP_MENU: toolName, authorEmail, helpPage = cls.HELP_MENU helpMenu = new.getMenu( 'Help' ) MelMenuItem( helpMenu, l="Help...", en=helpPage is not None, c=lambda x: cmd.showHelp(helpPage, absolute=True) ) #MelMenuItemDiv( helpMenu ) #bugReporterUI.addBugReporterMenuItems( toolName, assignee=authorEmail, parent=helpMenu ) #validate the instance list - this should be done regularly, but not always because its kinda slow... BaseMelUI.ValidateInstanceList() #track the instance cls._INSTANCE_LIST.append( new ) return new def __init__( self, *a, **kw ): pass def __call__( self, *a, **kw ): return cmd.window( self, *a, **kw ) def setTitle( self, newTitle ): cmd.window( self.WINDOW_NAME, e=True, title=newTitle ) def getMenus( self ): menus = self( q=True, menuArray=True ) or [] return [ MelMenu.FromStr( m ) for m in menus ] def getMenu( self, menuName, createIfNotFound=True ): ''' returns the UI name for the menu with the given name ''' for m in self.getMenus(): if m.getValue() == menuName: return m if createIfNotFound: return MelMenu( l=menuName, helpMenu='help' in menuName.lower() ) def getLayout( self ): ''' returns the layout parented to this window ''' layoutNameStart = '%s|' % self existingLayouts = cmd.lsUI( controlLayouts=True, long=True ) for existingLayout in existingLayouts: if existingLayout.startswith( layoutNameStart ): toks = existingLayout.split( '|' ) return BaseMelLayout.FromStr( '%s|%s' % (self, toks[1]) ) def exists( self ): return cmd.window( self.WINDOW_NAME, q=True, ex=True ) def show( self, state=True, forceDefaultSize=None ): ''' if forceDefaultSize is None - it uses the FORCE_DEFAULT_SIZE class attribute ''' if state: cmd.showWindow( self ) else: self( e=True, visible=False ) if forceDefaultSize is None: forceDefaultSize = self.FORCE_DEFAULT_SIZE if forceDefaultSize: self( e=True, widthHeight=self.DEFAULT_SIZE ) def layout( self ): ''' forces the window to re calc layouts for children ''' curWidth = self( q=True, width=True ) self( e=True, width=curWidth+1 ) self( e=True, width=curWidth ) def processEvent( self, methodName, methodArgs, methodKwargs ): method = getattr( self, methodName, None ) if callable( method ): method( *methodArgs, **methodKwargs ) def close( self ): self.Close() ### ### PROCEDURAL UI BUILDING ### ### class UITypeError(TypeError): pass class PyFuncLayout(MelColumnLayout): ''' builds a default layout for a function - makes it easy to build UI for functions call by passing a python function object on construction like so: def sweet( this=12, isA=True, test=100 ): pass PyFuncLayout( parentLayout, sweet ) NOTE: the UI building looks for a bunch of special attributes on the function that can help control the presentation _hideArgs = [] #this is a list of attribute names that won't be presented in the UI _show = False #defaults to False - controls whether the function appears when building UI for a module (otherwise ignored) _expand = False #defaults to False - controls whether the frame layout for function is expanded or not by default when building UI for a module (ignored otherwise) ''' def __init__( self, parent, func ): MelColumnLayout.__init__( self, parent ) hideArgNames = [] if hasattr( func, '_hideArgs' ): hideArgNames = list( func._hideArgs ) self.argUIDict = {} #stores the argName->UI mapping self.func = func #stores the function passed in argNames, vargName, vkwargName, defaults = inspect.getargspec( func ) numDefaults = len( defaults ) numArgsWithoutDefaults = len( argNames ) - numDefaults #pad the defaults with empty strings for args that have no default - it'll be up to the user to write appropriate python expressions defaults = ([ '' ] * numArgsWithoutDefaults) + list( defaults ) labels = [] for argName, default in zip( argNames, defaults ): if argName in hideArgNames: continue hLayout = MelHLayout( self ) lbl = MelLabel( hLayout, l=names.camelCaseToNice( argName ) ) labels.append( lbl ) ui = buildUIForObject( default, hLayout ) ui.setChangeCB( filesystem.Callback( self.changeCB, argName ) ) hLayout.setWeight( lbl, 0 ) hLayout.layout() #finally stuff the ui into the argUIDict self.argUIDict[ argName ] = ui maxWidth = max( [ lbl.getWidth() for lbl in labels ] ) + 10 #10 for padding... for lbl in labels: lbl.setWidth( maxWidth ) MelButton( self, l='Execute %s' % names.camelCaseToNice( func.__name__ ), c=self.execute ) def changeCB( self, argName ): common.printInfoStr( '%s arg changed!' % argName ) def getArgDict( self ): argDict = {} for argName, ui in self.argUIDict.iteritems(): argDict[ argName ] = ui.getValue() #we need to get the args that have no default values and eval the values from the ui - it is assumed they're valid python expressions argNames, vargName, vkwargName, defaults = inspect.getargspec( self.func ) numArgsWithoutDefaults = len( argNames ) - len( defaults ) for argName in argNames[ :numArgsWithoutDefaults ]: uiStr = ui.getValue() if not uiStr: raise UITypeError( "No value given for %s arg" % argName ) argDict[ argName ] = eval( uiStr ) return argDict def execute( self, *a ): try: self.func( **self.getArgDict() ) except UITypeError: cmd.confirmDialog( "No value was entered for one of the args!", b='OK', db='OK') class PyFuncWindow(BaseMelWindow): ''' this is basically just a wrapper around the PyFuncLayout above. Its called in a similar way: def sweet( this=12, isA=True, test=100 ): pass PyFuncWindow( sweet ) ''' WINDOW_NAME = 'funcWindow' DEFAULT_MENU = None FORCE_DEFAULT_SIZE = False def __init__( self, func ): PyFuncLayout( self, func ) self.setTitle( '%s Window' % names.camelCaseToNice( func.__name__ ) ) self.show() class PyModuleLayout(MelColumnLayout): ''' builds a window for an entire module ''' def __init__( self, parent, module, showAll=False ): def func(): pass funcType = type( func ) #track the number of expanded frame layouts - we want to make sure at least one is expanded... numExpanded = 0 self.funcUIDict = {} for objName, obj in module.__dict__.iteritems(): if not isinstance( obj, funcType ): continue #skip any obj that already has UI built if obj in self.funcUIDict: continue show = False if hasattr( obj, '_show' ): show = obj._show #if we're not showing all, check the show state and skip accordingly if not showAll: if not show: continue expand = False if hasattr( obj, '_expand' ): expand = obj._expand if expand: numExpanded += 1 frame = MelFrameLayout( self, label=names.camelCaseToNice( objName ), cl=not expand, cll=True ) ui = PyFuncLayout( frame, obj ) self.funcUIDict[ obj ] = ui #if there are no expanded frames - expand the first one... if not numExpanded: children = self.getChildren() children[ 0 ].setCollapse( False ) class PyModuleWindow(BaseMelWindow): ''' this is basically just a wrapper around the PyFuncLayout above. Its called in a similar way: def sweet( this=12, isA=True, test=100 ): pass PyFuncWindow( sweet ) ''' WINDOW_NAME = 'moduleWindow' DEFAULT_MENU = None def __init__( self, module, showAll=False ): PyModuleLayout( self, module, showAll ) self.setTitle( '%s Window' % names.camelCaseToNice( module.__name__ ) ) self.show() #end
Python
from filesystem import * from baseMelUI import * from mappingUtils import * import names import api import presetsUI TOOL_NAME = 'zoo' TOOL_VER = 1 EXT = 'mapping' ui = None class MappingForm(MelHLayout): ''' Acts as a generic UI for editing "mappings". A mapping is basically just a dictionaries in maya, but they're used for things like animation transfer and weight transfer between one or more differing name sets. Mappings can be stored out to presets. ''' #args for controlling the name mapping algorithm - see the names.matchNames method for documentation on what these variables actually control STRIP_NAMESPACES = True PARITY_MATCH = True UNIQUE_MATCHING = False MATCH_OPPOSITE_PARITY = False THRESHOLD = names.DEFAULT_THRESHOLD #defines whether namespaces are hidden from the list view of the data - defaults to True. the namespaces are still stored, they just aren't displayed HIDE_NAMESPACES = True #if this is set to True, then sources can be mapped to multiple targets ALLOW_MULTI_SELECTION = True def __new__( cls, parent, *a, **kw ): return MelHLayout.__new__( cls, parent ) def __init__( self, parent, srcItems=None, tgtItems=None ): MelHLayout.__init__( self, parent ) self.expand = True self._srcToTgtDict = {} self._previousMappingFile = None szLeft = MelVLayout( self ) szRight = MelVLayout( self ) szLeft.expand = True szRight.expand = True self.UI_srcButton = srcBut = MelButton( szLeft, l='Source Items (click for menu)' ) self.UI_tgtButton = tgtBut = MelButton( szRight, l='Target Items (click for menu)' ) szLeft.setWeight( srcBut, 0 ) szRight.setWeight( tgtBut, 0 ) szHLeft = MelHLayout( szLeft ) szHLeft.expand = True szHRight = MelHLayout( szRight ) szHRight.expand = True vLayout = MelVLayout( szHLeft ) self.UI_but_srcUp = MelButton( vLayout, label='up', vis=True, width=22, c=self.on_src_up ) self.UI_but_srcDn = MelButton( vLayout, label='dn', vis=True, width=22, c=self.on_src_dn ) vLayout.layout() szHLeft.setWeight( vLayout, 0 ) self.UI_srcs = srcs = MelObjectScrollList( szHLeft, deleteKeyCommand=self.on_delete, doubleClickCommand=self.on_selectSrc ) self.UI_srcs.setChangeCB( self.on_selectItemSrc ) self.UI_tgts = MelObjectScrollList( szHRight, deleteKeyCommand=self.on_delete, doubleClickCommand=self.on_selectTgt, ams=True ) self.UI_tgts.setChangeCB( self.on_selectItemTgt ) #vLayout = MelVLayout( szHRight ) #self.UI_but_tgtUp = MelButton( vLayout, label='up', vis=False, width=1, c=self.on_tgt_up ) #self.UI_but_tgtDn = MelButton( vLayout, label='dn', vis=False, width=1, c=self.on_tgt_dn ) #vLayout.layout() szLeft.layout() szRight.layout() szHLeft.layout() szHRight.layout() self.layout() MelPopupMenu( self.UI_srcs, pmc=self.build_srcMenu ) MelPopupMenu( self.UI_tgts, pmc=self.build_tgtMenu ) MelPopupMenu( self.UI_srcButton, pmc=self.build_srcMenu ) MelPopupMenu( self.UI_tgtButton, pmc=self.build_tgtMenu ) MelPopupMenu( self.UI_srcButton, b=1, pmc=self.build_srcMenu ) MelPopupMenu( self.UI_tgtButton, b=1, pmc=self.build_tgtMenu ) if srcItems is not None: self.addSrcItems( srcItems ) if tgtItems is not None: self.addTgtItems( tgtItems ) @property def srcs( self ): return self.UI_srcs.getItems() @property def tgts( self ): return self.UI_tgts.getItems() def showUpDownButtons( self ): self.UI_but_srcUp.show() self.UI_but_srcDn.show() def hideUpDownButtons( self ): self.UI_but_srcUp.hide() self.UI_but_srcDn.hide() def setSrcsLabel( self, newLabel ): self.UI_srcButton.setLabel( newLabel ) def setTgtsLabel( self, newLabel ): self.UI_tgtButton.setLabel( newLabel ) def getUnmappedSrcs( self ): return list( set( self.srcs ).difference( self.getMapping().srcs ) ) def getUnmappedTgts( self ): return list( set( self.tgts ).difference( self.getMapping().tgts ) ) def getMapping( self ): mapping = names.Mapping.FromDict( self._srcToTgtDict ) return mapping def setMapping( self, mapping ): if isinstance( mapping, dict ): self._srcToTgtDict = mapping elif isinstance( mapping, names.Mapping ): self._srcToTgtDict = mapping.asDict() else: raise TypeError, "unsupported mapping type %s" % type( mapping ) self.refresh() def getSelectedSrc( self ): ''' returns the name of the src item selected. None if nothing is selected ''' try: return self.UI_srcs.getSelectedItems()[ 0 ] except IndexError: return None def getSelectedTgts( self ): return self.UI_tgts.getSelectedItems() def mapSrcItem( self, src ): self._srcToTgtDict[ src ] = names.matchNames( [ src ], self.tgts, self.STRIP_NAMESPACES, self.PARITY_MATCH, self.UNIQUE_MATCHING, self.MATCH_OPPOSITE_PARITY, self.THRESHOLD ) def mapAllSrcItems( self ): for src in self.srcs: self.mapSrcItem( src ) def addSrcItems( self, items ): if items: self.UI_srcs.appendItems( list( sorted( items ) ) ) for i in items: self.mapSrcItem( i ) def replaceSrcItems( self, items ): self.UI_tgts.clear() self.addSrcItems( items ) def addTgtItems( self, items ): if items: self.UI_tgts.appendItems( items ) performMapping = bool( self.UI_tgts.getItems() ) if performMapping: self.mapAllSrcItems() def clear( self ): self._srcToTgtDict = {} self.UI_srcs.clear() self.UI_tgts.clear() def clearSrcs( self ): self._srcToTgtDict = {} self.UI_srcs.clear() def clearTgts( self ): self._srcToTgtDict = {} self.UI_tgts.clear() def refresh( self ): theSrcs = [] theTgts = [] for src in sorted( self._srcToTgtDict.keys() ): theSrcs.append( src ) theTgts += self._srcToTgtDict[ src ] theSrcs = removeDupes( theSrcs ) theTgts = removeDupes( theTgts ) self.UI_srcs.setItems( theSrcs ) self.UI_tgts.setItems( theTgts ) def saveMappingToFile( self, filepath ): filepath = Path( filepath ).setExtension( EXT ) filedata = api.writeExportDict( TOOL_NAME, TOOL_VER ), self.getMapping() filepath.pickle( filedata ) def saveMappingPreset( self, presetName ): filepath = Preset( LOCAL, TOOL_NAME, presetName, EXT ) self.saveMappingToFile( filepath ) def loadMappingFile( self, filepath ): d, mapping = Path( filepath ).unpickle() mapping = names.Mapping.FromDict( mapping ) if self.ALLOW_MULTI_SELECTION: self._srcToTgtDict = mapping.asDict() else: self._srcToTgtDict = mapping.asFlatDict() self.refresh() def loadMappingPreset( self, presetName ): filepath = findPreset( presetName, TOOL_NAME, EXT ) self.loadMappingFile( filepath ) ### MENU BUILDERS ### def build_srcMenu( self, *a ): cmd.setParent( a[ 0 ], menu=True ) cmd.menu( a[ 0 ], e=True, dai=True ) cmd.menuItem( l='Add Selected Objects', c=self.on_addSrc ) cmd.menuItem( l='Replace With Selected Objects', c=self.on_replaceSrc ) cmd.menuItem( d=True ) cmd.menuItem( l='Remove Highlighted Item', c=self.on_removeSrcItem ) cmd.menuItem( d=True ) cmd.menuItem( l='Select All Objects', c=self.on_selectAllSrc ) cmd.menuItem( d=True ) cmd.menuItem( l='Save Mapping...', c=self.on_saveMapping ) cmd.menuItem( l='Load Mapping...', sm=True ) pm = PresetManager( TOOL_NAME, EXT ) presets = pm.listAllPresets( True ) for loc in LOCAL, GLOBAL: for f in presets[ loc ]: f = Path( f ) cmd.menuItem( l=f.name(), c=Callback( self.loadMappingFile, f ) ) cmd.menuItem( d=True ) cmd.menuItem( l='Manage Mappings...', c=lambda *x: presetsUI.load( TOOL_NAME, LOCAL, EXT ) ) cmd.setParent( '..', menu=True ) cmd.menuItem( d=True ) cmd.menuItem( l='Swap Mapping', c=self.on_swap ) def build_tgtMenu( self, *a ): cmd.setParent( a[ 0 ], menu=True ) cmd.menu( a[ 0 ], e=True, dai=True ) cmd.menuItem( l='Add Selected Objects', c=self.on_addTgt ) cmd.menuItem( l='Replace With Selected Objects', c=self.on_replaceTgt ) cmd.menuItem( d=True ) cmd.menuItem( l='Select All Objects', c=self.on_selectAllTgt ) cmd.menuItem( l='Select Highlighted Objects', c=self.on_selectTgt ) cmd.menuItem( d=True ) cmd.menuItem( l='Remove Highlighted Items', c=self.on_removeTgtItem ) cmd.menuItem( d=True) cmd.menuItem( l='Swap Mapping', c=self.on_swap ) ### EVENT CALLBACKS ### def on_selectAllSrc( self, *a ): cmd.select( cl=True ) for s in self.UI_srcs.getItems(): s = str( s ) if cmd.objExists( s ): cmd.select( s, add=True ) def on_selectAllTgt( self, *a ): cmd.select( cl=True ) for t in self.UI_tgts.getItems(): t = str( t ) if cmd.objExists( t ): cmd.select( t, add=True ) def on_selectItemSrc( self, *a ): self.UI_tgts.clearSelection() src = self.getSelectedSrc() if src: try: tgts = self._srcToTgtDict[ src ] except KeyError: return for t in tgts: if t: self.UI_tgts.selectByValue( t ) def on_addSrc( self, *a ): self.addSrcItems( cmd.ls( sl=True ) ) def on_replaceSrc( self, *a ): self._srcToTgtDict = {} self.UI_srcs.clear() self.on_addSrc() def on_removeSrcItem( self, *a ): sel = self.getSelectedSrc() try: self._srcToTgtDict.pop( sel ) except KeyError: pass try: self.UI_srcs.removeByValue( sel ) except IndexError: pass def on_selectSrc( self, *a ): src = self.getSelectedSrc() if src: #if the object doesnt' exist in teh scene - try to find it src = findItem( src ) if src is not None: cmd.select( src ) def on_src_up( self, *a ): self.UI_srcs.moveSelectedItemsUp() def on_src_dn( self, *a ): self.UI_srcs.moveSelectedItemsDown() def on_selectItemTgt( self, *a ): src = self.getSelectedSrc() if src: self._srcToTgtDict[ src ] = self.UI_tgts.getSelectedItems() else: self.UI_tgts.clearSelection() def on_delete( self, *a ): src = self.getSelectedSrc() if src: del( self._srcToTgtDict[ src ] ) self.on_selectItemSrc() def on_addTgt( self, *a ): self.addTgtItems( cmd.ls( sl=True ) ) def on_replaceTgt( self, *a ): self._srcToTgtDict = {} self.UI_tgts.clear() self.on_addTgt() self.mapAllSrcItems() def on_removeTgtItem( self, *a ): selTgts = self.getSelectedTgts() for aSrc, tgts in self._srcToTgtDict.iteritems(): newTgts = [ tgt for tgt in tgts if tgt not in selTgts ] self._srcToTgtDict[ aSrc ] = newTgts idxs = self.UI_tgts.getSelectedIdxs() for idx in reversed( sorted( idxs ) ): self.UI_tgts.removeByIdx( idx ) def on_selectTgt( self, *a ): tgts = self.getSelectedTgts() if tgts: existingTgts = [] for t in tgts: t = findItem( t ) if t is not None: existingTgts.append( t ) if existingTgts: cmd.select( existingTgts ) def on_tgt_up( self, *a ): self.UI_tgts.moveSelectedItemsUp() def on_tgt_dn( self, *a ): self.UI_tgts.moveSelectedItemsDown() def on_swap( self, *a ): curMapping = names.Mapping.FromDict( self._srcToTgtDict ) curMapping.swap() if self.ALLOW_MULTI_SELECTION: self._srcToTgtDict = curMapping.asDict() else: self._srcToTgtDict = curMapping.asFlatDict() self.refresh() def on_saveMapping( self, *a ): ret = cmd.promptDialog( m='Enter a name for the mapping', t='Enter Name', b=('Ok', 'Cancel'), db='Ok' ) if ret == 'Ok': self.saveMappingPreset( cmd.promptDialog( q=True, tx=True ) ) def on_loadMapping( self, *a ): previous = getPresetDirs( LOCAL, TOOL_NAME )[ 0 ] if self._previousMappingFile is not None: previous = self._previousDir filename = cmd.fileDialog( directoryMask=( "%s/*.%s" % (previous, EXT) ) ) filepath = Path( filename ) self._previousMappingFile = filepath.up() self.loadMappingFile( filepath ) class MappingEditor(BaseMelWindow): ''' ''' WINDOW_NAME = 'mappingEditorUI' WINDOW_TITLE = 'Mapping Editor' DEFAULT_SIZE = 400, 600 def __new__( cls, *a, **kw ): return BaseMelWindow.__new__( cls ) def __init__( self, srcItems=None, tgtItems=None ): BaseMelWindow.__init__( self ) self.editor = MappingForm( self, srcItems, tgtItems ) self.show() def getMapping( self ): return self.editor.getMapping() def load(): global ui ui = MappingEditor() #end
Python
from __future__ import with_statement from maya import mel from maya.cmds import * from baseMelUI import * from vectors import Vector, Colour from common import printErrorStr, printWarningStr from mayaDecorators import d_unifyUndo from apiExtensions import asMObject, sortByHierarchy from triggered import resolveCmdStr, Trigger import re import names import colours import presetsUI eval = __builtins__[ 'eval' ] #otherwise this gets clobbered by the eval in maya.cmds TOOL_NAME = 'zooPicker' TOOL_EXTENSION = filesystem.presets.DEFAULT_XTN TOOL_CMD_EXTENSION = 'cmdPreset' VERSION = 0 MODIFIERS = SHIFT, CAPS, CTRL, ALT = 2**0, 2**1, 2**2, 2**3 ADDITIVE = CTRL | SHIFT def isValidMayaNodeName( theStr ): validChars = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' for char in theStr: if char not in validChars: return False return True def getLabelWidth( theString ): ''' some guestimate code to determine the width of a given string when displayed as text on a ButtonUI instance ''' wideLetters = 'abcdeghkmnopqrsuvwxyz_ ' width = 0 for char in theString: if char in wideLetters: width += 7 else: width += 3 return width def removeRefEdits( objs, cmd=None ): ''' removes reference edits from a list of objects. if the $cmd arg is an empty string then ALL commands are removed. if $cmd is a valid reference edit command, only those commands are removed from the list of objects supplied ''' refNodeLoadStateDict = {} for obj in objs: if referenceQuery( obj, inr=True ): refNode = referenceQuery( obj, rfn=True ) loadState = bool( referenceQuery( refNode, n=True ) ) refNodeLoadStateDict[ refNode ] = loadState #now unload all references so we can remove edits for node in refNodeLoadStateDict: file( unloadReference=node ) #remove failed edits for obj in objs: referenceEdit( obj, failedEdits=True, successfulEdits=False, removeEdits=True ) #remove specified edits for the objects for obj in objs: if cmd is None: referenceEdit( obj, failedEdits=True, successfulEdits=True, removeEdits=True ) else: referenceEdit( obj, failedEdits=True, successfulEdits=True, editCommand=cmd, removeEdits=True ) #now set the refs to their initial load state for node, loadState in refNodeLoadStateDict.iteritems(): if loadState: file( loadReference=node ) select( objs ) def getTopPickerSet(): existing = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == TOOL_NAME ] if existing: return existing[ 0 ] else: pickerNode = createNode( 'objectSet', n='picker' ) sets( pickerNode, e=True, text=TOOL_NAME ) return pickerNode class Button(object): ''' A Button instance is a "container" for a button within a picker. To instantiate a button you need to pass the set node that contains the button data. You can create a new set node using Button.Create. A button, when pressed, by default selects the contents of the set based on the keyboard modifiers pressed. But a button can also define its own press command. Button press commands are stored on the cmdStr string attribute on the set node and can be most easily edited using the editor tab created by the PickerLayout UI. ''' SELECTION_STATES = NONE, PARTIAL, COMPLETE = range( 3 ) CMD_MODES = MODE_SELECTION_FIRST, MODE_CMD_FIRST, MODE_CMD_ONLY = range( 3 ) CMD_MODES_NAMES = 'selection first', 'cmd first', 'cmd only' MIN_SIZE, MAX_SIZE = 5, 100 DEFAULT_SIZE = 14, 14 DEFAULT_COLOUR = tuple( Colour( (0.25, 0.25, 0.3) ).asRGB() ) AUTO_COLOUR = None COLOUR_PARTIAL, COLOUR_COMPLETE = (1, 0.6, 0.5), Colour( 'white' ).asRGB() DEFAULT_ATTRS = ( { 'ln': 'posSize', 'dt': 'string' }, #stuff pos and size into a single str attr - so lazy... { 'ln': 'colour', 'dt': 'string' }, { 'ln': 'label', 'dt': 'string' }, { 'ln': 'cmdStr', 'dt': 'string' }, { 'ln': 'cmdIsPython', 'at': 'bool', 'dv': False }, { 'ln': 'cmdMode', 'at': 'enum', 'enumName': ':'.join( CMD_MODES_NAMES ), 'dv': MODE_SELECTION_FIRST } ) @classmethod def Create( cls, character, pos, size=DEFAULT_SIZE, colour=AUTO_COLOUR, label=None, objs=(), cmdStr=None, cmdIsPython=False ): node = sets( em=True, text='zooPickerButton' ) sets( node, e=True, add=character.getNode() ) cls.ValidateNode( node ) self = cls( node ) self.setPosSize( pos, size ) self.setLabel( label ) self.setObjs( objs ) self.setCmdStr( cmdStr ) self.setCmdIsPython( cmdIsPython ) #if the colour is set to "AUTO_COLOUR" then try to determine the button colour based off the object's colour if colour is cls.AUTO_COLOUR: self.setColour( cls.DEFAULT_COLOUR ) self.setAutoColour() else: self.setColour( colour ) return self @classmethod def ValidateNode( cls, node ): for addAttrKw in cls.DEFAULT_ATTRS: if not objExists( '%s.%s' % (node, addAttrKw[ 'ln' ]) ): addAttr( node, **addAttrKw ) def __init__( self, node ): self.__node = asMObject( node ) def __repr__( self ): return "%s( '%s' )" % (type( self ).__name__, self.getNode()) __str__ = __repr__ def __eq__( self, other ): ''' two buttons are equal on if all their attributes are the same ''' return self.getCharacter() == other.getCharacter() and \ self.getPos() == other.getPos() and \ self.getSize() == other.getSize() and \ self.getColour() == other.getColour() and \ self.getLabel() == other.getLabel() and \ self.getObjs() == other.getObjs() and \ self.getCmdStr() == other.getCmdStr() and \ self.getCmdIsPython() == other.getCmdIsPython() def __ne__( self, other ): return not self.__eq__( other ) def __hash__( self ): return hash( self.getNode() ) def getNode( self ): return unicode( self.__node ) def getCharacter( self ): cons = listConnections( self.getNode(), type='objectSet', s=False ) if cons: return Character( cons[0] ) def getPosSize( self ): valStr = getAttr( '%s.posSize' % self.getNode() ) if valStr is None: return Vector( (0,0,0) ), self.DEFAULT_SIZE posStr, sizeStr = valStr.split( ';' ) pos = Vector( [ int( p ) for p in posStr.split( ',' ) ] ) size = Vector( [ int( p ) for p in sizeStr.split( ',' ) ] ) return pos, size def getPos( self ): return self.getPosSize()[0] def getSize( self ): return self.getPosSize()[1] def getColour( self ): rgbStr = getAttr( '%s.colour' % self.getNode() ) if rgbStr is None: return self.DEFAULT_COLOUR rgb = rgbStr.split( ',' ) rgb = map( float, rgb ) return Colour( rgb ) def getLabel( self ): return getAttr( '%s.label' % self.getNode() ) def getNiceLabel( self ): labelStr = self.getLabel() #if there is no label AND the button has objects, communicate this to the user if not labelStr: if len( self.getObjs() ) > 1: return '+' return labelStr def getObjs( self ): return sets( self.getNode(), q=True ) or [] def getCmdStr( self ): return getAttr( '%s.cmdStr' % self.getNode() ) def getCmdIsPython( self ): return getAttr( '%s.cmdIsPython' % self.getNode() ) def getCmdMode( self ): try: return getAttr( '%s.cmdMode' % self.getNode() ) except TypeError: self.ValidateNode( self.getNode() ) return getAttr( '%s.cmdMode' % self.getNode() ) def getResolvedCmdStr( self ): cmdStr = self.getCmdStr() if self.getCmdIsPython(): return cmdStr % locals() else: return resolveCmdStr( cmdStr, self.getNode(), self.getObjs() ) def setPosSize( self, pos, size ): #make sure the pos/size values are ints... pos = map( int, map( round, pos ) ) size = map( int, map( round, size ) ) posStr = ','.join( map( str, pos ) ) sizeStr = ','.join( map( str, size ) ) valStr = setAttr( '%s.posSize' % self.getNode(), '%s;%s' % (posStr, sizeStr), type='string' ) def setPos( self, val ): if not isinstance( val, Vector ): val = Vector( val ) p, s = self.getPosSize() self.setPosSize( val, s ) def setSize( self, val ): if not isinstance( val, Vector ): val = Vector( val ) p, s = self.getPosSize() self.setPosSize( p, val ) def setColour( self, val ): if val is None: val = self.DEFAULT_COLOUR valStr = ','.join( map( str, val ) ) setAttr( '%s.colour' % self.getNode(), valStr, type='string' ) def setLabel( self, val ): if val is None: val = '' setAttr( '%s.label' % self.getNode(), val, type='string' ) #rename the node to reflect the label try: if val and isValidMayaNodeName( val ): rename( self.getNode(), val ) else: objs = self.getObjs() if objs: rename( self.getNode(), '%s_picker' % objs[0] ) else: rename( self.getNode(), 'picker' ) #this generally happens if the node is referenced... its no big deal if the rename fails - renaming just happens to make the sets slightly more comprehendible when outliner surfing except RuntimeError: pass def setObjs( self, val ): if isinstance( val, basestring ): val = [ val ] if not val: return sets( e=True, clear=self.getNode() ) sets( val, e=True, add=self.getNode() ) def setCmdStr( self, val ): if val is None: val = '' setAttr( '%s.cmdStr' % self.getNode(), val, type='string' ) def setCmdIsPython( self, val ): setAttr( '%s.cmdIsPython' % self.getNode(), val ) def setCmdMode( self, val ): setAttr( '%s.cmdMode' % self.getNode(), val ) def setAutoColour( self, defaultColour=None ): objs = self.getObjs() for obj in objs: colour = colours.getObjColour( obj ) if colour: self.setColour( colour ) return if defaultColour is not None: self.setColour( defaultColour ) def select( self, forceModifiers=None, executeCmd=True ): ''' this is what happens when a user "clicks" or "selects" this button. It handles executing the button command in the desired order and handling object selection ''' cmdMode = self.getCmdMode() #if we're executing the command only, execute it and bail if cmdMode == self.MODE_CMD_ONLY: if executeCmd: self.executeCmd() return #if we're executing the command first - do it if cmdMode == self.MODE_CMD_FIRST: if executeCmd: self.executeCmd() if forceModifiers is None: mods = getModifiers() else: mods = forceModifiers objs = self.getObjs() if objs: if mods & SHIFT and mods & CTRL: select( objs, add=True ) elif mods & SHIFT: select( objs, toggle=True ) elif mods & CTRL: select( objs, deselect=True ) else: select( objs ) if cmdMode == self.MODE_SELECTION_FIRST: if executeCmd: self.executeCmd() def selectedState( self ): ''' returns whether this button is partially or fully selected - return values are one of the values in self.SELECTION_STATES ''' objs = self.getObjs() sel = ls( objs, sl=True ) if not sel: return self.NONE elif len( objs ) == len( sel ): return self.COMPLETE return self.PARTIAL def moveBy( self, offset ): pos = self.getPos() self.setPos( pos + offset ) def exists( self ): return objExists( self.getNode() ) def isEmpty( self ): return not bool( self.getObjs() ) def executeCmd( self ): ''' executes the command string for this button ''' cmdStr = self.getResolvedCmdStr() if cmdStr: try: if self.getCmdIsPython(): return eval( cmdStr ) else: return maya.mel.eval( "{%s;}" % cmdStr ) except: printErrorStr( 'Executing command "%s" on button "%s"' % (cmdStr, self.getNode()) ) def duplicate( self ): dupe = self.Create( self.getCharacter(), self.getPos(), self.getSize(), self.getColour(), self.getLabel(), self.getObjs(), self.getCmdStr(), self.getCmdIsPython() ) return dupe def mirrorObjs( self ): ''' replaces the objects in this button with their name based opposites - ie if this button contained the object ctrl_L, this method would replace the objects with ctrl_R. It uses names.swapParity ''' oppositeObjs = [] for obj in self.getObjs(): opposite = names.swapParity( obj ) if opposite: oppositeObjs.append( opposite ) self.setObjs( oppositeObjs ) def delete( self ): delete( self.getNode() ) class Character(object): ''' A Character is made up of many Button instances to select the controls or groups of controls that comprise a puppet rig. A Character is also stored as a set node in the scene. New Character nodes can be created using Character.Create, or existing ones instantiated by passing the set node to Character. ''' DEFAULT_BG_IMAGE = 'pickerGrid.bmp' @classmethod def IterAll( cls ): for node in ls( type='objectSet' ): if sets( node, q=True, text=True ) == 'zooPickerCharacter': yield cls( node ) @classmethod def Create( cls, name ): ''' creates a new character for the picker tool ''' node = sets( em=True, text='zooPickerCharacter' ) node = rename( node, name ) sets( node, e=True, add=getTopPickerSet() ) addAttr( node, ln='version', at='long' ) addAttr( node, ln='name', dt='string' ) addAttr( node, ln='bgImage', dt='string' ) addAttr( node, ln='bgColour', dt='string' ) addAttr( node, ln='filepath', dt='string' ) setAttr( '%s.version' % node, VERSION ) setAttr( '%s.name' % node, name, type='string' ) setAttr( '%s.bgImage' % node, cls.DEFAULT_BG_IMAGE, type='string' ) setAttr( '%s.bgColour' % node, '0,0,0', type='string' ) #lock the node - this stops maya from auto-deleting it if all buttons are removed lockNode( node ) self = cls( node ) allButton = self.createButton( (5, 5), (25, 14), (1, 0.65, 0.25), 'all', [], '%(self)s.getCharacter().selectAllButtonObjs()', True ) return self def __init__( self, node ): self.__node = asMObject( node ) def __repr__( self ): return "%s( '%s' )" % (type( self ).__name__, self.getNode()) __str__ = __repr__ def __eq__( self, other ): return self.getNode() == other.getNode() def __ne__( self, other ): return not self.__eq__( other ) def getNode( self ): return unicode( self.__node ) def getButtons( self ): buttonNodes = sets( self.getNode(), q=True ) or [] return [ Button( node ) for node in buttonNodes ] def getName( self ): return getAttr( '%s.name' % self.getNode() ) def getBgImage( self ): return getAttr( '%s.bgImage' % self.getNode() ) def getBgColour( self ): colStr = getAttr( '%s.bgColour' % self.getNode() ) return Colour( [ float( c ) for c in colStr.split( ',' ) ] ).asRGB() def getFilepath( self ): return getAttr( '%s.filepath' % self.getNode() ) def setName( self, val ): setAttr( '%s.name' % self.getNode(), str( val ), type='string' ) lockNode( self.getNode(), lock=False ) rename( self.getNode(), val ) lockNode( self.getNode(), lock=True ) def setBgImage( self, val ): setAttr( '%s.bgImage' % self.getNode(), val, type='string' ) def setBgColour( self, val ): valStr = ','.join( map( str, val ) ) setAttr( '%s.bgColour' % self.getNode(), valStr, type='string' ) def setFilepath( self, filepath ): setAttr( '%s.filepath' % self.getNode(), filepath, type='string' ) def createButton( self, pos, size, colour=None, label=None, objs=(), cmdStr=None, cmdIsPython=False ): ''' appends a new button to the character - a new Button instance is returned ''' return Button.Create( self, pos, size, colour, label, objs, cmdStr, cmdIsPython ) def removeButton( self, button, delete=True ): ''' given a Button instance, will remove it from the character ''' for aButton in self.getButtons(): if button == aButton: sets( button.getNode(), e=True, remove=self.getNode() ) if delete: button.delete() return def breakoutButton( self, button, direction, padding=5, colour=None ): ''' doing a "breakout" on a button will basically take each object in the button and create a new button for it in the given direction ''' buttonPos, buttonSize = button.getPosSize() colour = button.getColour() posIncrement = Vector( direction ).normalize() posIncrement[0] *= buttonSize[0] + padding posIncrement[1] *= buttonSize[1] + padding newButtons = [] objs = button.getObjs() #figure out which axis to use to sort the objects - basically figure out which axis has the highest delta between smallest and largest posObjs = [ (Vector( xform( obj, q=True, ws=True, rp=True ) ), obj) for obj in objs ] bestDelta, bestSorting = 0, [] for n in range( 3 ): sortedByN = [ (objPos[n], obj) for objPos, obj in posObjs ] sortedByN.sort() delta = abs( sortedByN[-1][0] - sortedByN[0][0] ) if delta > bestDelta: bestDelta, bestSorting = delta, sortedByN #now we've figured out which axis is the most appropriate axis and have the best sorting, build the buttons objs = [ obj for objPosN, obj in bestSorting ] #if the direction is positive (which is down the screen in the picker), then we want to breakout the buttons in ascending hierarchical fashion ascending = True if direction[0] < 0 or direction[1] < 0: ascending = False if ascending: objs.reverse() for obj in objs: buttonPos += posIncrement button = self.createButton( buttonPos, buttonSize, objs=[ obj ] ) button.setAutoColour( colour ) newButtons.append( button ) return newButtons def selectAllButtonObjs( self ): for button in self.getButtons(): button.select( ADDITIVE, False ) def isEmpty( self ): if objExists( self.getNode() ): return not self.getButtons() return False def delete( self ): for button in self.getButtons(): button.delete() node = self.getNode() lockNode( node, lock=False ) delete( node ) def saveToPreset( self, filepath ): ''' stores this picker character out to disk ''' filepath = filesystem.Path( filepath ) if filepath.exists(): filepath.editoradd() with open( filepath, 'w' ) as fOpen: infoDict = {} infoDict[ 'version' ] = VERSION infoDict[ 'name' ] = self.getName() infoDict[ 'bgImage' ] = self.getBgImage() or '' infoDict[ 'bgColour' ] = tuple( self.getBgColour() ) fOpen.write( str( infoDict ) ) fOpen.write( '\n' ) #the preset just needs to contain a list of buttons for button in self.getButtons(): buttonDict = {} pos, size = button.getPosSize() buttonDict[ 'pos' ] = tuple( pos ) buttonDict[ 'size' ] = tuple( size ) buttonDict[ 'colour' ] = tuple( button.getColour() ) buttonDict[ 'label' ] = button.getLabel() buttonDict[ 'objs' ] = button.getObjs() buttonDict[ 'cmdStr' ] = button.getCmdStr() buttonDict[ 'cmdIsPython' ] = button.getCmdIsPython() buttonDict[ 'cmdMode' ] = button.getCmdMode() fOpen.write( str( buttonDict ) ) fOpen.write( '\n' ) #store the filepath on the character node self.setFilepath( filepath.unresolved() ) @classmethod def LoadFromPreset( cls, filepath, namespaceHint=None ): ''' ''' filepath = filesystem.Path( filepath ) #make sure the namespaceHint - if we have one - doesn't end in a semi-colon if namespaceHint: if namespaceHint.endswith( ':' ): namespaceHint = namespaceHint[ :-1 ] buttonDicts = [] with open( filepath ) as fOpen: lineIter = iter( fOpen ) try: infoLine = lineIter.next() infoDict = eval( infoLine.strip() ) while True: buttonLine = lineIter.next() buttonDict = eval( buttonLine.strip() ) buttonDicts.append( buttonDict ) except StopIteration: pass version = infoDict.pop( 'version', 0 ) newCharacter = cls.Create( infoDict.pop( 'name', 'A Picker' ) ) newCharacter.setBgImage( infoDict.pop( 'bgImage', cls.DEFAULT_BG_IMAGE ) ) newCharacter.setBgColour( infoDict.pop( 'bgColour', (0, 0, 0) ) ) #if there is still data in the infoDict print a warning - perhaps new data was written to the file that was handled when loading the preset? if infoDict: printWarningStr( 'Not all info was loaded from %s on to the character: %s still remains un-handled' % (filepath, infoDict) ) for buttonDict in buttonDicts: newButton = Button.Create( newCharacter, buttonDict.pop( 'pos' ), buttonDict.pop( 'size' ), buttonDict.pop( 'colour', Button.DEFAULT_COLOUR ), buttonDict.pop( 'label', '' ) ) newButton.setCmdStr( buttonDict.pop( 'cmdStr', '' ) ) newButton.setCmdIsPython( buttonDict.pop( 'cmdIsPython', False ) ) newButton.setCmdMode( buttonDict.pop( 'cmdMode', Button.MODE_SELECTION_FIRST ) ) #now handle objects - this is about the only tricky part - we want to try to match the objects stored to file to objects in this scene as best we can objs = buttonDict.pop( 'objs', [] ) realObjs = [] for obj in objs: #does the exact object exist? if objExists( obj ): realObjs.append( obj ) continue #how about inserting a namespace in-between any path tokens? pathToks = obj.split( '|' ) if namespaceHint: objNs = '|'.join( '%s:%s' % (namespaceHint, tok) for tok in pathToks ) if objExists( objNs ): realObjs.append( objNs ) continue #how about ANY matches on the leaf path token? anyMatches = ls( pathToks[-1] ) if anyMatches: realObjs.append( anyMatches[0] ) if not namespaceHint: namespaceHint = ':'.join( anyMatches[0].split( ':' )[ :-1 ] ) newButton.setObjs( realObjs ) #print a warning if there is still data in the buttonDict - perhaps new data was written to the file that was handled when loading the preset? if buttonDict: printWarningStr( 'Not all info was loaded from %s on to the character: %s still remains un-handled' % (filepath, infoDict) ) return newCharacter def _drag( *a ): ''' passes the local coords the widget is being dragged from ''' return [a[-3], a[-2]] def _drop( src, tgt, msgs, x, y, mods ): ''' this is the drop handler used by everything in this module ''' src = BaseMelUI.FromStr( src ) tgt = BaseMelUI.FromStr( tgt ) #if dragging an existing button around on the form, interpret it as a move if isinstance( src, ButtonUI ) and isinstance( tgt, DragDroppableFormLayout ): srcX, srcY = map( int, msgs ) x -= srcX y -= srcY #figure out the delta moved curX, curY = src.button.getPos() delta = x - curX, y - curY charUI = src.getParentOfType( CharacterUI ) buttonsToMove = charUI.getSelectedButtonUIs() #if the button dragged isn't in the selection - add it to the selection if src not in buttonsToMove: buttonsToMove.insert( 0, src ) charUI.setSelectedButtonUIs( buttonsToMove ) #now move all the buttons by the given delta for buttonUI in buttonsToMove: buttonUI.button.moveBy( delta ) buttonUI.updateGeometry( False ) #finally, refresh the BG image charUI.refreshImage() #if dragging from the form to the form, or dragging from the creation button, interpret it as a create new button elif isinstance( src, CreatePickerButton ) and isinstance( tgt, DragDroppableFormLayout ) or \ isinstance( src, DragDroppableFormLayout ) and isinstance( tgt, DragDroppableFormLayout ): characterUI = tgt.getParentOfType( CharacterUI ) if characterUI: newButton = characterUI.createButton( (x, y) ) class ButtonUI(MelIconButton): def __init__( self, parent, button ): MelIconButton.__init__( self, parent ) self.setColour( button.getColour() ) assert isinstance( button, Button ) self.button = button self.state = Button.NONE self( e=True, dgc=_drag, dpc=_drop, style='textOnly', c=self.on_press ) self.POP_menu = MelPopupMenu( self, pmc=self.buildMenu ) self._hashGeo = 0 self._hashApp = 0 self.update() def buildMenu( self, *a ): menu = self.POP_menu isEditorOpen = EditorWindow.Exists() menu.clear() editButtonKwargs = { 'l': 'edit this button', 'c': self.on_edit, 'ann': 'opens the button editor which allows you to edit properties of this button - colour, size, position etc...' } if isEditorOpen: MelMenuItem( menu, l='ADD selection to button', c=self.on_add, ann='adds the selected scene objects to this button' ) MelMenuItem( menu, l='REPLACE button with selection', c=self.on_replace, ann="replaces this button's objects with the selected scene objects" ) MelMenuItem( menu, l='REMOVE selection from button', c=self.on_remove, ann='removes the selected scene objects from this button' ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='mirror duplicate button', c=self.on_mirrorDupe ) MelMenuItem( menu, l='move to mirror position', c=self.on_mirrorThis ) MelMenuItemDiv( menu ) MelMenuItem( menu, **editButtonKwargs ) MelMenuItem( menu, l='select highlighted buttons', c=self.on_selectHighlighted, ann='selects all buttons that are highlighted (ie are %s)' % Colour.ColourToName( Button.COLOUR_COMPLETE ) ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='breakout UP', c=self.on_breakoutUp, ann='for each object in this button, creates a button above this one' ) MelMenuItem( menu, l='breakout DOWN', c=self.on_breakoutDown, ann='for each object in this button, creates a button below this one' ) MelMenuItem( menu, l='<-- breakout LEFT', c=self.on_breakoutLeft, ann='for each object in this button, creates a button to the left of this one' ) MelMenuItem( menu, l='breakout RIGHT -->', c=self.on_breakoutRight, ann='for each object in this button, creates a button to the right of this one' ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='DELETE this button', c=self.on_delete, ann='deletes the button being right clicked on' ) MelMenuItem( menu, l='DELETE selected buttons', c=self.on_deleteSelected, ann='deletes all selected buttons. NOTE: this is not necessarily the highlighted buttons - look in the button editor for the list of buttons that are selected' ) else: class Callback(object): def __init__( self, func, *a ): self.f = func self.a = a def __call__( self, *a ): return self.f( *self.a ) buttonObjs = self.button.getObjs() if len( buttonObjs ) == 1: objTrigger = Trigger( buttonObjs[0] ) for slot, menuName, menuCmd in objTrigger.iterMenus( True ): MelMenuItem( menu, l=menuName, c=Callback( mel.eval, menuCmd ) ) MelMenuItemDiv( menu ) MelMenuItem( menu, **editButtonKwargs ) def updateHighlightState( self ): selectedState = self.button.selectedState() if self.state == selectedState: return if selectedState == Button.PARTIAL: self.setColour( Button.COLOUR_PARTIAL ) elif selectedState == Button.COMPLETE: self.setColour( Button.COLOUR_COMPLETE ) else: self.setColour( self.button.getColour() ) self.state = selectedState def isButtonHighlighted( self ): return self.button.selectedState() def update( self ): self.updateGeometry() self.updateAppearance() self.updateHighlightState() def updateGeometry( self, refreshUI=True ): posSize = pos, size = self.button.getPosSize() x, y = pos #check against the stored hash - early out if they match if hash( posSize ) == self._hashGeo: return #clamp the pos to the size of the parent parent = self.getParent() maxX, maxY = parent.getSize() #x = min( max( x, 0 ), maxX ) #NOTE: this is commented out because it seems maya reports the size of the parent to be 0, 0 until there are children... #y = min( max( y, 0 ), maxY ) parent( e=True, ap=((self, 'top', y, 0), (self, 'left', x, 0)) ) self.setSize( size ) #store the hash - geo hashes are stored so that we can do lazy refreshes self._hashGeo = hash( posSize ) if refreshUI: self.sendEvent( 'refreshImage' ) def updateAppearance( self ): niceLabel = self.button.getNiceLabel() if hash( niceLabel ) == self._hashApp: return self.setLabel( niceLabel ) self._hashApp = hash( niceLabel ) def mirrorDuplicate( self ): dupe = self.button.duplicate() dupe.mirrorObjs() dupe.setAutoColour( self.button.getColour() ) self.mirrorPosition( dupe ) #if the button has a label - see if it has a parity and if so, reverse it label = self.button.getLabel() if label: newLabel = names.swapParity( label ) dupe.setLabel( newLabel ) self.sendEvent( 'appendButton', dupe, True ) def mirrorPosition( self, button=None ): if button is None: button = self.button pickerLayout = self.getParentOfType( PickerLayout ) pickerWidth = pickerLayout( q=True, w=True ) pos, size = button.getPosSize() buttonCenterX = pos.x + (size.x / 2) newPosX = pickerWidth - buttonCenterX - size.x newPosX = min( max( newPosX, 0 ), pickerWidth ) button.setPos( (newPosX, pos.y) ) ### EVENT HANDLERS ### def on_press( self, *a ): self.button.select() self.sendEvent( 'buttonSelected', self ) def on_add( self, *a ): objs = self.button.getObjs() objs += ls( sl=True ) or [] self.button.setObjs( objs ) def on_replace( self, *a ): self.button.setObjs( ls( sl=True ) or [] ) def on_remove( self, *a ): objs = self.button.getObjs() objs += ls( sl=True ) or [] self.button.setObjs( objs ) def on_mirrorDupe( self, *a ): self.mirrorDuplicate() def on_mirrorThis( self, *a ): self.mirrorPosition() self.updateGeometry() def on_edit( self, *a ): self.sendEvent( 'buttonSelected', self ) self.sendEvent( 'on_showEditor' ) def on_selectHighlighted( self, *a ): self.sendEvent( 'selectHighlightedButtons' ) def on_breakoutUp( self, *a ): self.sendEvent( 'breakoutButton', self, (0, -1) ) def on_breakoutDown( self, *a ): self.sendEvent( 'breakoutButton', self, (0, 1) ) def on_breakoutLeft( self, *a ): self.sendEvent( 'breakoutButton', self, (-1, 0) ) def on_breakoutRight( self, *a ): self.sendEvent( 'breakoutButton', self, (1, 0) ) def on_delete( self, *a ): self.delete() self.button.delete() self.sendEvent( 'refreshImage' ) self.sendEvent( 'updateButtonList' ) def on_deleteSelected( self, *a ): self.sendEvent( 'deleteSelectedButtons' ) class MelPicture(BaseMelWidget): WIDGET_CMD = picture def getImage( self ): return self( q=True, i=True ) def setImage( self, image ): self( e=True, i=image ) class DragDroppableFormLayout(MelFormLayout): def __init__( self, parent, **kw ): MelFormLayout.__init__( self, parent, **kw ) self( e=True, dgc=_drag, dpc=_drop ) class CharacterUI(MelHLayout): def __init__( self, parent, character ): self.character = character self._selectedButtonUIs = [] self.UI_picker = MelPicture( self, en=False, dgc=_drag, dpc=_drop ) self.UI_picker.setImage( character.getBgImage() ) self.layout() self.UI_buttonLayout = UI_buttonLayout = DragDroppableFormLayout( self ) self( e=True, af=((UI_buttonLayout, 'top', 0), (UI_buttonLayout, 'left', 0), (UI_buttonLayout, 'right', 0), (UI_buttonLayout, 'bottom', 0)) ) self.populate() self.highlightButtons() self.setDeletionCB( self.on_close ) def populate( self ): for button in self.character.getButtons(): self.appendButton( button ) def updateEditor( self ): self.sendEvent( 'updateEditor' ) def updateButtonList( self ): self.sendEvent( 'updateButtonList' ) def createButton( self, pos, size=Button.DEFAULT_SIZE, colour=Button.AUTO_COLOUR, label='', objs=None ): if objs is None: objs = ls( sl=True, type='transform' ) newButton = Button.Create( self.character, pos, size, colour, label, objs ) #we want the drop position to be the centre of the button, not its edge - so we need to factor out the size, which we can only do after instantiating the button so we can query its size sizeHalf = newButton.getSize() / 2.0 newButton.setPos( Vector( pos ) - sizeHalf ) self.appendButton( newButton, True ) #tell the editor to update the button list self.sendEvent( 'updateButtonList' ) return newButton def appendButton( self, button, select=False ): ui = ButtonUI( self.UI_buttonLayout, button ) if select: self.buttonSelected( ui ) self.updateButtonList() return ui def highlightButtons( self ): for buttonUI in self.getButtonUIs(): buttonUI.updateHighlightState() def getSelectedButtonUIs( self ): selButtonUIs = [] for buttonUI in self._selectedButtonUIs: if buttonUI.button.exists(): selButtonUIs.append( buttonUI ) return selButtonUIs def setSelectedButtonUIs( self, buttonUIs ): self._selectedButtonUIs = buttonUIs[:] self.updateEditor() def selectHighlightedButtons( self ): currentSelection = [] for buttonUI in self.getButtonUIs(): if buttonUI.isButtonHighlighted() == Button.COMPLETE: currentSelection.append( buttonUI ) self.setSelectedButtonUIs( currentSelection ) def breakoutButton( self, buttonUI, direction ): buttons = self.character.breakoutButton( buttonUI.button, direction ) for button in buttons: self.appendButton( button ) def refreshImage( self ): self.UI_picker.setVisibility( False ) self.UI_picker.setVisibility( True ) self.updateEditor() def buttonSelected( self, button ): mods = getModifiers() if mods & SHIFT and mods & CTRL: if button not in self._selectedButtonUIs: self._selectedButtonUIs.append( button ) elif mods & CTRL: if button in self._selectedButtonUIs: self._selectedButtonUIs.remove( button ) elif mods & SHIFT: if button in self._selectedButtonUIs: self._selectedButtonUIs.remove( button ) else: self._selectedButtonUIs.append( button ) else: self._selectedButtonUIs = [ button ] self.updateEditor() def getButtonUIs( self ): return self.UI_buttonLayout.getChildren() def clearEmptyButtons( self ): needToRefresh = False for buttonUI in self.getButtonUIs(): if buttonUI.button.isEmpty(): buttonUI.button.delete() buttonUI.delete() needToRefresh = True if needToRefresh: self.refreshImage() def delete( self ): self.character.delete() MelHLayout.delete( self ) def deleteSelectedButtons( self ): selectedButtonUIs = self.getSelectedButtonUIs() for buttonUI in selectedButtonUIs: buttonUI.button.delete() buttonUI.delete() self.refreshImage() self.updateButtonList() ### EVENT HANDLERS ### def on_close( self, *a ): CmdEditorWindow.Close() class CreatePickerButton(MelButton): ''' this class exists purely so we can test for it instead of having to test against a more generic "MelButton" instance when handling drop callbacks ''' pass class MelColourSlider(BaseMelWidget): WIDGET_CMD = colorSliderGrp KWARG_VALUE_NAME = 'rgb' KWARG_VALUE_LONG_NAME = 'rgbValue' class CmdEditorLayout(MelVSingleStretchLayout): def __init__( self, parent, buttonUIs ): self.UI_cmd = MelTextScrollField( self ) #add the popup menu to the cmd editor MelPopupMenu( self.UI_cmd, pmc=self.buildMenu ) hLayout = MelHLayout( self ) self.UI_isPython = MelCheckBox( hLayout, l='Command is Python' ) self.UI_cmdMode = MelOptionMenu( hLayout, l='Command Mode' ) for modeStr in Button.CMD_MODES_NAMES: self.UI_cmdMode.append( modeStr ) hLayout.layout() hLayout = MelHLayout( self ) self.UI_save = MelButton( hLayout, l='Save and Close', c=self.on_saveClose ) self.UI_delete = MelButton( hLayout, l='Delete and Close', c=self.on_deleteClose ) self.UI_cancel = MelButton( hLayout, l='Cancel', c=self.on_cancel ) hLayout.layout() self.setStretchWidget( self.UI_cmd ) self.layout() self.setButtons( buttonUIs ) def buildMenu( self, menu, menuParent ): cmd.menu( menu, e=True, dai=True ) MelMenuItem( menu, l='save preset', en=bool( self.UI_cmd.getValue() ), c=self.on_savePreset ) presetMenu = MelMenuItem( menu, l='load preset', sm=True ) presetManager = filesystem.PresetManager( TOOL_NAME, TOOL_CMD_EXTENSION ) for locale, presets in presetManager.listAllPresets().iteritems(): for p in presets: MelMenuItem( presetMenu, l=p.name(), c=Callback( self.loadPreset, p ) ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='manage presets', c=lambda *a: presetsUI.load( TOOL_NAME, ext=TOOL_CMD_EXTENSION ) ) def loadPreset( self, preset, *a ): cmdStrLines = filesystem.Path( preset ).read() firstLine = cmdStrLines.pop( 0 ) cmdIsPython = 'python' in firstLine self.UI_cmd.setValue( '\n'.join( cmdStrLines ) ) self.UI_isPython.setValue( cmdIsPython ) def savePreset( self ): BUTTONS = OK, CANCEL = 'Ok', 'Cancel' ret = promptDialog( t='Preset Name', m='Enter the preset name', b=BUTTONS, db=OK ) if ret == OK: name = promptDialog( q=True, tx=True ) if name: cmdStrLines = [ '//'+ ('python' if self.UI_isPython.getValue() else 'mel') ] cmdStrLines.append( self.UI_cmd.getValue() ) preset = filesystem.Preset( filesystem.GLOBAL, TOOL_NAME, name, TOOL_CMD_EXTENSION ) preset.write( '\n'.join( cmdStrLines ) ) def setButtons( self, buttonUIs ): self.buttonUIs = buttonUIs self.update() def update( self ): button = self.buttonUIs[0].button self.UI_cmd.setValue( button.getCmdStr() or '' ) self.UI_isPython.setValue( button.getCmdIsPython() ) self.UI_cmdMode.selectByIdx( button.getCmdMode() ) ### EVENT HANDLERS ### def on_savePreset( self, *a ): self.savePreset() @d_unifyUndo def on_saveClose( self, *a ): for buttonUI in self.buttonUIs: buttonUI.button.setCmdStr( self.UI_cmd.getValue() ) buttonUI.button.setCmdIsPython( self.UI_isPython.getValue() ) buttonUI.button.setCmdMode( self.UI_cmdMode.getSelectedIdx() ) for ui in PickerLayout.IterInstances(): ui.updateEditor() self.sendEvent( 'delete' ) @d_unifyUndo def on_deleteClose( self, *a ): for buttonUI in self.buttonUIs: buttonUI.button.setCmdStr( None ) for ui in PickerLayout.IterInstances(): ui.updateEditor() self.sendEvent( 'delete' ) def on_cancel( self, *a ): self.sendEvent( 'delete' ) class CmdEditorWindow(BaseMelWindow): WINDOW_NAME = 'PickerButtonCommandEditor' WINDOW_TITLE = 'Command Editor' DEFAULT_MENU = None DEFAULT_SIZE = 450, 200 FORCE_DEFAULT_SIZE = True def __init__( self, button ): self.UI_editor = CmdEditorLayout( self, button ) self.show() class ButtonList(MelObjectScrollList): def itemAsStr( self, item ): return item.button.getNode().split( ':' )[-1].split( '|' )[-1].replace( '_picker', '' ) class EditorLayout(MelVSingleStretchLayout): DIRECTIONS = DIR_H, DIR_V = range( 2 ) def __init__( self, parent, pickerUI ): self.pickerUI = pickerUI self.expand = True self.padding = 0 lblWidth = 40 self.UI_buttonLbl = MelLabel( self, align='center' ) self.UI_new = CreatePickerButton( self, l='Create Button: middle drag to place', dgc=_drag, dpc=_drop ) MelSeparator( self, h=16 ) hLayout = MelHSingleStretchLayout( self ) hLayout.expand = True vLayout = MelVSingleStretchLayout( hLayout ) self.UI_buttons = ButtonList( vLayout, w=100, ams=True, sc=self.on_selectButtonFromList, dcc=self.on_doubleClickButton ) self.UI_selectHighlighted = MelButton( vLayout, l='select highlighted', c=self.on_selectHighlighted ) vLayout.padding = 0 vLayout.setStretchWidget( self.UI_buttons ) vLayout.layout() selLayout = MelVSingleStretchLayout( hLayout ) selLayout.padding = 0 #UI for label SZ_lblLabel = MelHSingleStretchLayout( selLayout ) lbl = MelLabel( SZ_lblLabel, l='label:', w=lblWidth ) SZ_label = MelHSingleStretchLayout( SZ_lblLabel ) self.UI_selectedLabel = MelTextField( SZ_label ) self.UI_autoSize = MelButton( SZ_label, l='fit to label', c=self.on_autoSize ) SZ_label.setStretchWidget( self.UI_selectedLabel ) SZ_label.layout() SZ_lblLabel.setStretchWidget( SZ_label ) SZ_lblLabel.layout() #UI for colour self.UI_selectedColour = MelColourSlider( selLayout, label='colour:', cw=(1, lblWidth + 7), columnAttach=((1, 'left', 0), (2, 'left', 0), (3, 'left', 0)), adj=3 ) #UI for position SZ_lblPos = MelHSingleStretchLayout( selLayout ) lbl = MelLabel( SZ_lblPos, l='pos:', w=lblWidth ) SZ_pos = MelHLayout( SZ_lblPos ) SZ_lblPos.setStretchWidget( SZ_pos ) SZ_lblPos.layout() SZ_X = MelHSingleStretchLayout( SZ_pos ) self.UI_selectedPosX = MelIntField( SZ_X, min=0, max=640, step=1, cc=self.on_savePosX ) self.UI_selectedNudgeXL = MelButton( SZ_X, l='<', c=self.on_nudgeXL ) self.UI_selectedNudgeXR = MelButton( SZ_X, l='>', c=self.on_nudgeXR ) SZ_X.setStretchWidget( self.UI_selectedPosX ) SZ_Y = MelHSingleStretchLayout( SZ_pos ) self.UI_selectedPosY = MelIntField( SZ_Y, min=0, max=640, step=1, cc=self.on_savePosY ) self.UI_selectedNudgeYU = MelButton( SZ_Y, l='^', c=self.on_nudgeYU ) self.UI_selectedNudgeYD = MelButton( SZ_Y, l='v', c=self.on_nudgeYD ) SZ_Y.setStretchWidget( self.UI_selectedPosY ) SZ_X.padding = 0 SZ_Y.padding = 0 SZ_X.layout() SZ_Y.layout() SZ_pos.layout() #UI for align buttons thinButton = 18 SZ_lblAlignX = MelHSingleStretchLayout( selLayout ) MelLabel( SZ_lblAlignX, l='align:', w=lblWidth ) SZ_alignX = MelHLayout( SZ_lblAlignX ) SZ_lblAlignX.setStretchWidget( SZ_alignX ) SZ_lblAlignX.layout() MelButton( SZ_alignX, l='horiz', h=thinButton, c=self.on_alignH ) MelButton( SZ_alignX, l='vert', h=thinButton, c=self.on_alignV ) SZ_alignX.layout() #UI for size SZ_lblSize = MelHSingleStretchLayout( selLayout ) lbl = MelLabel( SZ_lblSize, l='scale:', w=lblWidth ) SZ_size = MelHLayout( SZ_lblSize ) SZ_lblSize.setStretchWidget( SZ_size ) SZ_lblSize.layout() self.UI_selectedScaleX = MelIntField( SZ_size, min=Button.MIN_SIZE, max=Button.MAX_SIZE, step=1, v=Button.MIN_SIZE, cc=self.on_saveScaleX ) self.UI_selectedScaleY = MelIntField( SZ_size, min=Button.MIN_SIZE, max=Button.MAX_SIZE, step=1, v=Button.MIN_SIZE, cc=self.on_saveScaleY ) SZ_size.layout() #setup change callbacks self.UI_selectedLabel.setChangeCB( self.on_saveLabel ) self.UI_selectedColour.setChangeCB( self.on_saveColour ) #add UI to edit the button set node self.UI_selectedObjects = MelSetMemebershipList( selLayout, h=75 ) self.UI_selectedCmdButton = MelButton( selLayout, l='', c=self.on_editCmd ) hLayout.setStretchWidget( selLayout ) hLayout.layout() selLayout.setStretchWidget( self.UI_selectedObjects ) selLayout.layout() self.setStretchWidget( hLayout ) self.layout() self.setDeletionCB( self.on_delete ) def getCurrentCharacterUI( self ): return self.pickerUI.getCurrentCharacterUI() def getSelectedButtonUIs( self ): return self.pickerUI.getSelectedButtonUIs() def updateButtonList( self ): currentCharacterUI = self.getCurrentCharacterUI() if currentCharacterUI is None: return self.UI_buttons.setItems( currentCharacterUI.getButtonUIs() ) def update( self, selectInList=True ): currentCharacterUI = self.getCurrentCharacterUI() if not currentCharacterUI: self.UI_buttonLbl.setLabel( 'create a character first!' ) self.UI_new.setEnabled( False ) return self.UI_new.setEnabled( True ) #make sure the selected buttons exist selectedButtonUIs = self.getSelectedButtonUIs() existingButtonUIs = [] for buttonUI in selectedButtonUIs: if buttonUI.button.exists(): existingButtonUIs.append( buttonUI ) #if there buttons selected... if existingButtonUIs: button = existingButtonUIs[0].button pos, size = button.getPosSize() self.UI_buttonLbl.setLabel( 'editing button "%s"' % button.getNode() ) self.UI_selectedLabel.setValue( button.getLabel(), False ) self.UI_selectedPosX.setValue( pos.x, False ) self.UI_selectedPosY.setValue( pos.y, False ) self.UI_selectedScaleX.setValue( size.x, False ) self.UI_selectedScaleY.setValue( size.y, False ) self.UI_selectedColour.setValue( button.getColour(), False ) #set set editor edits sets for ALL selected buttons self.UI_selectedObjects.setSets( [ b.button.getNode() for b in existingButtonUIs ] ) #update the auto size from label button self.UI_autoSize.enable( bool( button.getLabel() ) ) #update the command editor button self.UI_selectedCmdButton.setEnabled( bool( existingButtonUIs ) ) cmdStr = button.getCmdStr() if cmdStr: self.UI_selectedCmdButton.setLabel( '***EDIT*** Press Command' ) else: self.UI_selectedCmdButton.setLabel( 'CREATE Press Command' ) #update the selected buttons lists if selectInList: self.UI_buttons.clearSelection() self.UI_buttons.selectItems( existingButtonUIs ) else: self.UI_buttonLbl.setLabel( 'no button selected!' ) def nudge( self, buttonUI, vectorIdx, direction=1 ): mods = getModifiers() increment = 5 if mods & SHIFT: increment += 5 elif mods & CTRL: increment = 5 elif mods & ALT: increment = 1 pos = buttonUI.button.getPos() pos[ vectorIdx ] += direction * increment buttonUI.button.setPos( pos ) buttonUI.update() def align( self, buttonUI, side=DIR_H ): pos, size = buttonUI.button.getPosSize() midHSide = pos[0] + (size[0] / 2.0) midVSide = pos[1] + (size[1] / 2.0) for b in self.getSelectedButtonUIs(): if b is buttonUI: continue if side == self.DIR_H: pos, size = b.button.getPosSize() pos[0] = midHSide - (size[0] / 2.0) b.button.setPos( pos ) elif side == self.DIR_V: pos, size = b.button.getPosSize() pos[1] = midVSide - (size[1] / 2.0) b.button.setPos( pos ) b.update() ### EVENT HANDLERS ### def on_selectButtonFromList( self, *a ): charUI = self.pickerUI.getCurrentCharacterUI() if charUI: selectedButtonUIs = self.UI_buttons.getSelectedItems() self.pickerUI.getCurrentCharacterUI().setSelectedButtonUIs( selectedButtonUIs ) for buttonUI in selectedButtonUIs: buttonUI.button.select( CTRL | SHIFT ) self.update( False ) charUI.highlightButtons() @d_unifyUndo def on_doubleClickButton( self, *a ): pass @d_unifyUndo def on_selectHighlighted( self, *a ): currentCharacterUI = self.getCurrentCharacterUI() if currentCharacterUI: currentCharacterUI.selectHighlightedButtons() @d_unifyUndo def on_autoSize( self, *a ): minHeight = 14 extraPadding = 15 for buttonUI in self.getSelectedButtonUIs(): button = buttonUI.button label = button.getLabel() if label: curSize = button.getSize() width = getLabelWidth( label ) + extraPadding height = max( minHeight, curSize[1] ) button.setSize( (width, height) ) buttonUI.updateGeometry() self.update() @d_unifyUndo def on_nudgeXL( self, *a ): for buttonUI in self.getSelectedButtonUIs(): self.nudge( buttonUI, 0, -1 ) @d_unifyUndo def on_nudgeXR( self, *a ): for buttonUI in self.getSelectedButtonUIs(): self.nudge( buttonUI, 0, 1 ) @d_unifyUndo def on_nudgeYU( self, *a ): for buttonUI in self.getSelectedButtonUIs(): self.nudge( buttonUI, 1, -1 ) @d_unifyUndo def on_nudgeYD( self, *a ): for buttonUI in self.getSelectedButtonUIs(): self.nudge( buttonUI, 1, 1 ) @d_unifyUndo def on_alignH( self, *a ): self.align( self.getSelectedButtonUIs()[0], self.DIR_H ) @d_unifyUndo def on_alignV( self, *a ): self.align( self.getSelectedButtonUIs()[0], self.DIR_V ) @d_unifyUndo def on_saveLabel( self, *a ): label = self.UI_selectedLabel.getValue() for buttonUI in self.getSelectedButtonUIs(): buttonUI.button.setLabel( label ) buttonUI.update() self.UI_buttons.update() @d_unifyUndo def on_saveColour( self, *a ): colour = self.UI_selectedColour.getValue() for buttonUI in self.getSelectedButtonUIs(): buttonUI.button.setColour( colour ) buttonUI.update() @d_unifyUndo def on_savePosX( self, *a ): poxX = self.UI_selectedPosX.getValue() for buttonUI in self.getSelectedButtonUIs(): pos = buttonUI.button.getPos() pos[0] = poxX buttonUI.button.setPos( pos ) buttonUI.update() @d_unifyUndo def on_savePosY( self, *a ): posY = self.UI_selectedPosY.getValue() for buttonUI in self.getSelectedButtonUIs(): pos = buttonUI.button.getPos() pos[1] = posY buttonUI.button.setPos( pos ) buttonUI.update() @d_unifyUndo def on_saveScaleX( self, *a ): sizeX = self.UI_selectedScaleX.getValue() for buttonUI in self.getSelectedButtonUIs(): size = buttonUI.button.getSize() size[0] = sizeX buttonUI.button.setSize( size ) buttonUI.update() @d_unifyUndo def on_saveScaleY( self, *a ): sizeY = self.UI_selectedScaleY.getValue() for buttonUI in self.getSelectedButtonUIs(): size = buttonUI.button.getSize() size[1] = sizeY buttonUI.button.setSize( size ) buttonUI.update() def on_editCmd( self, *a ): CmdEditorWindow( self.getSelectedButtonUIs() ) def on_delete( self, *a ): CmdEditorWindow.Close() class EditorWindow(BaseMelWindow): WINDOW_NAME = 'pickerEditorWindow' WINDOW_TITLE = 'Picker Editor' DEFAULT_SIZE = 450, 400 DEFAULT_MENU = None FORCE_DEFAULT_SIZE = True def __init__( self, pickerUI ): self.pickerUI = pickerUI self.UI_editor = EditorLayout( self, pickerUI ) #kill the window when the scene changes self.setSceneChangeCB( self.on_sceneChange ) self.show() def update( self ): self.UI_editor.update() def updateButtonList( self ): self.UI_editor.updateButtonList() ### EVENT HANDLERS ### def on_sceneChange( self ): self.close() class PickerLayout(MelVSingleStretchLayout): def __init__( self, parent ): self.UI_tabs = tabs = MelTabLayout( self ) self.UI_tabs.setChangeCB( self.on_tabChange ) self.UI_showEditorButton = MelButton( self, l='Show Editor', c=self.on_showEditor ) self.padding = 0 self.setStretchWidget( tabs ) self.layout() #build an editor - but keep it hidden self.UI_editor = None #setup up the UI self.populate() #update button state when the selection changes self.setSelectionChangeCB( self.on_selectionChange ) #make sure the UI gets updated when the scene changes self.setSceneChangeCB( self.on_sceneChange ) #hook up an undo callback to undo button changes and update the UI self.setUndoCB( self.on_undo ) #hook up a deletion callback self.setDeletionCB( self.on_delete ) def setUndoCbState( self, state ): if state: self.setUndoCB( self.on_undo ) else: self.setUndoCB( None ) def populate( self ): self.UI_tabs.clear() for character in Character.IterAll(): self.appendCharacter( character ) def appendCharacter( self, character ): idx = len( self.UI_tabs.getChildren() ) ui = CharacterUI( self.UI_tabs, character ) self.UI_tabs.setLabel( idx, character.getName() ) def getCurrentCharacterUI( self ): selUI = self.UI_tabs.getSelectedTab() if selUI: return CharacterUI.FromStr( selUI ) return None def getSelectedButtonUIs( self ): selectedTab = self.UI_tabs.getSelectedTab() if selectedTab: currentCharacter = CharacterUI.FromStr( selectedTab ) if currentCharacter: return currentCharacter.getSelectedButtonUIs() return [] def selectCharacter( self, character ): for idx, ui in enumerate( self.UI_tabs.getChildren() ): if ui.character == character: self.UI_tabs.setSelectedTabIdx( idx ) def isEditorOpen( self ): if self.UI_editor is None: return False return self.UI_editor.exists() def updateEditor( self ): if self.isEditorOpen(): self.UI_editor.update() def updateButtonList( self ): if self.isEditorOpen(): self.UI_editor.updateButtonList() def loadPreset( self, preset, *a ): #*a exists only because this gets directly called by a menuItem - and menuItem's always pass a bool arg for some reason... check state maybe? namespaceHint = None #if there is a selection, use any namespace on the selection as the namespace hint sel = ls( sl=True, type='transform' ) if sel: namespaceHint = sel[0].split( ':' )[0] newCharacter = Character.LoadFromPreset( preset, namespaceHint ) if newCharacter: self.appendCharacter( newCharacter ) else: printWarningStr( 'No character was created!' ) def renameCurrentCharacter( self, newName ): charUIStr = self.UI_tabs.getSelectedTab() if charUIStr: charUI = CharacterUI.FromStr( charUIStr ) if charUI: charUI.character.setName( newName ) charUIIdx = self.UI_tabs.getSelectedTabIdx() self.UI_tabs.setLabel( charUIIdx, charUI.character.getName() ) def clearEmptyButtons( self ): charUI = self.getCurrentCharacterUI() if charUI: charUI.clearEmptyButtons() ### EVENT HANDLERS ### def on_showEditor( self, *a ): if not self.isEditorOpen(): self.UI_editor = EditorWindow( self ) self.updateButtonList() self.updateEditor() def on_tabChange( self, *a ): if self.isEditorOpen(): self.UI_editor.updateButtonList() self.on_selectionChange() def on_sceneChange( self, *a ): self.populate() def on_selectionChange( self, *a ): charUIStr = self.UI_tabs.getSelectedTab() if charUIStr: charUI = CharacterUI.FromStr( charUIStr ) charUI.highlightButtons() def on_undo( self, *a ): #check to see if the user only wants the undo to work if the editor is open undoOnlyIfEditorOpen = optionVar( q='zooUndoOnlyIfEditorOpen' ) if undoOnlyIfEditorOpen: if not self.isEditorOpen(): return charUI = self.getCurrentCharacterUI() if charUI: self.updateEditor() self.updateButtonList() for buttonUI in charUI.getButtonUIs(): buttonUI.updateGeometry() buttonUI.updateAppearance() def on_delete( self, *a ): EditorWindow.Close() class PickerWindow(BaseMelWindow): WINDOW_NAME = 'zooPicker' WINDOW_TITLE = 'Picker Tool' DEFAULT_SIZE = 275, 525 DEFAULT_MENU = 'File' DEFAULT_MENU_IS_HELP = False FORCE_DEFAULT_SIZE = True HELP_MENU = 'hamish@macaronikazoo.com', TOOL_NAME, None def __init__( self ): fileMenu = self.getMenu( 'File' ) fileMenu( e=True, pmc=self.buildFileMenu ) self.UI_editor = PickerLayout( self ) self.show() def buildFileMenu( self ): menu = self.getMenu( 'File' ) menu.clear() currentCharUI = self.UI_editor.getCurrentCharacterUI() charSelected = bool( currentCharUI ) charSelectedIsReferenced = True if charSelected: charSelectedIsReferenced = referenceQuery( currentCharUI.character.getNode(), inr=True ) MelMenuItem( menu, l='New Picker Tab', c=self.on_create ) MelMenuItem( menu, en=charSelected, l='Rename Current Picker Tab', c=self.on_rename ) MelMenuItem( menu, en=not charSelectedIsReferenced, l='Remove Current Picker Tab', c=self.on_remove ) MelMenuItemDiv( menu ) MelMenuItem( menu, en=not charSelectedIsReferenced, l='Remove Empty Buttons', c=self.on_clearEmpty ) MelMenuItem( menu, en=charSelectedIsReferenced, l='Remove Edits To Referenced Picker', c=self.on_clearRefEdits ) MelMenuItemDiv( menu ) MelMenuItem( menu, en=charSelected, l='Save Picker Preset', c=self.on_save ) self.SUB_presets = MelMenuItem( menu, l='Load Picker Preset', sm=True, pmc=self.buildLoadablePresets ) undoOnlyIfEditorOpen = optionVar( q='zooUndoOnlyIfEditorOpen' ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='Only Refresh On Undo If Editor Open', cb=undoOnlyIfEditorOpen, c=self.on_undoPrefChange ) def buildLoadablePresets( self, *a ): menu = self.SUB_presets man = filesystem.PresetManager( TOOL_NAME, TOOL_EXTENSION ) presets = man.listAllPresets() for loc, locPresets in presets.iteritems(): for p in locPresets: pName = p.name() MelMenuItem( menu, l=pName, c=Callback( self.UI_editor.loadPreset, p ) ) MelMenuItemDiv( menu ) MelMenuItem( menu, l='manage presets', c=self.on_loadPresetManager ) ### EVENT HANDLERS ### def on_create( self, *a ): BUTTONS = OK, CANCEL = 'Ok', 'Cancel' defaultName = filesystem.Path( file( q=True, sn=True ) ).name() ret = promptDialog( t='Create Picker Tab', m='Enter a name for the new picker tab:', text=defaultName, b=BUTTONS, db=OK ) if ret == OK: name = promptDialog( q=True, text=True ) if name: newCharacter = Character.Create( name ) self.UI_editor.populate() self.UI_editor.selectCharacter( newCharacter ) self.UI_editor.on_showEditor() def on_rename( self, *a ): currentCharacterUI = self.UI_editor.getCurrentCharacterUI() if currentCharacterUI: BUTTONS = OK, CANCEL = 'Ok', 'Cancel' ret = promptDialog( t='New Name', m='Enter the new name for the picker', tx=currentCharacterUI.character.getName(), b=BUTTONS, db=OK ) if ret == OK: newName = promptDialog( q=True, tx=True ) if not newName: printWarningStr( "You must enter a name!" ) return self.UI_editor.renameCurrentCharacter( newName ) def on_remove( self, *a ): currentCharacterUI = self.UI_editor.getCurrentCharacterUI() if currentCharacterUI: currentCharacterUI.delete() def on_clearEmpty( self, *a ): self.UI_editor.clearEmptyButtons() def on_clearRefEdits( self, *a ): currentCharacterUI = self.UI_editor.getCurrentCharacterUI() if currentCharacterUI: objs = [ currentCharacterUI.character.getNode() ] objs += [ button.getNode() for button in currentCharacterUI.character.getButtons() ] removeRefEdits( objs ) self.UI_editor.populate() def on_save( self, *a ): currentChar = self.UI_editor.getCurrentCharacterUI() if currentChar: BUTTONS = OK, CANCEL = 'Ok', 'Cancel' ret = promptDialog( t='Preset Name', m='enter the name of the preset', tx=currentChar.character.getName(), b=BUTTONS, db=OK ) if ret == OK: presetName = promptDialog( q=True, tx=True ) if presetName: currentChar.character.saveToPreset( filesystem.Preset( filesystem.GLOBAL, TOOL_NAME, presetName, TOOL_EXTENSION ) ) def on_loadPresetManager( self, *a ): presetsUI.load( TOOL_NAME, ext=TOOL_EXTENSION ) def on_undoPrefChange( self, *a ): undoOnlyIfEditorOpen = optionVar( iv=('zooUndoOnlyIfEditorOpen', int( a[0] )) ) #end
Python
import subprocess import marshal import inspect import pickle import time import imp import sys import os import gc from zlib import crc32 from modulefinder import ModuleFinder import filesystem from filesystem import Path, removeDupes _MODULE_TYPE = type( os ) def getPythonStdLibDir(): ''' returns the root directory of the current python interpreter's root directory ''' return Path( inspect.getfile( os ) ).up() _LIB_PATHS = ( getPythonStdLibDir(), ) def logMessage( *a ): print ' '.join( map( str, a ) ) logWarning = logMessage def getDeps( aModule ): if not isinstance( aModule, _MODULE_TYPE ): raise TypeError( "must specify a module object" ) dependencySet = set() getfile = inspect.getfile def _getDeps( module ): #grab module dependencies for n, o in aModule.__dict__.iteritems(): try: objectFile = Path( getfile( o ) ) #this happens on builtins... so skip em except TypeError: continue if isinstance( o, _MODULE_TYPE ): if objectFile in dependencySet: continue dependencySet.add( objectFile ) _getDeps( o ) #recurse else: dependencySet.add( objectFile ) _getDeps( aModule ) return dependencySet def isScriptInSuperiorBranch( scriptPath ): ''' returns whether the given scriptPath can be found in a directory searched before the given script. Ie, if the following paths are in sys.path: sys.path = [ 'd:/somePath', 'd:/otherPath' ] isScriptInSuperiorBranch( 'd:/otherPath/someScript.py' ) if there is a someScript.py in d:/somePath, this function will return True ''' if not isinstance( scriptPath, Path ): scriptPath = Path( scriptPath ) originalPath = scriptPath for p in sys.path: if scriptPath.isUnder( p ): scriptPath = scriptPath - p break for p in sys.path: possibleSuperiorPath = p / scriptPath if possibleSuperiorPath.exists(): if possibleSuperiorPath == originalPath: return None return possibleSuperiorPath class DependencyNode(dict): def addDepedency( self, callerScriptPaths ): curDepNode = self for callScript in callerScriptPaths[ 1: ]: #skip the first item - its always the script being walked for dependencies #builtins have None for their paths as do modules in the stdlib if they're in a zip file, so break #because at this point we don't care about downstream deps because we don't change the stdlib if callScript is None: break curDepNode = curDepNode.setdefault( Path( callScript ), DependencyNode() ) return curDepNode def findDependents( self, changedScriptPath ): affected = [] for srcFile, depNode in self.iteritems(): if srcFile == changedScriptPath: continue if changedScriptPath in depNode: affected.append( srcFile ) else: if depNode: #no point recursing if the depNode is empty affected += depNode.findDependents( changedScriptPath ) return affected class DepFinder(ModuleFinder): ''' simple wrapper to ModuleFinder class to discover dependencies for a given script path NOTE: the script doesn't get executed, modulefinder just walks through the script bytecode, looks for imports that happen, and then asks python to resolve them to locations on disk ''' #depth of the dependency tree - by default its just a single import deep - ie it only records immediate dependencies. #change this to None to make it arbitrary depth #NOTE: a depth of 1 is sufficient for deep dependency parsing because the DependencyTree has a 1-depth node for each script _DEPTH = 1 def __init__( self, scriptPath, additionalPaths=(), depth=_DEPTH, *a, **kw ): self._depth = depth self._depNode = DependencyNode() self._callerStack = [] ModuleFinder.__init__( self, *a, **kw ) #add in the additional paths preSysPath = sys.path[:] for p in reversed( additionalPaths ): sys.path.insert( 0, str( p ) ) #insert the path of the script sys.path.insert( 0, str( Path( scriptPath ).up() ) ) try: self.run_script( scriptPath ) except SyntaxError: pass finally: #restore the original sys.path sys.path = preSysPath def __contains__( self, item ): return item in self._depNode def __getitem__( self, item ): return self._depNode[ item ] def __setitem__( self, item, value ): self._depNode[ item ] = value def load_module( self, fqname, fp, pathname, file_info ): if pathname: if not isinstance( pathname, Path ): pathname = Path( pathname ) if pathname.hasExtension( 'cmd' ): line = fp.readline().strip() suffix, mode, type = file_info[0], file_info[1], imp.PY_SOURCE #pretend the cmd script is a py file assert '@setlocal' in line and '& python' in line, "Doesn't seem to be a python cmd script!" return ModuleFinder.load_module( self, fqname, fp, pathname, file_info ) def import_hook( self, name, caller=None, fromlist=None, level=None ): if caller is None: return None try: self._callerStack.append( caller.__file__ ) return ModuleFinder.import_hook( self, name, caller, fromlist ) finally: self._callerStack.pop() def import_module( self, partnam, fqname, parent ): depth = self._depth if depth is None or len( self._callerStack ) <= depth: r = ModuleFinder.import_module( self, partnam, fqname, parent ) if r is not None: self._depNode.addDepedency( self._callerStack +[ r.__file__ ] ) return r def getDependencyNode( self ): return self._depNode def findDependents( self, changedScriptPath ): return self._depNode.findDependents( changedScriptPath ) def generateFileCRC( filePath ): with file( filePath, 'rb' ) as f: return crc32( f.read() ) class DependencyTree(DependencyNode): _VERSION = 0 _CACHE_PATH = Path( '~/_py_dep_cache' ) @classmethod def _convertDictDataTo( cls, theDict, keyCastMethod ): def convToDict( theDict ): for key in theDict.keys(): value = theDict.pop( key ) key = keyCastMethod( key ) theDict[ key ] = value if isinstance( value, dict ): convToDict( value ) convToDict( theDict ) return theDict @classmethod def ToSimpleDict( cls, theDict ): cls._convertDictDataTo( theDict, str ) @classmethod def FromSimpleDict( cls, theDict ): cls._convertDictDataTo( theDict, Path ) def __new__( cls, dirsToWalk=(), dirsToExclude=(), extraSearchPaths=(), rebuildCache=False, skipLib=True ): ''' constructs a new dependencyTree dictionary or loads an existing one from a disk cache, and strips out files that no longer exist ''' if not dirsToWalk: dirsToWalk = sys.path[:] dirsToWalk = map( Path, dirsToWalk ) dirsToExclude = map( Path, dirsToExclude ) if skipLib: dirsToExclude += _LIB_PATHS cache = Path( cls._CACHE_PATH ) self = None if cache.exists() and not rebuildCache: try: with file( cache, 'r' ) as f: version, self = pickle.load( f ) except: pass else: if version == cls._VERSION: cls.FromSimpleDict( self ) #keys are converted to strings before pickling - so convert them back to Path instances cls.FromSimpleDict( self._crcs ) cls.FromSimpleDict( self._stats ) #remove any files from the cache that don't exist for f in self.keys(): if not f.exists(): self.pop( f ) else: self = None logWarning( 'VERSION UPDATE: forcing rebuild' ) if self is None: self = dict.__new__( cls ) self._crcs = {} self._stats = {} self._dirs = dirsToWalk self._dirsExclude = dirsToExclude self._extraPaths = extraSearchPaths self.freshenDependencies() return self def __init__( self, dirsToWalk=(), dirsToExclude=(), extraSearchPaths=(), rebuildCache=False, skipLib=True ): dict.__init__( self ) def getFiles( self ): files = [] for d in self._dirs: skipDir = False for dd in self._dirsExclude: if d.isUnder( dd ): skipDir = True break if skipDir: continue for dirPath, dirNames, fileNames in os.walk( d ): dirPath = Path( dirPath ) skipDir = False for d in self._dirsExclude: if dirPath.isUnder( d ): skipDir = True break if skipDir: continue for f in fileNames: f = dirPath / f if f.hasExtension( 'py' ): files.append( f ) #if the cmd script looks like its a python cmd script, then add it to the list - the DepFinder class knows how to deal with these files elif f.hasExtension( 'cmd' ): with file( f ) as fopen: line = fopen.readline().strip() if '@setlocal ' in line and '& python' in line: files.append( f ) return files def freshenDependencies( self ): ''' freshens the dependency tree with new files - deleted files are cleaned out of the cache at load time, see the __new__ method for details ''' padding = 15 start = time.clock() files = self.getFiles() extraSearchPaths = self._extraPaths stats = self._stats crcs = self._crcs for f in files: #do we need to re-parse dependencies? first we check the data in the file stat checkCrc = False currentStat = os.stat( f ).st_mtime cachedStat = stats.get( f, None ) if cachedStat == currentStat: continue #store the mod time stats[ f ] = currentStat #if they don't match, check the crc currentCrc = generateFileCRC( f ) cachedCrc = crcs.get( f, 0 ) if cachedCrc == currentCrc: continue elif cachedCrc == 0: logMessage( 'new file:'.ljust( padding ), f ) else: logMessage( 'stale file:'.ljust( padding ), f ) finder = DepFinder( f, extraSearchPaths ) self[ f ] = finder.getDependencyNode() crcs[ f ] = currentCrc self.writeCache() logMessage( 'Time to update cache: %0.2g' % (time.clock()-start) ) logMessage() def findDependents( self, changedScriptPath ): ''' returns a 2-tuple of scripts that immediately rely on changedScriptPath. ie: the scripts that directly import the queried script, and those that import the queried script by proxy. Secondary scripts are any downstream script that imports the one in question - regardless of how far down the dependency chain it is. ie: given scriptA, scriptB, scriptC scriptA imports scriptB scriptB imports scriptC calling findDependents( scriptC ) will return scriptB as an immediate dependent, and scriptA as a secondary dependent ''' changedScriptPath = Path( changedScriptPath ) #make sure the script in question doesn't have a superior script hasSuperior = isScriptInSuperiorBranch( changedScriptPath ) if hasSuperior is not None: logWarning( 'WARNING - a superior script was found: %s. Using it for dependency query instead!' % hasSuperior ) changedScriptPath = hasSuperior primaryAffected = set() secondaryAffected = set() #add the primary affected dependencies for script, depNode in self.iteritems(): if script == changedScriptPath: continue #if the changedScript is in this dependency node, add the script to the list of affected if changedScriptPath in depNode: primaryAffected.add( script ) #don't even start looking for secondary deps if there are no primary deps... if primaryAffected: #returns whether it has found any new dependencies def gatherSecondaryDependencies( theDepNode ): stillAdding = False for script, depNode in theDepNode.iteritems(): if script == changedScriptPath: continue if script in primaryAffected or script in secondaryAffected: continue #if its not, we had better recurse and see if it is somewhere deeper in the dependency tree for this script else: for sub_script in depNode.iterkeys(): if sub_script in primaryAffected or sub_script in secondaryAffected: secondaryAffected.add( script ) stillAdding = True return stillAdding #keep calling gatherSecondaryDependencies until it returns False while gatherSecondaryDependencies( self ): pass return primaryAffected, secondaryAffected def findDependencies( self, scriptPath, depth=None, includeFilesFromExcludedDirs=True ): ''' returns a list of dependencies for scriptPath ''' scriptPath = Path( scriptPath ) #make sure the script in question doesn't have a superior script hasSuperior = isScriptInSuperiorBranch( scriptPath ) if hasSuperior is not None: logWarning( 'WARNING - a superior script was found: %s. Using it for dependency query instead!' % hasSuperior ) scriptPath = hasSuperior deps = set() maxDepth = depth def getDeps( script, depth=0 ): if maxDepth is not None and depth >= maxDepth: return if script in self: for ss in self[ script ]: if ss in deps: continue deps.add( ss ) getDeps( ss, depth+1 ) getDeps( scriptPath ) #if we're not including files from excluded directories, go through the list of deps and remove files that are under any of the exlude dirs if not includeFilesFromExcludedDirs: depsWithoutExcludedFiles = [] for dep in deps: shouldFileBeIncluded = True for excludeDir in self._dirsExclude: if dep.isUnder( excludeDir ): shouldFileBeIncluded = False break if shouldFileBeIncluded: depsWithoutExcludedFiles.append( dep ) deps = depsWithoutExcludedFiles return list( sorted( deps ) ) def writeCache( self ): self.ToSimpleDict( self ) self.ToSimpleDict( self._crcs ) self.ToSimpleDict( self._stats ) with open( self._CACHE_PATH, 'w' ) as f: pickle.dump( (self._VERSION, self), f ) self.FromSimpleDict( self ) self.FromSimpleDict( self._crcs ) self.FromSimpleDict( self._stats ) def moduleNameToScript( self, moduleName ): for scriptPath in self: if scriptPath.name() == moduleName or moduleName in scriptPath: if makeScriptPathRelative( scriptPath ).name() == moduleName: return scriptPath raise ValueError( "Module cannot be mapped to any script" ) def _depTreeStr( scriptPath, dependencyTree, depth=None ): if not isinstance( scriptPath, Path ): scriptPath = Path( scriptPath ) indent = ' ' #the string used to "indent" dependencies in the tree maxDepth = depth alreadySerialized = set() def genLines( script, depth=0 ): lines = [] depthPrefix = indent * depth if maxDepth and depth >= maxDepth: return lines try: scriptDeps = dependencyTree[ script ] except KeyError: return lines alreadySerialized.add( script ) for s in scriptDeps: lines.append( '%s%s' % (depthPrefix, s) ) if s in alreadySerialized: continue alreadySerialized.add( s ) lines += genLines( s, depth+1 ) return lines lines = [ scriptPath ] lines += genLines( scriptPath, 1 ) return '\n'.join( lines ) def printDepTree( scriptPath, dependencyTree, depth=None ): logMessage( _depTreeStr( scriptPath, dependencyTree, depth ) ) def generateDepTree( rebuildCache=False ): return DependencyTree( rebuildCache=rebuildCache ) def makeScriptPathRelative( scriptFilepath ): ''' will attempt to transform the name of the given script into the shortest possible path relative to the python search paths defined in sys.path. For example, just say you have a package called "foo" this package contains the script: "bar.py" given the full path to bar.py this function will return: "foo/bar.py" ''' scriptFilepath = Path( scriptFilepath ) sysPaths = map( Path, sys.path ) bestFitPath = None for p in sysPaths: if scriptFilepath.isUnder( p ) or len( p ) > len( bestFitPath ): if bestFitPath is None: bestFitPath = p if bestFitPath is None: raise ValueError( "Cannot find a path under any of the paths in sys.path!" ) shortestPath = scriptFilepath - bestFitPath return shortestPath def packageScripts( scriptFilesToPackage, destPackageFilepath, dependencyTree ): ''' will package all given files and import dependencies into a single zip file ''' destPackageFilepath = Path( destPackageFilepath ).setExtension( 'zip' ) if destPackageFilepath.exists(): destPackageFilepath.delete() filesToPackage = map( Path, scriptFilesToPackage ) for f in scriptFilesToPackage: filesToPackage += dependencyTree.findDependencies( f, None, False ) if not filesToPackage: return None #remove any duplicate files... filesToPackage = removeDupes( filesToPackage ) #this is a little hacky - but we don't want to re-distribute wingdbstub so lets check to see if its in the list of files for f in filesToPackage: if f.name() == 'wingdbstub': filesToPackage.remove( f ) break #now build the zip file import zipfile with zipfile.ZipFile( str( destPackageFilepath ), 'w' ) as thePackage: for f in filesToPackage: thePackage.write( str( f ), str( makeScriptPathRelative( f ) ) ) return destPackageFilepath def getScriptTests( scriptFilepath, depTree=None ): if not isinstance( scriptFilepath, Path ): scriptFilepath = Path( scriptFilepath ) if depTree is None: depTree = generateDepTree() testDependencyDict = {} for script in depTree: if script.name().startswith( 'devTest_' ): testDependencyDict[ script ] = depTree.findDependencies( script ) scriptTestCandidates = [] for test, testDependencies in testDependencyDict.iteritems(): if scriptFilepath in testDependencies: scriptTestCandidates.append( test ) return scriptTestCandidates def flush( dirsNeverToFlush=() ): ''' flushes all loaded modules from sys.modules which causes them to be reloaded when next imported... super useful for developing crap within a persistent python environment dirsNeverToFlush should be a list - scripts under any of directories in this list won't be flushed ''' dirsNeverToFlush = list( dirsNeverToFlush ) #these dirs never get flushed keysToDelete = [] dirsNeverToFlush.extend( _LIB_PATHS ) flushableExtensions = 'py', 'pyc', 'pyo' builtin_module_names = set( sys.builtin_module_names ) while True: try: for modName, mod in sys.modules.items(): try: modPath = filesystem.Path( mod.__file__ ) except AttributeError: continue #if its in the list of builtin module names, skip it - no point flushing builtins if modName in builtin_module_names: continue #only flush the module if has a valid extension - binary modules don't unload properly in CPython if modPath.getExtension() not in flushableExtensions: continue doFlush = True for ignoreDir in dirsNeverToFlush: if modPath.isUnder( ignoreDir ): doFlush = False break if doFlush: keysToDelete.append( modName ) break #sometimes the sys.modules dict changes while the above loop is happening which causes a runtimeerror to be thrown. so just try again if it happens... except RuntimeError: continue for keyToDelete in keysToDelete: try: del( sys.modules[ keyToDelete ] ) except KeyError: continue #force a garbage collection gc.collect() #end
Python