Module Mesh :: Class Mesh

Class Mesh

source code

The Mesh Data object

This object gives access to mesh data in Blender.


Note: the verts, edges and faces attributes are implemented as sequences. The operator[] and len() are defined for these sequences. You cannot assign to an item in the sequence, but you can assign to most of the attributes of individual items.

Instance Methods
 
getFromObject(object, cage=0, render=0)
Replace the mesh's existing data with the raw mesh data from a Blender Object.
source code
 
calcNormals()
Recalculates the vertex normals using face data.
source code
 
pointInside(point, selected_only=False) source code
 
getTangents()
Calculates tangents for this mesh, returning a list of tuples, each with 3 or 4 tangent vectors, these are alligned with the meshes faces.
source code
 
transform(matrix, recalc_normals=False, selected_only=False)
Transforms the mesh by the specified 4x4 matrix (such as returned by Object.Object.getMatrix).
source code
 
vertexShade(object)
Colors vertices based on the current lighting setup, like when there are no vertex colors and no textured faces and a user enters Vertex Paint Mode in Blender (only lamps in visible layers account).
source code
 
update(key=None)
Update display lists after changes to mesh.
source code
int, None or list
findEdges(edges)
Quickly search for the location of an edges.
source code
 
addVertGroup(group)
Add a named and empty vertex (deform) group to the object this mesh is linked to.
source code
 
removeVertGroup(group)
Remove a named vertex (deform) group from the object linked to this mesh.
source code
 
assignVertsToGroup(group, vertList, weight, assignmode)
Adds an array (a Python list) of vertex points to a named vertex group associated with a mesh.
source code
 
removeVertsFromGroup(group, vertList=None)
Remove a list of vertices from the given group.
source code
 
getVertsFromGroup(group, weightsFlag=0, vertList=None)
Return a list of vertex indices associated with the passed group.
source code
 
renameVertGroup(groupName, newName)
Renames a vertex group.
source code
list of strings
getVertGroupNames()
Return a list of all vertex group names.
source code
list of strings
getUVLayerNames()
Return a list of all UV layer names
source code
list of strings
getColorLayerNames()
Return a list of all color layer names
source code
list of lists
getVertexInfluences(index)
Get the bone influences for a specific vertex.
source code
bool
removeAllKeys()
Remove all mesh keys stored in this mesh.
source code
 
insertKey(frame=None, type='relative')
Insert a mesh key at the given frame.
source code
 
addUVLayer(name)
Adds a new UV/Image layer to this mesh, it will always be the last layer but not made active.
source code
 
addColorLayer(name)
Adds a new Vertex Color layer to this mesh, it will always be the last layer but not made active.
source code
 
addMultiresLevel(levels=1, type='catmull-clark')
Adds multires levels to this mesh.
source code
 
removeUVLayer(name)
Removes the active UV/Image layer.
source code
 
removeColorLayer(name)
Removes the active Vertex Color layer.
source code
 
renameUVLayer(name, newname)
Renames the UV layer called name to newname.
source code
 
renameColorLayer(name, newname)
Renames the color layer called name to newname.
source code
 
smooth()
Flattens angle of selected faces.
source code
 
flipNormals()
Toggles the direction of selected face's normals.
source code
 
toSphere()
Moves selected vertices outward in a spherical shape.
source code
 
fill()
Scan fill a closed selected edge loop.
source code
 
triangleToQuad()
Convert selected triangles to quads.
source code
 
quadToTriangle(mode=0)
Convert selected quads to triangles.
source code
 
subdivide(beauty=0)
Subdivide selected edges in a mesh.
source code
int
remDoubles(limit)
Removes duplicates from selected vertices.
source code
 
recalcNormals(direction=0)
Recalculates inside or outside normals for selected faces.
source code
Mesh
__copy__()
Make a copy of this mesh
source code
Instance Variables
string activeColorLayer
The mesh's active Vertex Color layer.
int activeFace
Index of the mesh's active face in UV Face Select and Paint modes.
string or None activeGroup
The mesh's active vertex group.
string activeUVLayer
The mesh's active UV/Image layer.
int degr
The max angle for auto smoothing in [1,80].
sequence of MEdges edges
The mesh's edges.
bool faceUV
The mesh contains UV-mapped textured faces.
sequence of MFaces faces
The mesh's faces.
bool fakeUser
When set to True, this datablock wont be removed, even if nothing is using it.
boolean hide
Sets hidden status for all vertices, edges and faces in the mesh (write only).
Key or None key
The Key object containing the keyframes for this mesh, if any.
string or None lib
path to the blend file this datablock is stored in (readonly).
list of Materials materials
The mesh's materials.
  maxSmoothAngle
