Jun 28, 2019

Creating a torus (animated and variations)


Looking at the Pentagon torus:


And its source code:



And changing the rings to 30:




And if you use triangle surface to create the Pentagonal torus in 3D:



What are the difference in programming?   In the previous two, the torus is created by a prebuilt function called (look into the "display()" function for how the object is generated) glutWireTorus().
        global xrot, yrot, zrot
        global ndisc
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        gluLookAt(
                0.0, 0.0, 10.0,
                0.0, 0.0, 0.0,
                0.0, 1.0, 0.0)
        glRotatef(xrot, 1.0, 0.0, 0.0)
        glRotatef(yrot, 0.0, 1.0, 0.0)
        glRotatef(zrot, 0.0, 0.0, 1.0)
        glColor3f(0.5, 0.0, 1.0)
        glutWireTorus(0.5,1.5,5,5)
        glFlush()
        glutSwapBuffers()
But in the case of triangulated surface generated torus it is built from scratch using "triangle", and thus can be controlled via use of cosine() and sine() to generate the triangles for the surface of the torus.   The technique is to generate a list of coordinates of the vertices of the surface, and the normal vector centering on that coordinate.
        vertices = []
        normals = []
        u_step = 2 * pi / (slices)
        v_step = 2 * pi / (inner_slices)
        u = 0.
        for i in range(slices+1):
            cos_u = cos(1*u)
            sin_u = sin(1*u)
            v = 0.
            for j in range(inner_slices):
                cos_v = cos(1*v)
                sin_v = sin(1*v)
                d = (radius + inner_radius * cos_v)
                x = d * (cos_u +2)* cos_u
                y = d * (cos_u +2)* sin_u
                z = inner_radius * sin_v
                nx = cos_u * cos_v
                ny = sin_u * cos_v
                nz = sin_v
                vertices.extend([x, y, z])
                normals.extend([nx, ny, nz])
                v += v_step
            u += u_step
        # Create a list of triangle indices.
        indices = []
        for i in range(slices):
            for j in range(inner_slices):
                p = i * inner_slices + j
                indices.extend([p, p + inner_slices, p + inner_slices + 1])
                indices.extend([p, p + inner_slices + 1, p + 1])
        self.vertex_list = batch.add_indexed(len(vertices)//3,
                                             GL_TRIANGLE_STRIP,
                                             group,
                                             indices,
                                             ('v3f/static', vertices),
                                             ('n3f/static', normals))

No comments: