Learn · Scripting · Lesson 2 of 3
Edit a mesh with numpy
Scripts can read and write a whole mesh at once. You will roughen a model by moving every vertex a little, then taper it — each change one operation and one undo step, however many vertices the mesh has.
- 10 minutes
- Intermediate
- Browser or Windows
1. Check the selection
Open a model, switch to the Model editor and select one mesh object. A good script refuses politely when it has nothing to work on:
import numpy as np
import toolbox3d as tb
obj = tb.scene.selection.active
if obj is None or obj.mesh is None:
raise tb.NotApplicable("select a mesh object first")
The script stops there and the output console shows the message, so whoever runs your tool knows what to do next.
2. Read the vertices
positions = obj.mesh.positions()
print(positions.shape) # (number of vertices, 3)
positions() returns a numpy float32 array with one row per vertex, in the object's own space. It is a snapshot: changing the array does not touch the scene until you write it back. numpy is available in the browser editor as well as the Windows app.
3. Change them
Work on the whole array at once instead of looping over vertices in Python. A fixed random seed makes the result repeatable:
AMOUNT = 0.02 # scene units
rng = np.random.default_rng(1)
positions += rng.normal(0.0, AMOUNT, positions.shape).astype(np.float32)
4. Write them back
obj.mesh.set_positions(positions)
print(f"moved {len(positions)} vertices of {obj.name}")
set_positions replaces every vertex position in one operation, so one Ctrl+Z restores the original mesh. The array must keep the same number of rows; topology does not change.
Shortcut: steps 1–4 ship as 04_numpy_noise.py under Help › Script Examples and on the examples page.
5. Shape, not just noise
The same pattern shapes a model. This tapers the mesh towards its top by scaling X and Z with height:
positions = obj.mesh.positions()
y = positions[:, 1]
t = (y - y.min()) / max(float(y.max() - y.min()), 1e-6) # 0 at the bottom, 1 at the top
scale = 1.0 - 0.5 * t
positions[:, 0] *= scale
positions[:, 2] *= scale
with tb.undo.group("Taper"):
obj.mesh.set_positions(positions)