Python Tools — Session 6A
Return Values, Area Calculations, and Node Searching
2020.02.11 — Session 6A
Session Navigation
Overview
This session covers how to return calculated values from functions, using face area queries to compute total surface area of meshes, iterating over transform nodes to find objects by name, and exporting selected nodes to files. These are essential patterns for building reusable Maya tools.
Key Concepts
- Return Values — Functions can calculate and return results for use elsewhere in your code
- Face Area Queries — Iterating over mesh faces and summing their individual areas to get total surface area
- Node Searching — Looping through transform nodes and using string matching to find objects by name
- Export Operations — Selecting nodes programmatically and exporting them to external file formats
- Selection Management — Saving and restoring the user's selection state before and after operations
Code
sessions_6a_code_commented.py
"""
#############################################################################
filename session_6a_code_commented.py
author Matt Osbond
dP email m.osbond@digipen.edu
course CS115
Brief Description:
Session 6A - Tuesday Feb 11th
#############################################################################
"""
"""
Returning a calculated value from a function
"""
import pymel.core as pm
def get_area(mesh_node):
"""Returns the surface area of an object by iterating through each face and adding up as we go
"""
# Create a variable to add to - initialize it to zero
area = 0.0
# Iterate over each face
for face in mesh_node.faces:
# Add the area of the face to the total
# area += current_face is shorthand for area = area + current_face
area += face.getArea()
# Return the total area of the face
return area
# This line does 3 things
# 1 - the "pm.ls(selection=True)[0])" part grabs the first selected object
# 2 - the "get_area(..)" part calls the function, using the selected object
# 3 - finally we print the returned result
print get_area(pm.ls(selection=True)[0])
# Note - there is a faster way to this (below)
# We are sinplying using this method to show the process of return a calculated value from a function
print pm.ls(selection=True)[0].area()
################################################################
################################################################
import pymel.core as pm
def get_nodes_by_name(find_str):
"""Returns all nodes whose name contains the given string
"""
result = list()
for node in pm.ls(type='transform'):
print node, node.nodeType()
if find_str.lower() in node.name().lower():
result.append(node)
return result
def save_nodes(find_str, target_file):
original_selection = pm.ls(selection=True)
named_nodes = get_nodes_by_name(find_str)
print (named_nodes )
pm.select(named_nodes)
pm.exportSelected(target_file, force=True)
pm.select(original_selection)
save_nodes('ReadyToExport', r'C:\temp\export.fbx')