<<< Return to the Blender Python Notebook
Summary
If you are looking for a little more serendipity to your scripting, why not try a random variable? Whereas, the sin wave surface gives as a very predictable form, we can create a less predictable construction by supplying random variables into our parametric plot.
The key is to use the random library with "import random"
Random Surface
We will use a script that is almost identical to the wave surface. However, instead of using a mathematical Sin operation to control the Z-axis, we will use a random variable.
Random
To access random values, you first need to import the random class
import random
We can then call a random value from within the vertex For loop…
#fill verts array for i in range (0, numX): for j in range(0,numY): x = scale * i y = scale * j z = random.random()*amp vert = (x,y,z) verts.append(vert)
We can create an incremental effect for the random variation by multiplying the random value by the i variable and tweaking the amplitude.
#fill verts array for i in range (0, numX): for j in range(0,numY): x = scale * i y = scale * j z = (i * random.random())*amp vert = (x,y,z) verts.append(vert)
Subdivision Modifier
Our mesh is a little coarse, but we can easily smooth it out with a subdivision modifier. We can call the modifier with the following code:
# subdivide modifier myobject.modifiers.new("subd", type='SUBSURF') myobject.modifiers['subd'].levels = 3 # this adjusts the subdivisions in view
Show as Smooth
Finally, we can display the mesh as "smooth" faces…
# show mesh as smooth mypolys = mymesh.polygons for p in mypolys: p.use_smooth = True
Final Code
import bpy import random # mesh arrays verts = [] faces = [] # mesh variables numX = 20 numY = 20 # wave variables amp = 0.5 scale = 1 #fill verts array for i in range (0, numX): for j in range(0,numY): x = scale * i y = scale * j z = (i*random.random())*amp vert = (x,y,z) verts.append(vert) #fill faces array count = 0 for i in range (0, numY *(numX-1)): if count < numY-1: A = i B = i+1 C = (i+numY)+1 D = (i+numY) face = (A,B,C,D) faces.append(face) count = count + 1 else: count = 0 #create mesh and object mymesh = bpy.data.meshes.new("random mesh") myobject = bpy.data.objects.new("random mesh",mymesh) #set mesh location myobject.location = bpy.context.scene.cursor_location bpy.context.scene.objects.link(myobject) #create mesh from python data mymesh.from_pydata(verts,[],faces) mymesh.update(calc_edges=True) # subdivide modifier myobject.modifiers.new("subd", type='SUBSURF') myobject.modifiers['subd'].levels = 3 # show mesh as smooth mypolys = mymesh.polygons for p in mypolys: p.use_smooth = True
After a little Cycles rendering… viola!