Optimizing LoopFunction - Python

Optimizing LoopFunction - Python

Anonymous
Not applicable
2,036 Views
3 Replies
Message 1 of 4

Optimizing LoopFunction - Python

Anonymous
Not applicable

Hello everyone,

 

I am currently making a script in Python, and at some point I have to rotate every component of a mesh in order to have them follow an angle between function. However my script is quite long, and would not be able to process more than a few thousands polys before it become unefficient.

Here is the bit of script I was talking about, it is in a for loop, meaning it repeat for every polygon in the facePoly variable:

angleBetweenVectors.append((cmds.angleBetween( euler=True, v1=(geoNormals[current]), v2=(camList))))
cmds.manipRotateContext( mode = 9, orientObject = facePoly[current], activeHandle=0, rotate = (((1 - abs(thresoldRatio[current]))*(angleBetweenVectors[current][0])), ((1 - abs(thresoldRatio[current])))*(angleBetweenVectors[current][1]), ((1 - abs(thresoldRatio[current]))*(angleBetweenVectors[current][2]))), useManipPivot = True, tweakMode = False)

 

I am using the manipRotateContext, because I could not find out how to use the component's pivot for the rotation otherwise. But it also makes a new rotation manipulator for evey face, which I don't know how to make disappear unless I delete the mesh and undo.

Capture.JPG
Also, every rotation command is echoed in the script editor. I thought it might be what is causing it to be so slow, but I can't make the commands disappear using:

cmds.commandEcho(addFilter=('rotate', 'manipRotateContext'))

 

The code echoed in the script editor is like this one, one line for every poly:
rotate -r -p -9.091062cm 29.075383cm -8.392409cm -oa 0rad 0rad 0rad -ws -fo 68.885534 19.157418 40.271034 ;

If you guys had any idea of how I could optimize this bit of code/ hide the rotate command echoed in the script editor / hide the created manipulators by the manipRotateContext without deleting and undoing, I would be very interested.

 

Thank you in advance,

 

Martin

 

0 Likes
Accepted solutions (2)
2,037 Views
3 Replies
Replies (3)
Message 2 of 4

tkaap2
Autodesk
Autodesk
Accepted solution

Here's a proof-of-concept for an alternative approach (which definitely has it's own drawbacks, too).  This module estimates the componentPivot location as the average of each face's verts, then rotates the face normal by the angleBetween.

 

rotateEachComponent.py

import maya.cmds as mc
import maya.mel as mm
from math import pi
import re
from operator import sub

