Python CAD Tutorial 08 - Drawing a polygon & add generic shape class

View/Download Code


Figure 1: Polygon

We created a grid in the previous tutorial. Now let's add a polygon class and a shape object to contain our primitives.The polygon class is basically an extension of the line class. It works in the same way, however we have added an append method which keeps adding points to the polygon on each click. The draw method has then been adjusted to loop over and draw the polygon from the point list.

from point import createpoint

class createpolygon:
    name = 'polygon'
    points = []
    closed = True

    def __init__(self, point):
	self.points = []
	self.color = 0, 1, 0
	self.display_color = 0, 1, 0
	self.newPoint = None

    def append(self, point):

    def glvertex(self):
	glVertex3f(self.p1.x, self.p1.y, self.p1.z)

    #vertexs to draw a line use with glbegin(GL_LINES)
    def glvertexlist(self):
	glVertex3f(self.p1.x, self.p1.y, self.p1.z)
	glVertex3f(self.p2.x, self.p2.y, self.p2.z)

    def get_points(self):
	for p in self.points:
	    yield (p)

    def draw(self):
	if len(self.points) > 1:
	    for n in xrange(0, len(self.points) - 1):
		glVertex3f(self.points[n].x, self.points[n].y, self.points[n].z)
		glVertex3f(self.points[n + 1].x, self.points[n + 1].y, self.points[n + 1].z)
	    if self.closed is True:
		glVertex3f(self.points[0].x, self.points[0].y, self.points[0].z)
		glVertex3f(self.points[-1].x, self.points[-1].y, self.points[-1].z)

	for item in self.points:

The shape class below is basically just a container object for storing our various primitives like lines, circles and polygons. This class has methods to loop over and add the primitives store,. This will be useful later on for changing properties on mass.In the main file you can see that our new polygon is contained and updated through the shape class. Later on we will attach this to our GUI so we can dynamically add primitives as we need them.

from point import createpoint

class createshape:
    location = createpoint((0, 0, 0))
    primitives = []

    def __init__(self, name=None):
	self.primitives = []

    def append(self, item):

    def __getitem__(self, n):
	return self.primitives[n]

    #temporary to get last primitive added to the scene
    def update_last(self):
	return self.primitives[-1]

    def count(self):
	return len(self.primitives) - 1

    def draw(self):
	for item in self.primitives: