def timer(mode="l", function=""): if mode == "s": try: startTime = cmds.timer(startTimer=True) G.UM_timerMessage = "startTime: %s\n" % startTime G.UM_timerLap = 1 except: pass elif mode == "l": try: lapTime = cmds.timer(lapTime=True) G.UM_timerMessage += "lapTime %s: %s\n" % (G.UM_timerLap, lapTime) G.UM_timerLap += 1 except: pass elif mode == "e": try: fullTime = cmds.timer(endTimer=True) G.UM_timerMessage += "Timer: %s took %s sec.\n" % (function, fullTime) except: pass print G.UM_timerMessage
def timer(mode="l", function=""): if mode == "s": try: startTime = cmds.timer( startTimer=True) G.UM_timerMessage = "startTime: %s\n"%startTime G.UM_timerLap = 1 except: pass elif mode == "l": try: lapTime = cmds.timer( lapTime=True) G.UM_timerMessage += "lapTime %s: %s\n"%(G.UM_timerLap, lapTime) G.UM_timerLap += 1 except: pass elif mode == "e": try: fullTime = cmds.timer( endTimer=True) G.UM_timerMessage += "Timer: %s took %s sec.\n"%(function, fullTime) except: pass print G.UM_timerMessage
def onRelease(self): cmds.timer(e=True) self.endTime = cmds.currentTime(q=True) if "translate" in self.mode: if self.channelBox is True: if self.simplify is True: utils().simplify(self.object, (self.startTime, self.endTime), at=self.attributes) else: if self.simplify is True: if self.shape is True: simpAt = ['xValue', 'yValue', 'zValue'] else: simpAt = ['tx', 'ty', 'tz'] utils().simplify(self.object, (self.startTime, self.endTime), at=simpAt) if "rotate" in self.mode and self.shape is False: if self.channelBox is True: # euler filter for at in self.attributes: cmds.filterCurve(self.object + '.' + at, f='euler', s=self.startTime, e=self.endTime) if self.simplify is True: utils().simplify(self.object, (self.startTime, self.endTime), at=self.attributes) else: for at in ['rx', 'ry', 'rz']: cmds.filterCurve(self.object + '.' + at, f='euler', s=self.startTime, e=self.endTime) if self.simplify is True: utils().simplify(self.object, (self.startTime, self.endTime), at=['rx', 'ry', 'rz']) mel.eval('timeControl -e -endScrub $gPlayBackSlider;')
def main(meshName, outputFolder): cmds.timer(s=True) cmds.undoInfo( state=False) mel.eval("paneLayout -e -manage false $gMainPane") #Take the markers arranged in groups markersSelection = sorted(cmds.listRelatives("TopMarkers")) + sorted(cmds.listRelatives("TopMiddleMarkers")) + sorted(cmds.listRelatives("MiddleMarkers")) + sorted(cmds.listRelatives("MiddleBottomMarkers")) + sorted(cmds.listRelatives("BottomMarkers")) #Take the geodesic vertices geodesicVertices = cmds.ls(cmds.sets("MouthArea", q=True), flatten=True) + cmds.ls(cmds.sets("REyeArea", q=True), flatten=True) + cmds.ls(cmds.sets("LEyeArea", q=True), flatten=True) matrix = calculateDistanceMatrixToFile(meshName, outputFolder, markersSelection, geodesicVertices, calculateEuclideanMatrix = True, calculateGeodesicMatrix=True) mel.eval("paneLayout -e -manage true $gMainPane") cmds.undoInfo( state=True) time = cmds.timer(e=True) print("Matrix calculations completed. Files created at: " + outputFolder) print("Running time: " + str(time) + "s")
def onPress(self): self.attributes = cmds.channelBox("mainChannelBox", query=True, sma=True) if self.attributes is None: self.attributes = [] self.lastT = 0 cmds.timer(s=True) self.startTime = cmds.currentTime(q=True) self.lastHit = cmds.draggerContext(self.dragCtx, q=True, anchorPoint=True) # get cam vectors camObject = utils().getCam() viewDir = camObject.viewDirection(om.MSpace.kWorld) self.upDir = camObject.upDirection(om.MSpace.kWorld) rightDir = camObject.rightDirection(om.MSpace.kWorld) self.lastVec = None self.lastRot = [0.0, 0.0, 0.0] self.idQuat = utils().quatFromObj(self.object) self.idVec = utils().localToWorld(self.idLocalVec, self.object) mel.eval('timeControl -e -beginScrub $gPlayBackSlider;')
def onDrag(self): # timer lap = cmds.timer(lap=True) curTime = cmds.currentTime(q=True) sub = lap - self.lastT #get position dragPosition = cmds.draggerContext(self.dragCtx, q=True, dragPoint=True) # start operations if sub > self.timeFactor / self.fps: self.objPos = cmds.xform(self.object, q=True, ws=True, t=True) # translate if "translate" in self.mode: # key attributes if self.channelBox is True: if 'tx' in self.attributes: cmds.move(dragPosition[0] * self.unit, self.object, ws=True, absolute=True, wd=True, x=True) cmds.setKeyframe(self.object, at='tx') if 'ty' in self.attributes: cmds.move(dragPosition[1] * self.unit, self.object, ws=True, absolute=True, wd=True, y=True) cmds.setKeyframe(self.object, at='ty') if 'tz' in self.attributes: cmds.move(dragPosition[2] * self.unit, self.object, ws=True, absolute=True, wd=True, z=True) cmds.setKeyframe(self.object, at='tz') else: cmds.move(dragPosition[0] * self.unit, dragPosition[1] * self.unit, dragPosition[2] * self.unit, self.object, ws=True, absolute=True, wd=True) if self.shape: cmds.setKeyframe(self.object) else: cmds.setKeyframe(self.object, at='translate') # rotate if "rotate" in self.mode and self.shape is False: self.vector = om.MVector(dragPosition[0] - self.objPos[0], dragPosition[1] - self.objPos[1], dragPosition[2] - self.objPos[2]) if self.autoAim is True: if self.lastVec is None: self.idVec = self.vector rotator = om.MQuaternion(self.idVec, self.vector) result = self.idQuat * rotator euler = result.asEulerRotation() dragRotation = [ math.degrees(euler.x), math.degrees(euler.y), math.degrees(euler.z) ] relRotation = [ new - old for new, old in zip(dragRotation, self.lastRot) ] # key attributes if self.channelBox is True: if 'rx' in self.attributes: cmds.rotate(dragRotation[0], ws=True, absolute=True, x=True) cmds.setKeyframe(self.object, at='rx') if 'ry' in self.attributes: cmds.rotate(dragRotation[1], ws=True, absolute=True, y=True) cmds.setKeyframe(self.object, at='ry') if 'rz' in self.attributes: cmds.rotate(dragRotation[2], ws=True, absolute=True, z=True) cmds.setKeyframe(self.object, at='rz') else: cmds.rotate(dragRotation[0], dragRotation[1], dragRotation[2], ws=True, absolute=True) # cmds.rotate(relRotation[0],relRotation[1],relRotation[2],ws=True,relative=True,eu=True) self.lastRot = dragRotation cmds.setKeyframe(self.object, at='rotate') # looping variables self.lastVec = self.vector # change time cmds.currentTime(curTime + 1) cmds.currentTime(curTime + 1) self.lastT = lap
def calculateDistanceMatrixToFile(meshName, outputFolder, markersList, geodesicVertices, calculateEuclideanMatrix=True, calculateGeodesicMatrix=True): #Start progress bar progressAmount = 0; gMainProgressBar = mel.eval('$tmp = $gMainProgressBar') cmds.progressBar(gMainProgressBar, edit=True, progress=progressAmount, status='Calculating...', isInterruptable=True, bp=True ) nVert = cmds.polyEvaluate(meshName, v=True) outFileEuclidean = None outFileGeodesics = None outFileHybrid = None #Open the output files if (calculateEuclideanMatrix): if not os.path.exists(outputFolder): try: os.makedirs(outputFolder) except OSError as exc: if exc.errno != errno.EEXIST: raise path = outputFolder+"/eucMatrix.mtx" outFileEuclidean = open(path, 'w') if (calculateGeodesicMatrix): if not os.path.exists(outputFolder): try: os.makedirs(outputFolder) except OSError as exc: if exc.errno != errno.EEXIST: raise path = outputFolder+"/geoMatrix.mtx" outFileGeodesics = open(path, 'w') if (calculateEuclideanMatrix and calculateGeodesicMatrix): if not os.path.exists(outputFolder): try: os.makedirs(outputFolder) except OSError as exc: if exc.errno != errno.EEXIST: raise path = outputFolder+"/hybMatrix.mtx" outFileHybrid = open(path, 'w') #Go to frame 0 (reference frame) cmds.currentTime(0) #Create a list with the closest vertices to the markers vertexMarkers = matchMarkersWithMesh(markersList, meshName) #Progress control progressStep = float(100) / float(nVert) euclideanTime = 0 geodesicTime = 0 hybridTime = 0 #Calculate distance matrix values for every vertex if (calculateEuclideanMatrix or calculateGeodesicMatrix): for i in range (0, nVert): progressAmount += progressStep cmds.progressBar(gMainProgressBar, edit=True, status="Calculating distance matrices for row " + str(i) + " of " + str(nVert), progress=progressAmount) for j in range (0, len(vertexMarkers)): v1Name = meshName + ".vtx[" + str(i) + "]" v2Name = meshName + ".vtx[" + str(vertexMarkers[j]) + "]" eucDist = 0 geoDist = 0 if (calculateEuclideanMatrix): cmds.timer(s=True, name="euclideanTimer") v1 = cmds.pointPosition(v1Name) v2 = cmds.pointPosition(v2Name) eucDist = getEuclideanDistance(v1, v2) outFileEuclidean.write(str(eucDist)+"\n") euclideanTime += cmds.timer(e=True, name="euclideanTimer") if (calculateGeodesicMatrix): cmds.timer(s=True, name="geodesicTimer") geoDist = getGeodesicDistancev2(meshName, i, vertexMarkers[j]) outFileGeodesics.write(str(geoDist)+"\n") geodesicTime += cmds.timer(e=True, name="geodesicTimer") if (calculateEuclideanMatrix and calculateGeodesicMatrix): cmds.timer(s=True, name="hybridTimer") hybDist = getHybridDistance(geodesicVertices, v1Name, eucDist, geoDist) outFileHybrid.write(str(hybDist)+"\n") hybridTime += cmds.timer(e=True, name="hybridTimer") #Progress control if cmds.progressBar(gMainProgressBar, q=True, ic=True): cmds.progressBar(gMainProgressBar, edit=1, ep=1) if (outFileEuclidean != None): outFileEuclidean.close() if (outFileGeodesics != None): outFileGeodesics.close() if (outFileHybrid != None): outFileHybrid.close() return #Close the file descriptors if (outFileEuclidean != None): outFileEuclidean.close() if (outFileGeodesics != None): outFileGeodesics.close() if (outFileHybrid != None): outFileHybrid.close() #Close the progress bar cmds.progressBar(gMainProgressBar, edit=1, ep=1) #Print the time results print("Time for calculating Euclidean dist. matrix: " + str(euclideanTime)) print("Time for calculating Geodesic dist. matrix: " + str(geodesicTime)) print("Time for calculating Hybrid dist. matrix: " + str(hybridTime))
def startRender(self): # Will also return time taken from start to finish in minutes, to 2 decimal places frameDataLog = [] #Stores a comprehensive list of each frame as it is rendered with a timestamp for initialisation frameDataStringLog = []#Stores a comprehensive string list of each frame as it is rendered with a timestamp for initialisation, for using in the render log frameDataLogTemp = [] #Stores frame information temporarily #ints framesRendered = 0 #Stores current amount of frames rendered for determining overall progress percentComplete = 0 #Stores the percentage to completion, also used to determine if render completed successfully #Strings frameDataString = "null" #Stores frame information renderStartTimeStamp = ma.date(t=True) #Stores the time in which the render function was first called #floats renderTimeStamp = 0.0 #Stores the time in which the render completed or was forcably stopped #startTimer renderTimer = ma.timer(startTimer = True) ###WINDOW CREATION #createWindow to allow interupting of progress. ma.progressWindow(isInterruptable=1, t="aBRS_RENDER", status = "Rendering...") #begin rendering frames for frame in self._frameList: ##Allow interuption to stop the render if ma.progressWindow(query=True, isCancelled = True): print "Render Cancelled by User." break #set current frame ma.currentTime(frame) #store frame data and timestamp for initialisation then print. frameDataLogTemp = [self._getCam(frame), frame, ma.date(t=True)] # A nice list storing frame information (incase of storage) frameDataString = "Camera: %s, Frame: %s, TimeStarted: %s" % (str(frameDataLogTemp[0]), str(frameDataLogTemp[1]), str(frameDataLogTemp[2])) #Store data in lists frameDataLog.append(frameDataLogTemp) frameDataStringLog.append(frameDataString) #print current string data to viewport print frameDataString """RENDER OCCURS HERE""" #try as maya 2018 arnold render returns a runtime error when interuption is detected self.tryArnoldRender(frame) #Add to frames rendered framesRendered += 1 #Get percentage according to rendered vs total frames percentComplete = self._renderPercentComplete(framesRendered) #Update the progress window ma.progressWindow( edit=True, progress=percentComplete ) '''Rendering has finished - Closing procedures''' #End timer renderTimer = ma.timer(endTimer = True) #End Progress window ma.progressWindow(endProgress=1) #Store total render time renderTimeStamp = str(round(renderTimer/60, 2)) #record values for log file self._lS_frameDataSTR = frameDataStringLog self._lS_frameData = frameDataLog self._lS_renderStartTime = renderStartTimeStamp self._lS_renderEndTime = ma.date(t=True) self._lS_renderTimeInMinutes = renderTimeStamp self._lS_renderCompletionSuccessful = percentComplete == 100 self.storeRenderData() #Generate log self.generateRenderLog() return "Render Time in Minutes: " + str(renderTimeStamp)
def main(firstFrame, lastFrame, steps, meshName, matrixFolderPath, stiffnessValues, RBFTechnique): #Check if the mesh exists in the DAG if not cmds.objExists(meshName): print("Mesh name does not match any object") return #Check that the RBF technique is valid if (RBFTechnique < 0 or RBFTechnique > 2): print("The RBF Technique code is not valid") return #Try to open the distance matrix files matrixFileEuclidean = None matrixFileGeodesics = None matrixFileHybrid = None if (RBFTechnique == 0): try: matrixFileEuclidean = open(matrixFolderPath + "/eucMatrix.mtx", 'r') except IOError: confirm = cmds.confirmDialog( title='Matrix no found', message= 'Could not find the Euclidean matrix file (eucmatrix.mtx) in the given path, do you want to proceed with the calculations without matrix? (not recommended for dense meshes)', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if (confirm == "No"): return if (RBFTechnique == 1): try: matrixFileGeodesics = open(matrixFolderPath + "/geoMatrix.mtx", 'r') except IOError: confirm = cmds.confirmDialog( title='Matrix no found', message= 'Could not find the Geodesics matrix file (geomatrix.mtx) in the given path, do you want to proceed with the calculations without matrix? (not recommended for dense meshes)', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if (confirm == "No"): return if (RBFTechnique == 2): try: matrixFileHybrid = open(matrixFolderPath + "/hybMatrix.mtx", 'r') except IOError: confirm = cmds.confirmDialog( title='Matrix no found', message= 'Could not find the Hybrid matrix file (hybmatrix.mtx) in the given path, do you want to proceed with the calculations without matrix? (not recommended for dense meshes)', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if (confirm == "No"): return #Take the markers arranged in groups markersSelection = sorted(cmds.listRelatives("TopMarkers")) + sorted( cmds.listRelatives("TopMiddleMarkers")) + sorted( cmds.listRelatives("MiddleMarkers")) + sorted( cmds.listRelatives("MiddleBottomMarkers")) + sorted( cmds.listRelatives("BottomMarkers")) #Take the vertices of the geodesic areas (for hybrid) geodesicVertices = None if (RBFTechnique == 2): geodesicVertices = cmds.ls( cmds.sets("MouthArea", q=True), flatten=True) + cmds.ls( cmds.sets("REyeArea", q=True), flatten=True) + cmds.ls( cmds.sets("LEyeArea", q=True), flatten=True) #Calculate the animation of the mesh cmds.undoInfo(state=False) cmds.timer(s=True) mel.eval("paneLayout -e -manage false $gMainPane") animateMesh(meshName, markersSelection, firstFrame, lastFrame, steps, stiffnessValues, RBFTechnique, matrixFileEuclidean, matrixFileGeodesics, matrixFileHybrid, geodesicVertices) mel.eval("paneLayout -e -manage true $gMainPane") totalTime = cmds.timer(e=True) cmds.undoInfo(state=True) #Close the file descriptors if (matrixFileEuclidean != None): matrixFileEuclidean.close() if (matrixFileGeodesics != None): matrixFileGeodesics.close() if (matrixFileHybrid != None): matrixFileHybrid.close() #Print total time print("TOTAL ---------------------------------------") print("Total running time: " + str(totalTime) + "s") print("---------------------------------------------") print("")
def animateMesh(mesh, markersList, firstFrame, lastFrame, steps, stiffnessValues, RBFTechnique, matrixFileEuclidean, matrixFileGeodesics, matrixFileHybrid, geodesicVertices): #File flags eucMatrixExists = (matrixFileEuclidean != None) geoMatrixExists = (matrixFileGeodesics != None) hybMatrixExists = (matrixFileHybrid != None) #Start progress bar progressAmount = 0 gMainProgressBar = mel.eval('$tmp = $gMainProgressBar') cmds.progressBar(gMainProgressBar, edit=True, progress=progressAmount, status='Initializing calculations...', isInterruptable=True, bp=True) meshFullPath = cmds.ls(mesh, long=True)[0] nVert = cmds.polyEvaluate(mesh, v=True) RBFTime = 0 #Set the default position of the vertices in all the frames print("Setting default position in all frames") for x in range(firstFrame, lastFrame + 1, steps): cmds.currentTime(x) for i in range(nVert): cmds.select(mesh + ".vtx[" + str(i) + "]", r=True) cmds.setKeyframe(meshFullPath + "|" + mesh + "Shape.pnts[" + str(i) + "]", breakdown=0) cmds.setKeyframe(mesh + ".vtx[" + str(i) + "]", breakdown=0, hierarchy="none", controlPoints=0, shape=0) #Progress control if cmds.progressBar(gMainProgressBar, q=True, ic=True): cmds.progressBar(gMainProgressBar, edit=1, ep=1) return #Calculate the vertices matching the markers at frame 0 print("Calculating corresponding vertex for each marker...") #Pre-calculation timer starts cmds.timer(s=True, name="precalcTimer") cmds.currentTime(0) vertexMarkers = matchMarkersWithMesh(markersList, mesh) #Take the position reference from frame 0 print("Calculating initial positions...") markersInitialPos = [] for i in range(len(markersList)): markersInitialPos.append(getObjectPoint(markersList[i])) print("Filling distance matrix...") #Create and fill the distance matrix for Euclidean distMatrixEuc = [] if (RBFTechnique == 0): for i in range(nVert): distMatrixEuc.append([]) for j in range(nVert): distMatrixEuc[i].append(0) if (eucMatrixExists): for v in range(nVert): for c in range(len(markersList)): cmds.timer(s=True, name="RBFTimer") dist = float(matrixFileEuclidean.readline()) distMatrixEuc[v][vertexMarkers[c]] = dist distMatrixEuc[vertexMarkers[c]][v] = dist RBFTime += cmds.timer(e=True, name="RBFTimer") else: for v in range(nVert): for c in range(len(markersList)): vPos1 = cmds.pointPosition(mesh + ".vtx[" + str(v) + "]") vPos2 = cmds.pointPosition(mesh + ".vtx[" + str(vertexMarkers[c]) + "]") cmds.timer(s=True, name="RBFTimer") dist = getEuclideanDistance(vPos1, vPos2) distMatrixEuc[v][vertexMarkers[c]] = dist distMatrixEuc[vertexMarkers[c]][v] = dist RBFTime += cmds.timer(e=True, name="RBFTimer") #Create and fill the distance matrix for Geodesics distMatrixGeo = [] if (RBFTechnique == 1): for i in range(nVert): distMatrixGeo.append([]) for j in range(nVert): distMatrixGeo[i].append(0) if (geoMatrixExists): for v in range(nVert): for c in range(len(vertexMarkers)): cmds.timer(s=True, name="RBFTimer") dist = float(matrixFileGeodesics.readline()) distMatrixGeo[v][vertexMarkers[c]] = dist distMatrixGeo[vertexMarkers[c]][v] = dist RBFTime += cmds.timer(e=True, name="RBFTimer") else: for v in range(nVert): for c in range(len(markersList)): cmds.timer(s=True, name="RBFTimer") dist = getGeodesicDistancev2(mesh, v, vertexMarkers[c]) distMatrixGeo[v][vertexMarkers[c]] = dist distMatrixGeo[vertexMarkers[c]][v] = dist RBFTime += cmds.timer(e=True, name="RBFTimer") print("Calculating weight matrix...") #Create and fill the distance matrix for Hybrid distMatrixHybrid = [] if (RBFTechnique == 2): for i in range(nVert): distMatrixHybrid.append([]) for j in range(nVert): distMatrixHybrid[i].append(0) if (hybMatrixExists): for v in range(nVert): for c in range(len(vertexMarkers)): cmds.timer(s=True, name="RBFTimer") dist = float(matrixFileHybrid.readline()) distMatrixHybrid[v][vertexMarkers[c]] = dist distMatrixHybrid[vertexMarkers[c]][v] = dist RBFTime += cmds.timer(e=True, name="RBFTimer") else: for v in range(nVert): averWeight = 1 vName = mesh + ".vtx[" + str(v) + "]" vPoint = cmds.pointPosition(vName) if (not (vName in geodesicVertices)): gdist = sys.float_info.max for j in range(len(geodesicVertices)): auxDist = getEuclideanDistance( vPoint, cmds.pointPosition(geodesicVertices[j])) if (auxDist < gdist): gdist = auxDist averWeight = calculateGaussianRBF(gdist, 2) for c in range(len(markersList)): cmds.timer(s=True, name="RBFTimer") dist = 0 if (averWeight < 0.6): dist = getEuclideanDistance(vPoint, markersInitialPos[c]) else: dist = getGeodesicDistancev2( mesh, v, vertexMarkers[c] ) * averWeight + getEuclideanDistance( vPoint, markersInitialPos[c]) * (1 - averWeight) distMatrixHybrid[v][vertexMarkers[c]] = dist distMatrixHybrid[vertexMarkers[c]][v] = dist RBFTime += cmds.timer(e=True, name="RBFTimer") #Print total RBF Time RBFPrecTime = RBFTime print("Total RBF Time in distance calculations: " + str(RBFPrecTime) + " s") #Progress control progressStep = float(90) / (float(1 + lastFrame - firstFrame) / float(steps)) progressAmount += 5 if cmds.progressBar(gMainProgressBar, q=True, ic=True): cmds.progressBar(gMainProgressBar, edit=1, ep=1) return #End pre-calculation timer precalcTime = cmds.timer(e=True, name="precalcTimer") #Initialize new timers frameTime = 0 averageFrameTime = 0 keyframingTime = 0 averageKeyframingTime = 0 iterations = 0 for x in range(firstFrame, lastFrame + 1, steps): iterations += 1 #Frame timer starts cmds.timer(s=True, name="frameTimer") #Progress control cmds.progressBar(gMainProgressBar, edit=True, status="Calculating mesh deformation for frame " + str(x), progress=progressAmount) print("Calculating deformations for frame " + str(x)) #Calculate the displacement of the control points cmds.currentTime(x) markersDispPos = [] markersDisp = [] for i in range(len(markersList)): markersDispPos.append(getObjectPoint(markersList[i])) markersDisp.append([ markersDispPos[i][0] - markersInitialPos[i][0], markersDispPos[i][1] - markersInitialPos[i][1], markersDispPos[i][2] - markersInitialPos[i][2] ]) #Calculate the displacement of all the vertices by the RBF method #Initialize rbf matrix rbfMatrix = [] for i in range(len(markersList)): rbfMatrix.append([]) for j in range(len(markersList)): rbfMatrix[i].append(0) #Calculate the rbf matrix print(" Calculating RBF matrix... ") for i in range(0, len(markersList)): for j in range(i, len(markersList)): dist = 0 eucDist = 0 geoDist = 0 hybDist = 0 #Euclidean calculations if (RBFTechnique == 0): dist = distMatrixEuc[vertexMarkers[i]][vertexMarkers[j]] #Geodesics calculations if (RBFTechnique == 1): dist = distMatrixGeo[vertexMarkers[i]][vertexMarkers[j]] #Hybrid calculations if (RBFTechnique == 2): dist = distMatrixHybrid[vertexMarkers[i]][vertexMarkers[j]] cmds.timer(s=True, name="RBFTimer") rbf = calculateGaussianRBF(dist, stiffnessValues[i]) rbfMatrix[i][j] = rbf rbfMatrix[j][i] = rbf RBFTime += cmds.timer(e=True, name="RBFTimer") #Progress control if cmds.progressBar(gMainProgressBar, q=True, ic=True): cmds.progressBar(gMainProgressBar, edit=1, ep=1) return #Calculate the weight of each control point print(" Calculating weight of control points...") weights = [] for i in range(len(markersList)): weights.append([0, 0, 0]) cmds.timer(s=True, name="RBFTimer") for j in range(len(markersList)): weights[i][0] += rbfMatrix[i][j] weights[i][1] += rbfMatrix[i][j] weights[i][2] += rbfMatrix[i][j] weights[i][0] = markersDisp[i][0] / weights[i][0] weights[i][1] = markersDisp[i][1] / weights[i][1] weights[i][2] = markersDisp[i][2] / weights[i][2] RBFTime += cmds.timer(e=True, name="RBFTimer") #Calculate the displacement of the vertices of the mesh print(" Calculating displacement of the vertices of the mesh...") vDisp = [] for i in range(nVert): vDisp.append([0, 0, 0]) vName = mesh + ".vtx[" + str(i) + "]" vPos = cmds.pointPosition(vName) for c in range(len(markersList)): dist = 0 #Euclidean calculations if (RBFTechnique == 0): dist = distMatrixEuc[i][vertexMarkers[c]] #Geodesics calculations if (RBFTechnique == 1): dist = distMatrixGeo[i][vertexMarkers[c]] #Hybrid calculations if (RBFTechnique == 2): dist = distMatrixHybrid[i][vertexMarkers[c]] cmds.timer(s=True, name="RBFTimer") rbf = calculateGaussianRBF(dist, stiffnessValues[c]) vDisp[i][0] += weights[c][0] * rbf vDisp[i][1] += weights[c][1] * rbf vDisp[i][2] += weights[c][2] * rbf RBFTime += cmds.timer(e=True, name="RBFTimer") #Progress control if cmds.progressBar(gMainProgressBar, q=True, ic=True): cmds.progressBar(gMainProgressBar, edit=1, ep=1) return # Apply the calculated displacement to all the vertices print(" Applying displacements...") for j in range(nVert): #Keyframing timer starts cmds.timer(s=True, name="keyframingTimer") #Displace the vertex cmds.select(mesh + ".vtx[" + str(j) + "]", r=True) cmds.move(vDisp[j][0], vDisp[j][1], vDisp[j][2], r=True, ls=True, wd=True) #Set a key for the vertex cmds.setKeyframe(meshFullPath + "|" + mesh + "Shape.pnts[" + str(j) + "]", breakdown=0) cmds.setKeyframe(mesh + ".vtx[" + str(j) + "]", breakdown=0, hierarchy="none", controlPoints=0, shape=0) #Keyframing timer ends keyframingTime += cmds.timer(e=True, name="keyframingTimer") #Progress control progressAmount += progressStep if cmds.progressBar(gMainProgressBar, q=True, ic=True): cmds.progressBar(gMainProgressBar, edit=1, ep=1) return #Frame timer ends frameTime += cmds.timer(e=True, name="frameTimer") #Print times averageKeyframingTime = float(keyframingTime) / float(iterations) averageFrameTime = float(frameTime) / float(iterations) RBFTimePerFrame = float(RBFTime - RBFPrecTime) / float(iterations) print("") print("ALGORITHM: ----------------------------------") print("Pre-calculation time: " + str(precalcTime) + " s") print("Frames calculated: " + str(iterations) + " frames") print("Average frame time: " + str(averageFrameTime) + " s/frame") print(" Average keyframing time: " + str(averageKeyframingTime) + " s/frame") print(" Average algorithm time: " + str(averageFrameTime - averageKeyframingTime) + " s/frame") print("---------------------------------------------") print("") print("RBF CALCULATIONS: ---------------------------") print("RBF total calculation time: " + str(RBFTime) + " s") print(" RBF dist. calculation time: " + str(RBFPrecTime) + " s") print(" RBF calculation time per frame: " + str(RBFTimePerFrame) + " s/frame") print("---------------------------------------------") print("") #End progress bar cmds.progressBar(gMainProgressBar, edit=1, ep=1) return