"""
# DEMO:
# import rotateEachComponent as rec
# rec.run()
https://forums.autodesk.com/t5/maya-programming/optimizing-loopfunction-python/td-p/9111923 angleBetweenVectors.append((cmds.angleBetween( euler=True, v1=(geoNormals[current]), v2=(camList)))) cmds.manipRotateContext( mode = 9, orientObject = facePoly[current], activeHandle=0, rotate = (((1 - abs(thresoldRatio[current]))*(angleBetweenVectors[current][0])), ((1 - abs(thresoldRatio[current])))*(angleBetweenVectors[current][1]), ((1 - abs(thresoldRatio[current]))*(angleBetweenVectors[current][2]))), useManipPivot = True, tweakMode = False) Improve a way to rotate each poly component to a new angle (angleBetween), in a way that doesn't leave a trail of rotateContexts and rotateManips in its wake Also, make it fast, and scale well to a poly mesh with thousands of faces. Also, use the component's pivot for rotation. This might be fine to use the components center, or average vertex position. # Added this into render post-frame mel: print("post-render message1\n"); python("import rotateEachComponent as rec; reload(rec); rec.loadForUpdate([\"pSphere1\"],[\"locator1\"]); rec.updateAims()") print("post-render message2\n"); """ space = re.compile(' +') shapesToAim = [] aimTargetTransforms = [] def updateAims(): # A helper method to update the aiming (for use on frame changes) # for pair in zip(shapesToAim, aimTargetTransforms): print "updating pair %s"%(pair,) rotateEachComponent(pair[0], mc.xform(pair[1],q=1,t=1,ws=1)) def loadForUpdate(listOfShapes, listOfAimTargetTransforms): # loads the module globals with the shape-of-components and the aiming points # (for use when loading saved scenes instead of regenerating them from the run() method) global shapesToAim, aimTargetTransforms print "shapes to aim: %s"%(listOfShapes,) print "target transforms: %s"%(listOfAimTargetTransforms,) shapesToAim = listOfShapes aimTargetTransforms = listOfAimTargetTransforms def run(): # for doing basic setup to create a test scene: # global shapesToAim, aimTargetTransforms mc.file(f=1,new=1) Tx = createShape(shape='sphere') detachFaces(Tx) shapesToAim = [] aimTargetTransforms = [] shapesToAim.append(Tx) # load shape-transform into the global list aimLocator = mc.spaceLocator()[0] aimLocation = (1,1,1) mc.move(aimLocation[0], aimLocation[1], aimLocation[2], aimLocator) aimTargetTransforms.append(aimLocator) # load aim transform into the global list # mc.scale(0.1, 0.1, 0.1, aimLocator) rotateEachComponent(Tx, aimLocation) # for convenience, print out the syntax to re-load these components for use later print "rec.loadForUpdate([\"%s\"],[\"%s\"])"%(Tx,aimLocator) print "rec.rotateEachComponent(\"%s\",mc.xform(\"%s\",q=1,t=1,ws=1))"%(Tx,aimLocator) pass def detachFaces(Tx): # detaches a mesh so that faces do not share edges # numVerts = mc.polyEvaluate(Tx,v=True) mc.select(Tx + ".vtx[0:%d]"%(numVerts-1) ) mm.eval("performDetachComponents") mc.select(cl=1) def createShape(shape='cube'): # do timing tests: if shape is 'sphere': (Tx, history) = mc.polySphere(r=100) #(Tx, history) = mc.polySphere(sx=100,sy=100) elif shape is 'torus': (Tx, history) = mc.polyTorus() else: # cube (Tx, history) = mc.polyCube() return Tx pass def getCenterOfFace(faceStr): facePts = mc.xform(faceStr,q=1,t=1,ws=1) numPts = len(facePts) / 3 center = [0]*3 for pt in xrange(numPts): center[0] += facePts[pt*3] center[1] += facePts[pt*3+1] center[2] += facePts[pt*3+2] invNumPts = 1.0/numPts center[0] *= invNumPts center[1] *= invNumPts center[2] *= invNumPts """ # for validation, add a small locator at that point addLocator(center) """ return center def addLocator(point): loc = mc.spaceLocator() mc.move(point[0],point[1],point[2],loc) mc.scale(0.1,0.1,0.1,loc) def parsePolyInfoFaceNormals(shape): """ The polyInfo command irritatingly returns information for text printout, not in a data structure. This method builds a data structure form the text printout for face normals. """ stringResult = mc.polyInfo(shape,faceNormals=True) fns = [] for rest in stringResult: rest = space.sub(",",rest) rest = rest.split(",") #print(rest) fns.append([ float(rest[2]),float(rest[3]),float(rest[4])]) #print fv return fns def rotateEachComponent(shape, aimAtPos=None): # For each face in 'shape', compute the angle needed to aim the component's normal at # aimAtPos's world-space position. """ Find vector from camera to object""" if aimAtPos is None: # Use vector of default camera # aimAtPos = mc.xform("persp", t=True, ws=1, q=1) aimAtVec = aimAtPos # If false, aim the component in the aimAtPos direction-from-origin rather than # the aimAtPos direction from the component. wantComponentAim = True faceNormals = parsePolyInfoFaceNormals(shape) numFaces = mc.polyEvaluate(shape, f=True) for faceNum in range(numFaces): faceStr = shape+".f[%d]"%faceNum # estimate pivot for component: faceCenter = getCenterOfFace(faceStr) if wantComponentAim: aimAtVec = map(sub,aimAtPos,faceCenter) # v1 - v2 (aim from v2 to v1) angle = mc.angleBetween(v1=faceNormals[faceNum], v2=aimAtVec, euler=True) mc.rotate(angle[0], angle[1], angle[2], faceStr, pivot=faceCenter) pass
Message 3 of 4

tkaap2
Autodesk
Autodesk
Accepted solution

This second version splits the mesh into one transform per face, and connects a live angleBetween node to point each face at the target.  Here it is with a 100x100 poly plane. 

compRotate2.0066.png

 

The script and movie are attached.

 

It takes a little bit to set up, and evaluating each angleBetween isn't quick, but the results are reliable with minimal hassle to maintain as other animation is happening.

Message 4 of 4

Anonymous
Not applicable

This is perfect, I will evaluate both solutions in order to determine which is the most interesting for my use. Thank you so much for your time Tony !

 

Martin

0 Likes