Same as degr.
int mode
The mesh's mode bitfield.
bool multires
The mesh has multires data, set True to add multires data.
int multiresDrawLevel
The multires level to display in the 3dview in [1 - multiresLevelCount].
int multiresEdgeLevel
The multires level edge display in the 3dview [1 - multiresLevelCount].
int multiresLevelCount
The mesh has multires data.
int multiresPinLevel
The multires pin level, used for applying modifiers [1 - multiresLevelCount].
int multiresRenderLevel
The multires level to render [1 - multiresLevelCount].
string name
unique name within each blend file.
IDGroup properties
Returns an IDGroup reference to this datablocks's ID Properties.
string renderColorLayer
The mesh's rendered Vertex Color layer.
string renderUVLayer
The mesh's rendered UV/Image layer.
boolean sel
Sets selection status for all vertices, edges and faces in the mesh (write only).
list of 2 ints subDivLevels
The [display, rendering] subdivision levels in [1, 6].
bool tag
A temporary tag that to flag data as being used within a loop.
Mesh or None texMesh
The mesh's texMesh setting, used so coordinates from another mesh can be used for rendering textures.
int users
The number of users this datablock has.
bool vertexColors
The mesh contains vertex colors.
bool vertexUV
The mesh contains "sticky" per-vertex UV coordinates.
sequence of MVerts verts
The mesh's vertices.
Method Details

getFromObject(object, cage=0, render=0)

source code 
Replace the mesh's existing data with the raw mesh data from a Blender Object. This method supports all the geometry based objects (mesh, text, curve, surface, and meta). If the object has modifiers, they will be applied before to the object before extracting the vertex data unless the cage parameter is 1.
Parameters:
  • object (blender object or string) - The Blender object or its name, which contains the geometry data.
  • cage (int) - determines whether the original vertices or derived vertices
  • render (int) - determines whether the render setting for modifiers will be used or not. (for objects with modifiers) are used. The default is derived vertices.
Notes:
  • The mesh coordinates are in local space, not the world space of its object. For world space vertex coordinates, each vertex location must be multiplied by the object's 4x4 transform matrix (see transform).
  • The objects materials will not be copied into the existing mesh, however the face material indices will match the material list of the original data.

pointInside(point, selected_only=False)

source code 
Parameters:
  • point (vector) - Test if this point is inside the mesh
  • selected_only (bool) - if True or 1, only the selected faces are taken into account. Returns true if vector is inside the mesh.
Notes:
  • Only returns a valid result for mesh data that has no holes.
  • Bubbles in the mesh work as expect.

getTangents()

source code 

Calculates tangents for this mesh, returning a list of tuples, each with 3 or 4 tangent vectors, these are alligned with the meshes faces.

Example:
       # Display the tangents as edges over a the active mesh object
       from Blender import *
       sce = Scene.GetCurrent()
       ob = sce.objects.active
       
       me = ob.getData(mesh=1)
       ts = me.getTangents()
       me_disp = Mesh.New()
       
       verts = []
       edges = []
       for i, f in enumerate(me.faces):
               ft = ts[i]
               for j, v in enumerate(f):
                       tan = ft[j]
                       print tan
                       co = v.co
                       
                       verts.append(co)
                       verts.append(co+tan)
                       
                       i = len(verts)
                       edges.append((i-1, i-2))
       
       me_disp.verts.extend( verts )
       me_disp.edges.extend( edges )
       
       sce.objects.new( me_disp )

Note: The tangents are computed using the active UV layer, if there are no UV layers, orco coords are used.

transform(matrix, recalc_normals=False, selected_only=False)

source code 

Transforms the mesh by the specified 4x4 matrix (such as returned by Object.Object.getMatrix). The matrix should be invertible. Ideal usage for this is exporting to an external file where global vertex locations are required for each object. Sometimes external renderers or file formats do not use vertex normals. In this case, you can skip transforming the vertex normals by leaving the optional parameter recalc_normals as False or 0 (the default value).

