In this example we will draw a simple 3D primitive, add it to the plot, and display the result.
To draw the triangle we will use the mesh()
method from the k3d
module.
This method creates a Mesh
object, which can be added to a K3D Plot
.
import k3d
plot = k3d.plot()
vertices = [[0, 0, 0], [0, 0, 1], [1, 0, 0]]
indices = [[0, 1, 2]]
mesh = k3d.mesh(vertices, indices)
plot += mesh
plot.display()
Expected result:
The arguments we passed to the mesh()
function are a vertex array (a list
or NumPy's ndarray
is OK) which is composed of $(x, y, z)$ coordinates and an array of index triplets (int
s). Each triplet refers to the vertex array, defining one triangle.
We can of course add objects directly to the plot, without creating variables:
plot += k3d.mesh([0, 1, 1,
1, 1, 0,
1, 1, 1,
1, 1, 1,
1, 2, 2,
2, 1, 1], [0, 1, 2, 3, 4, 5], color=0x00ff00)
plot
Expected result:
This is a plot of two meshes. Please note -- in the second case we didn't nest the triplets - the numbers run continuously in a flat list. We also used an optional argument, color
to specify the color of the second object. K3D objects have many attributes, which we can find out about from the docstrings and from other examples, dedicated to the specific object type.
Back to the main topic. The plot
keeps track of the objects that it contains:
len(plot.objects)
We have 2 displays of the plot in the notebook, associated with 2 different cell outputs. However, they are the same plot - you should see the same scene (3 triangles) on both of them. Each view of the plot can be adjusted separately using the mouse.
When the plot becomes too cluttered with objects, we may want to remove some of them.
This is easily done with the -=
operator. This is the place, where having named our
objects beforehand comes in handy:
plot -= mesh
plot
Expected result:
Having variables is also convenient when we want to modify the objects already shown. This will be demonstrated in another example.