Python CAD Tutorial 02 - Draw points in 3d Space

View/Download Code


Figure 1: Point in 3D space

In this tutorial we will create a 3D point class and position and draw it to the screen.

This will be a base class for storing positions in space, we will also implement code to display the points in this class. For now we will hard code a single point in the camera view. We do not have a working camera class yet, so this will be fixed with a position so we know its working.We will store the x, y and z positions and colour for the point along with the display size. The important methods here are the 'init' and the 'draw' method, the others are helper methods which we will use later on.The helper methods include:

  • The eq method will be usefull for testing if two points share the same location in space.
  • str will format the point into a string, which is usefull for debugging.
  • getposition will return a numeric version of the point as a tuple.
class createpoint:
    x = y = z = 0.0
    display_color = (0, 0, 1)

    def __init__(self, p, c=(0, 1, 0)):
	""" Position in 3d space as a tuple or list, and colour in tuple or list format"""
	self.point_size = 5
	self.color = c
	self.display_color = c
	self.x, self.y, self.z = p

    def get_position(self):
	""" Return the cordinates as a tuple"""
	return self.x, self.y, self.z

    def glvertex(self):
	""" Opengl vertex useful so we can dont have to glbegin and glend for each point"""
	glVertex3f(self.x, self.y, self.z)

    def __getitem__(self, index):
	""" Get a cordinate handy for use in for loops where we want to calculate things"""
	return (self.x, self.y, self.z)[index]

    def __str__(self):
	""" Print point cordinates useful for debugging"""
	return '(%s, %s, %s)' % (str(self.x), str(self.y), str(self.z))

    def __eq__(self, point):
	""" Equality test so we can test if points occupy same space"""
	return self.x == point.x and self.y == point.y and self.z == point.z

    def draw(self, c=(0, 1, 0)):
	""" Set the size of the point and render"""
	glColor3f(self.color[0], self.color[1], self.color[2])
	glVertex3f(self.x, self.y, self.z)

Update the draw method to test out new code works.

def on_draw(self, *args):
    """ Test code to make sure we can draw a pixel successfully can play with the parameters here"""
    glClearColor(0.0, 0.0, 0.0, 0.0)
    test_point = point.createpoint((0,0,0.5))