Example:
       # This script outputs deformed meshes worldspace vertex locations
       # for a selected object without changing the object
       import Blender
       from Blender import Mesh, Object
       
       ob = Object.GetSelected()[0] # Get the first selected object
       me = Mesh.New()              # Create a new mesh
       me.getFromObject(ob.name)    # Get the object's mesh data
       verts = me.verts[:]          # Save a copy of the vertices
       me.transform(ob.matrix)      # Convert verts to world space
       for v in me.verts:
               print 'worldspace vert', v.co
       me.verts = verts             # Restore the original verts
Parameters:
  • matrix (Py_Matrix) - 4x4 Matrix which can contain location, scale and rotation.
  • recalc_normals (int) - if True or 1, also transform vertex normals.
  • selected_only (bool) - if True or 1, only the selected verts will be transformed.

Warning: unlike NMesh.transform(), this method will immediately modify the mesh data when it is used. If you transform the mesh using the object's matrix to get the vertices' world positions, the result will be a "double transform". To avoid this you either need to set the object's matrix to the identity matrix, perform the inverse transform after outputting the transformed vertices, or make a copy of the vertices prior to using this method and restore them after outputting the transformed vertices (as shown in the example).

vertexShade(object)

source code 
Colors vertices based on the current lighting setup, like when there are no vertex colors and no textured faces and a user enters Vertex Paint Mode in Blender (only lamps in visible layers account). An exception is thrown if called while in EditMode.
Parameters:
  • object (Object) - The Blender Object linked to the mesh.

update(key=None)

source code 
Update display lists after changes to mesh. Note: with changes taking place for using a directed acyclic graph (DAG) for scene and object updating, this method may be only temporary and may be removed in future releases.
Parameters:

Warning: Since Blender 2.42 this function has changed; now it won't recalculate vertex normals (seen when faces are smooth). See Mesh.calcNormals().

findEdges(edges)

source code 
Quickly search for the location of an edges.
Parameters:
  • edges (sequence(s) of ints or MVerts) - can be tuples of MVerts or integer indexes (note: will not work with PVerts) or a sequence (list or tuple) containing two or more sequences.
Returns: int, None or list
if an edge is found, its index is returned; otherwise None is returned. If a sequence of edges is passed, a list is returned.

addVertGroup(group)

source code 
Add a named and empty vertex (deform) group to the object this mesh is linked to. The mesh must first be linked to an object (with object.link() or object.getData() ) so the method knows which object to update. This is because vertex groups in Blender are stored in the object -- not in the mesh, which may be linked to more than one object.
Parameters:
  • group (string) - the name for the new group.

removeVertGroup(group)

source code 
Remove a named vertex (deform) group from the object linked to this mesh. All vertices assigned to the group will be removed (just from the group, not deleted from the mesh), if any. If this mesh was newly created, it must first be linked to an object (read the comment in addVertGroup for more info).
Parameters:
  • group (string) - the name of a vertex group.

assignVertsToGroup(group, vertList, weight, assignmode)

source code 

Adds an array (a Python list) of vertex points to a named vertex group associated with a mesh. The vertex list is a list of vertex indices from the mesh. You should assign vertex points to groups only when the mesh has all its vertex points added to it and is already linked to an object.

Example: The example here adds a new set of vertex indices to a sphere primitive:
       import Blender
       sphere = Blender.Object.Get('Sphere')
       replace = Blender.Mesh.AssignModes.REPLACE
       mesh = sphere.getData(mesh=True)
       mesh.addVertGroup('firstGroup')
       vertList = []
       for x in range(300):
               if x % 3 == 0:
                       vertList.append(x)
       mesh.assignVertsToGroup('firstGroup', vertList, 0.5, replace)
Parameters:
  • group (string) - the name of the group.
  • vertList (list of ints) - a list of vertex indices.
  • weight (float) - the deform weight for (which means: the amount of influence the group has over) the given vertices. It should be in the range [0.0, 1.0]. If weight <= 0, the given vertices are removed from the group. If weight > 1, it is clamped.
  • assignmode (module constant) - Three choices: REPLACE, ADD or SUBTRACT. See AssignModes for a complete description.

removeVertsFromGroup(group, vertList=None)

source code 
Remove a list of vertices from the given group. If this mesh was newly created, it must first be linked to an object (check addVertGroup).
Parameters:
  • group (string) - the name of a vertex group
  • vertList (list of ints) - a list of vertex indices to be removed from group. If None, all vertices are removed -- the group is emptied.

getVertsFromGroup(group, weightsFlag=0, vertList=None)

source code 

Return a list of vertex indices associated with the passed group. This method can be used to test whether a vertex index is part of a group and if so, what its weight is.

Example: Append this to the example from assignVertsToGroup:
       # ...
       print "Vertex indices from group %s :" % groupName
       print mesh.getVertsFromGroup('firstGroup')
       print "Again, with weights:"
       print mesh.getVertsFromGroup('firstGroup',1)
       print "Again, with weights and restricted to the given indices:"
       print mesh.getVertsFromGroup('firstGroup',1,[1,2,3,4,5,6])     
Parameters:
  • group (string) - the group name.
  • weightsFlag (bool) - if 1, each item in the list returned contains a tuple pair (index, weight), the weight is a float between 0.0 and 1.0.
  • vertList (list of ints) - if given, only those vertex points that are both in the list and group passed in are returned.

renameVertGroup(groupName, newName)

source code 
Renames a vertex group.
Parameters:
  • groupName (string) - the vertex group name to be renamed.
  • newName (string) - the name to replace the old name.

getVertGroupNames()

source code 
Return a list of all vertex group names.
Returns: list of strings
returns a list of strings representing all vertex group associated with the mesh's object

getUVLayerNames()

source code 
Return a list of all UV layer names
Returns: list of strings
returns a list of strings representing all UV layers associated with the mesh's object

getColorLayerNames()

source code 
Return a list of all color layer names
Returns: list of strings
returns a list of strings representing all color layers associated with the mesh's object

getVertexInfluences(index)

source code 
Get the bone influences for a specific vertex.
Parameters:
  • index (int) - The index of a vertex.
Returns: list of lists
List of pairs [name, weight], where name is the bone name (string) and weight is a float value.

removeAllKeys()

source code 
Remove all mesh keys stored in this mesh.
Returns: bool
True if successful or False if the Mesh has no keys.

insertKey(frame=None, type='relative')

source code 
Insert a mesh key at the given frame.
Parameters:
  • frame (int) - The Scene frame where the mesh key should be inserted. If None or the arg is not given, the current frame is used.
  • type (string) - The mesh key type: 'relative' or 'absolute'. This is only relevant on meshes with no keys.
Warnings:
  • This and removeAllKeys were included in this release only to make accessing vertex keys possible, but may not be a proper solution and may be substituted by something better later. For example, it seems that 'frame' should be kept in the range [1, 100] (the curves can be manually tweaked in the Ipo Curve Editor window in Blender itself later).
  • Will throw an error if the mesh has multires. use multires to check.

addUVLayer(name)

source code 
Adds a new UV/Image layer to this mesh, it will always be the last layer but not made active.
Parameters:
  • name (string) - The name of the new UV layer, 31 characters max.

addColorLayer(name)

source code 
Adds a new Vertex Color layer to this mesh, it will always be the last layer but not made active.
Parameters:
  • name (string) - The name of the new Color layer, 31 characters max.

addMultiresLevel(levels=1, type='catmull-clark')

source code 
Adds multires levels to this mesh.
Parameters:
  • levels (int) - The number of levels to add
  • type (string) - The type of multires level, 'catmull-clark' or 'simple'.

removeUVLayer(name)

source code 
Removes the active UV/Image layer.
Parameters:
  • name (string) - The name of the UV layer to remove.

removeColorLayer(name)

source code 
Removes the active Vertex Color layer.
Parameters:
  • name (string) - The name of the Color layer to remove.

renameUVLayer(name, newname)

source code 
Renames the UV layer called name to newname.
Parameters:
  • name (string) - The UV layer to rename.
  • newname (string) - The new name of the UV layer, will be made unique.

renameColorLayer(name, newname)

source code 
Renames the color layer called name to newname.
Parameters:
  • name (string) - The Color layer to rename.
  • newname (string) - The new name of the Color layer, will be made unique.

smooth()

source code 
Flattens angle of selected faces. Experimental mesh tool. An exception is thrown if called while in EditMode.

flipNormals()

source code 
Toggles the direction of selected face's normals. Experimental mesh tool. An exception is thrown if called while in EditMode.

toSphere()

source code 
Moves selected vertices outward in a spherical shape. Experimental mesh tool. An exception is thrown if called while in EditMode.

fill()

source code 
Scan fill a closed selected edge loop. Experimental mesh tool. An exception is thrown if called while in EditMode.

triangleToQuad()

source code 
Convert selected triangles to quads. Experimental mesh tool. An exception is thrown if called while in EditMode.

quadToTriangle(mode=0)

source code 
Convert selected quads to triangles. Experimental mesh tool. An exception is thrown if called while in EditMode.
Parameters:
  • mode (int) - specifies whether a to add the new edge between the closest (=0) or farthest(=1) vertices.

subdivide(beauty=0)

source code 
Subdivide selected edges in a mesh. Experimental mesh tool. An exception is thrown if called while in EditMode.
Parameters:
  • beauty (int) - specifies whether a "beauty" subdivide should be enabled (disabled is default). Value must be in the range [0,1].

remDoubles(limit)

source code 
Removes duplicates from selected vertices. Experimental mesh tool. An exception is thrown if called while in EditMode.
Parameters:
  • limit (float) - specifies the maximum distance considered for vertices to be "doubles". Value is clamped to the range [0.0,1.0].
Returns: int
the number of vertices deleted

recalcNormals(direction=0)

source code 
Recalculates inside or outside normals for selected faces. Experimental mesh tool. An exception is thrown if called while in EditMode.
Parameters:
  • direction (int) - specifies outward (0) or inward (1) normals. Outward is the default. Value must be in the range [0,1].

__copy__()

source code 
Make a copy of this mesh
Returns: Mesh
a copy of this mesh

Instance Variable Details

activeColorLayer

The mesh's active Vertex Color layer. None if there is no UV/Image layers.

Note: After setting this value, call update so the result can be seen the the 3d view.
Type:
string

activeFace

Index of the mesh's active face in UV Face Select and Paint modes. Only one face can be active at a time. Note that this is independent of the selected faces in Face Select and Edit modes. Will throw an exception if the mesh does not have UV faces; use faceUV to test.
Type:
int

activeGroup

The mesh's active vertex group. The mesh must be linked to an object (read the comment in addVertGroup for more info).
Type:
string or None

activeUVLayer

The mesh's active UV/Image layer. None if there is no UV/Image layers.

Note: After setting this value, call update so the result can be seen the the 3d view.
Type:
string

fakeUser

When set to True, this datablock wont be removed, even if nothing is using it. All data has this disabled by default except for Actions.
Type:
bool

lib

path to the blend file this datablock is stored in (readonly).

lib will be None unless you are using external blend files with (File, Append/Link)

Note: the path may be relative, to get the full path use Blender.sys.expandpath
Type:
string or None

materials

The mesh's materials. Each mesh can reference up to 16 materials. Empty slots in the mesh's list are represented by None. Note: Object.colbits needs to be set correctly for each object in order for these materials to be used instead of the object's materials. Note: Making the material list shorter does not change the face's material indices. Take care when using the face's material indices to reference a material in this list. Note: The list that's returned is not linked to the original mesh. mesh.materials.append(material) won't do anything. Use mesh.materials += [material] instead.
Type:
list of Materials

maxSmoothAngle

Same as degr. This attribute is only for compatibility with NMesh scripts and will probably be deprecated in the future.

mode

The mesh's mode bitfield. See Modes.
Type:
int

multires

The mesh has multires data, set True to add multires data. Will throw an exception if the mesh has shape keys; use key to test.
Type:
bool

multiresLevelCount

The mesh has multires data. (read only)
Type:
int

name

unique name within each blend file.

The name is case sensitive and 21 characters maximum length.

Note: a blend file may have naming collisions when external library data is used, be sure to check the value of lib.

Note: Setting a value longer then 21 characters will be shortened
Type:
string

renderColorLayer

The mesh's rendered Vertex Color layer. None if there is no UV/Image layers.
Type:
string

renderUVLayer

The mesh's rendered UV/Image layer. None if there is no UV/Image layers.
Type:
string

tag

A temporary tag that to flag data as being used within a loop. always set all tags to True or False before using since blender uses this flag for its own internal operations.
Type:
bool

users

The number of users this datablock has. (readonly) Zero user datablocks are de-allocated after reloading and saving.
Type:
int

vertexColors

The mesh contains vertex colors. Set True to add vertex colors.
Type:
bool