def init(filename): """ Initialize aspects of the GL object rendering. """ global \ trackball, flashlight, \ models, buffers, \ surface_shader, flat_shader # Initialize quaternions for the light and trackball flashlight = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) trackball = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) # Read the .OBJ/.PGM file. if filename[-3:] == 'obj': object = surface.from_obj(filename) elif filename[-3:] == 'pgm': object = surface.from_pgm(filename) else: print("Unknown file format. Should be a .obj or .pgm file.\n") quit() models = [object] buffers = [buffers_for_model(object)] # Set up the shader(s). surface_shader = init_shaders('shaders/vs-mesh.c', 'shaders/fs-mesh.c') # Set up OpenGL state. glEnable(GL_DEPTH_TEST)
def init(filename): """ Initialize aspects of the GL scene rendering. """ global trackball, flashlight, vertex_buffer, normal_buffer, color_buffer, colors, vertices, normals # initialize quaternions for the light and trackball flashlight = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) trackball = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) # read the .OBJ file into VBOs scene.read(filename) vertices, normals, colors = scene.compile() vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertices) * 4, (c_float * len(vertices))(*vertices), GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normals) * 4, (c_float * len(normals))(*normals), GL_STATIC_DRAW) color_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, color_buffer) glBufferData(GL_ARRAY_BUFFER, len(colors) * 4, (c_float * len(colors))(*colors), GL_STATIC_DRAW) # set up the object shaders init_shaders() glEnable(GL_DEPTH_TEST)
def __init__(self, x=0, y=0, z=0, x_angle=0, y_angle=0, z_angle=0, scale=None, x_scale=1, y_scale=1, z_scale=1): if scale != None: x_scale = scale if x_scale == 1 else x_scale y_scale = scale if y_scale == 1 else y_scale z_scale = scale if z_scale == 1 else z_scale self.position = vector([x, y, z]) self.scale = vector([x_scale, y_scale, z_scale]) # Convert angles in degrees to radians self.rotation = vector([ math.pi * x_angle / 180, math.pi * y_angle / 180, math.pi * z_angle / 180 ])
def __init__(self, resolutionX=400, resolutionY=400, frame_rate=60): self.screen = pygame.display.set_mode([resolutionX, resolutionY]) self.resolutionX = resolutionX self.resolutionY = resolutionY self.open = False self.objects = [] self.camera_position = vector([0, 0, 0]) self.camera_rotation = vector([0, 0, 0]) # Top left and bottom right corners self.camera_view_plane = ((-1, 1), (1, -1)) self.camera_view_plane_z = -1 self.frame_rate = frame_rate self.clock = pygame.time.Clock() os.environ["SDL_VIDEO_CENTERED"] = '1' pygame.init()
def __init__(self, mass0, position0): self.mass = mass0 self.position0 = position0 self.position = position0 self.velocity0 = vector(0.0,0.0,0.0) self.velocity = vector(0.0,0.0,0.0) self.fixed = False self.springs = [] Springies.masses.append(self)
def mouse(button, state, x, y): global xStart, yStart, trackball xStart = (x - width / 2) * scale yStart = (height / 2 - y) * scale if glutGetModifiers() == GLUT_ACTIVE_SHIFT and state == GLUT_DOWN: minus_z = trackball.recip().rotate(vector(0.0, 0.0, -1.0)) click = trackball.recip().rotate(vector(xStart, yStart, 2.0)) glutPostRedisplay()
def mouse(button, state, x, y): global xStart, yStart, trackball xStart = (x - width/2) * scale yStart = (height/2 - y) * scale if glutGetModifiers() == GLUT_ACTIVE_SHIFT and state == GLUT_DOWN: minus_z = trackball.recip().rotate(vector(0.0,0.0,-1.0)) click = trackball.recip().rotate(vector(xStart,yStart,2.0)) glutPostRedisplay()
def __init__(self, vEye=vector([0, 0, -3, 1]), vAt=vector([0.23, 0, 0, 1]), vUp=vector([0, 1, 0, 0]), fFov=0.5*np.pi, fAspect=1.0, fNear=1.0, fFar=500.0): self.m_vEye = vEye # 相机的位置 self.m_vAt = vAt # 注视目标的位置 self.m_vUp = vUp # 上向量 self.m_mViewTrans = None self.m_fFov = fFov # 竖直方向的张开角度 self.m_fAspect = fAspect self.m_fNear = fNear # 近裁剪平面 self.m_fFar = fFar # 远裁剪平面 self.m_mPerspTrans = None
def mouse(button, state, x, y): global xStart, yStart, trackball, selected_face, add_face xStart = (x - width / 2) * scale yStart = (height / 2 - y) * scale if glutGetModifiers() == GLUT_ACTIVE_SHIFT and state == GLUT_DOWN: minus_z = trackball.recip().rotate(vector(0.0, 0.0, -1.0)) click = trackball.recip().rotate(vector(xStart, yStart, 2.0)) selected_face = scene.intersect_ray(ORIGIN + click, minus_z) add_face = True glutPostRedisplay()
def draw_object(): if draw_mode == MODE_ALL: # * * * * * * * * * * * * * * * * # BEGIN drawing of all the triangular facets. # # # * * * # A. Select which shaders we went to use glUseProgram(surface_shader) shs = surface_shader # * * * # B. Identify the variables in the shader code. h_vertex = glGetAttribLocation(shs, 'vertex') h_normal = glGetAttribLocation(shs, 'normal') h_light = glGetUniformLocation(shs, 'light') h_eye = glGetUniformLocation(shs, 'eye') # * * * # C. Associate buffers/values with those variables. # all the vertex positions glEnableVertexAttribArray(h_vertex) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer(h_vertex, 3, GL_FLOAT, GL_FALSE, 0, None) # all the face normals glEnableVertexAttribArray(h_normal) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glVertexAttribPointer(h_normal, 3, GL_FLOAT, GL_FALSE, 0, None) # position of the flashlight light = flashlight.rotate(vector(0.0, 1.0, 0.0)) glUniform3fv(h_light, 1, (4.0 * light).components()) # position of the viewer's eye eye = trackball.recip().rotate(vector(0.0, 0.0, 1.0)) glUniform3fv(h_eye, 1, eye.components()) # * * * # D. Issue the geometry. glDrawArrays(GL_TRIANGLES, 0, num_vertices) # * * * # E. Disable some stuff. glDisableVertexAttribArray(h_vertex) glDisableVertexAttribArray(h_normal) glUseProgram(0) if draw_mode == MODE_TRON: draw_triangles(vertex_buffer, num_vertices, [0.05, 0.05, 0.1])
def Test1(): oCameraMgr = camera.CMgr() oCamera = oCameraMgr.GetCamera(camera.TYPE_NORMAL) oCamera.SetEye(vector([-3, 0, 0, 1])) oCamera.SetLookAt(vector([-2, 0, 0, 1])) oCamera.SetUp(vector([0, 1, 0, 0])) vPos = vector([-2, 0, 0, 1]) mViewing = oCamera.GetViewTrans() print(mViewing) vViewPos = np.dot(mViewing, vPos) vViewPos = [int(i) for i in vViewPos] print(vViewPos)
def init(filename): """ Initialize aspects of the GL object rendering. """ global \ trackball, flashlight, \ vertex_buffer, normal_buffer, bary_buffer, floor_buffer, \ floor_shader, mesh_shader # Initialize quaternions for the light and trackball flashlight = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) trackball = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) # Read the .OBJ file into VBOs. object.read(filename) vertices, normals = object.compile() barys = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] * len(face.instances) floor = [ -2.0, -0.01, -2.0, -2.0, -0.01, +2.0, +2.0, -0.01, +2.0, +2.0, -0.01, +2.0, +2.0, -0.01, -2.0, -2.0, -0.01, -2.0 ] # Scene vertices, both floor and object. floor_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, floor_buffer) glBufferData(GL_ARRAY_BUFFER, len(floor) * 4, (c_float * len(floor))(*floor), GL_STATIC_DRAW) vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertices) * 4, (c_float * len(vertices))(*vertices), GL_STATIC_DRAW) # Object normals. normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normals) * 4, (c_float * len(normals))(*normals), GL_STATIC_DRAW) # Object face barycenter determination. bary_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, bary_buffer) glBufferData(GL_ARRAY_BUFFER, len(barys) * 4, (c_float * len(barys))(*barys), GL_STATIC_DRAW) # Set up the shaders. floor_shader = init_shaders('shaders/vs-floor.c', 'shaders/fs-floor.c') mesh_shader = init_shaders('shaders/vs-mesh.c', 'shaders/fs-mesh.c') # Set up OpenGL state. glEnable(GL_DEPTH_TEST)
def make_ritchey_chretien(focal_length, D, b, aperture_radius): """Ritchey-Chrétien Args: focal_length: focal length D: distance between primary and secondary (along axis) b: backfocus from primary to focal plane aperture_radius: aperture radius Returns: The resulting Instrument Notation follows https://en.wikipedia.org/wiki/Ritchey%E2%80%93Chr%C3%A9tien_telescope """ debug = True F = focal_length B = D + b R1 = -(2 * D * F) / (F - B) R2 = -(2 * D * B) / (F - B - D) f1 = np.abs(R1) / 2 f2 = np.abs(R2) / 2 M = F / f1 M_alt = (F - B) / D print(f"M={M}, M_alt={M_alt}") assert np.isclose(M, M_alt) K1 = -1 - (2 / M**3) * (B / D) K2 = -1 - (2 / (M - 1)**3) * (M * (2 * M - 1) + B / D) print( f"primary: trying to make hyperboloid with radius {-R1} conic constant {K1} at z=0" ) primary = make_conic(-R1, K1, 0) print(f"primary: {primary}") print( f"secondary: trying to make hyperboloid with radius {-R2} conic constant {K2} at z={D}" ) secondary = make_conic(-R2, K2, D, reverse_normal=True) print(f"secondary: {secondary}") aperture0 = CircularAperture(point(0, 0, D), vector(0, 0, -aperture_radius)) # The rule we used for the parabolic should still be approximately correct here. z_reflector_edge = aperture_radius**2 / (4 * f1) aperture1 = CircularAperture(point(0, 0, z_reflector_edge), vector(0, 0, -aperture_radius)) #source = standard_source(focal_length, aperture_radius) source = standard_source(D, aperture_radius) elements = Compound([aperture0, aperture1, primary, secondary]) sensor = PlanarSensor.of_q_x_y(point(0, 0, -b), -ii, -jj) return Instrument(source, elements, sensor)
def compute_acceleration(self): Fg,Fd = vector(0.0,0.0,0.0),vector(0.0,0.0,0.0) if GLOBALS.gravity_on: Fg = vector(0.0,-self.mass*GRAVITY,0.0) if self.velocity0.norm() != 0: Fd = -DAMPING*(self.velocity0 / self.velocity0.norm()) Fs = vector(0.0,0.0,0.0) for spring in self.springs: Fs += spring.force(self) F_net = Fs + Fd + Fg return F_net / self.mass
def main(argc, argv): """ The main procedure, sets up GL and GLUT. """ global trackball, facets trackball = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) facets = makeObject() glutInit(argv) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowPosition(0, 20) glutInitWindowSize(360, 360) glutCreateWindow(b'object showcase - Press ESC to quit') initRendering() # Register interaction callbacks. glutKeyboardFunc(myKeyFunc) glutSpecialFunc(myArrowFunc) glutReshapeFunc(resizeWindow) glutDisplayFunc(drawScene) print() print('Press the arrow keys to rotate the object.') print('Press ESC to quit.\n') print() glutMainLoop() return 0
def arrow(key, x, y): """ Handle a "special" keypress. """ global trackball, flashlight if key == GLUT_KEY_DOWN or key == GLUT_KEY_UP: axis = trackball.recip().rotate(vector(1.0, 0.0, 0.0)) if key == GLUT_KEY_LEFT or key == GLUT_KEY_RIGHT: axis = trackball.recip().rotate(vector(0.0, 1.0, 0.0)) if key == GLUT_KEY_LEFT or key == GLUT_KEY_DOWN: angle = -pi / 12.0 if key == GLUT_KEY_RIGHT or key == GLUT_KEY_UP: angle = pi / 12.0 if key in {GLUT_KEY_LEFT, GLUT_KEY_RIGHT, GLUT_KEY_UP, GLUT_KEY_DOWN}: flashlight = quat.for_rotation(angle, axis) * flashlight glutPostRedisplay()
def init(filename): """ Initialize aspects of the GL object rendering. """ global \ trackball, flashlight, \ num_vertices, vertex_buffer, normal_buffer, \ object, \ surface_shader, flat_shader # Initialize quaternions for the light and trackball flashlight = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) trackball = quat.for_rotation(0.0, vector(1.0, 0.0, 0.0)) # Read the .OBJ/.PGM file. if filename[-3:] == 'obj': object = surface.from_obj(filename) elif filename[-3:] == 'pgm': object = surface.from_pgm(filename) else: print("Unknown file format. Should be a .obj or .pgm file.\n") quit() # Get the information from the surface for the VBOs just below. num_vertices, vertices, normals = object.compile() # Surface vertices. vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertices) * 4, (c_float * len(vertices))(*vertices), GL_STATIC_DRAW) # Surface normals. normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normals) * 4, (c_float * len(normals))(*normals), GL_STATIC_DRAW) # Set up the shader(s). surface_shader = init_shaders('shaders/vs-surface.c', 'shaders/fs-surface.c') flat_shader = init_shaders('shaders/vs-flat.c', 'shaders/fs-flat.c') # Set up OpenGL state. glEnable(GL_DEPTH_TEST)
def arrow(key, x, y): """ Handle a "special" keypress. """ global trackball,flashlight if key == GLUT_KEY_DOWN or key == GLUT_KEY_UP: axis = trackball.recip().rotate(vector(1.0,0.0,0.0)) if key == GLUT_KEY_LEFT or key == GLUT_KEY_RIGHT: axis = trackball.recip().rotate(vector(0.0,1.0,0.0)) if key == GLUT_KEY_LEFT or key == GLUT_KEY_DOWN: angle = -pi/12.0 if key == GLUT_KEY_RIGHT or key == GLUT_KEY_UP: angle = pi/12.0 if key in {GLUT_KEY_LEFT,GLUT_KEY_RIGHT,GLUT_KEY_UP,GLUT_KEY_DOWN}: # Apply an adjustment to the position of the light. flashlight = quat.for_rotation(angle,axis) * flashlight # Redraw. glutPostRedisplay()
def setNormal(self): """ Set normal by summing normals of adjacent triangles """ for tri in self.adj_tris: normalVec = vector(0.0, 0.0, 0.0) normalVec = normalVec + tri.normal self.normal = normalVec.unit() #self.normal = -1.0*self.normal return self.normal
def getColor(v1,v2,v3,hue): # Generates the color for a facet on an object, # given the facet's vertices and the object's hue; # color is determined using a combination of # ambient and diffuse lighting. lightPos = vector(0.0,0.0,1.0) ambStrength = 0.3 ambient,diffuse = [],[] for val in hue: ambient.append(ambStrength*val) # Get surface normal for the facet u = vector(v3[0]-v1[0],v3[1]-v1[1],v3[2]-v1[2]) w = vector(v1[0]-v2[0],v1[1]-v2[1],v1[2]-v2[2]) normal = u.cross(w) try: # Normalize surface normal normal = normal/normal.norm() # Get the facet's centroid center = vector((v1[0]+v2[0]+v3[0])/3, (v1[1]+v2[1]+v3[1])/3, (v1[2]+v2[2]+v3[2])/3) # Direction vector for light, normalized lightDir = lightPos-center lightDir = lightDir/lightDir.norm() # Amount of diffuse lighting d = max(normal.dot(lightDir),0.0) for val in hue: diffuse.append(d*val) c = color(ambient[0]+diffuse[0],ambient[1]+diffuse[1],ambient[2]+diffuse[2]) except ZeroDivisionError: # Default to hue if error in calculations # (this happens on the teapot for some reason) c = color(hue[0],hue[1],hue[2]) return c
def arrow(key, x, y): """ Handle a "special" keypress. """ global trackball, flashlight x_axis = trackball.recip().rotate(vector(1.0, 0.0, 0.0)) y_axis = trackball.recip().rotate(vector(0.0, 1.0, 0.0)) # Apply an adjustment to the overall rotation. if key == GLUT_KEY_DOWN: flashlight = quat.for_rotation(pi / 12.0, x_axis) * flashlight if key == GLUT_KEY_UP: flashlight = quat.for_rotation(-pi / 12.0, x_axis) * flashlight if key == GLUT_KEY_LEFT: flashlight = quat.for_rotation(-pi / 12.0, y_axis) * flashlight if key == GLUT_KEY_RIGHT: flashlight = quat.for_rotation(pi / 12.0, y_axis) * flashlight # Redraw. glutPostRedisplay()
def arrow(key, x, y): """ Handle a "special" keypress. """ global trackball,flashlight x_axis = trackball.recip().rotate(vector(1.0,0.0,0.0)) y_axis = trackball.recip().rotate(vector(0.0,1.0,0.0)) # Apply an adjustment to the overall rotation. if key == GLUT_KEY_DOWN: flashlight = quat.for_rotation( pi/12.0,x_axis) * flashlight if key == GLUT_KEY_UP: flashlight = quat.for_rotation(-pi/12.0,x_axis) * flashlight if key == GLUT_KEY_LEFT: flashlight = quat.for_rotation(-pi/12.0,y_axis) * flashlight if key == GLUT_KEY_RIGHT: flashlight = quat.for_rotation( pi/12.0,y_axis) * flashlight # Redraw. glutPostRedisplay()
def make_conic(R, K, z_offset, material=None, reverse_normal=False): """ See https://en.wikipedia.org/wiki/Conic_constant r^2 - 2Rz + (K+1)z^2 = 0 Be careful about the sign convention for radius of curvature. We follow the convention in https://en.wikipedia.org/wiki/Conic_constant but this is opposite the convention in https://en.wikipedia.org/wiki/Lens#Lensmaker's_equation . Args: R: radius of curvature; use R > 0 for concave "up" (direction of positive z-axis) while R < 0 is concave "down" K: conic constant; should be < -1 for hyperboloids, -1 for paraboloids, > -1 for ellipses (including 0 for spheres). The relationship with eccentricity e is K = -e^2 (when K <= 0). z_offset: z-coordinate where the surface intersects z-axis material: mostly self explanatory; None means reflector reverse_normal: If true, surface points in direction of negative z-axis rather than positive z-axis """ M = np.diag([1, 1, (K + 1), 0]) M[2, 3] = -R M[3, 2] = M[2, 3] # For either sign of R, we want the convention that gradient points up at origin. # That gradient is (0,0,-R). # When R < 0, we already have that. # For R > 0, we need to negate M to get that. if R > 0: M *= -1 if reverse_normal: M *= -1 quad = Quadric(M) geometry = quad.untransform(translation3f(0, 0, -z_offset)) if R > 0: # We want to keep the top sheet. # TODO: Let clip_z be halfway between the two foci. clip_z = z_offset - 1e-6 clip = Plane(make_bound_vector(point(0, 0, clip_z), vector(0, 0, -1))) else: clip_z = z_offset + 1e-6 clip = Plane(make_bound_vector(point(0, 0, clip_z), vector(0, 0, 1))) return SubElement(geometry, clip, material=material)
def myArrowFunc(key, x, y): """ Handle a "special" keypress. """ global trackball x_axis = vector(1.0, 0.0, 0.0) y_axis = vector(0.0, 1.0, 0.0) # Apply an adjustment to the overall rotation. if key == GLUT_KEY_DOWN: trackball = quat.for_rotation(pi / 12.0, x_axis) * trackball if key == GLUT_KEY_UP: trackball = quat.for_rotation(-pi / 12.0, x_axis) * trackball if key == GLUT_KEY_LEFT: trackball = quat.for_rotation(-pi / 12.0, y_axis) * trackball if key == GLUT_KEY_RIGHT: trackball = quat.for_rotation(pi / 12.0, y_axis) * trackball # Redraw. glutPostRedisplay()
def as_rotation(self): """ The rotation represented by self, given as an angle around an vector serving as the Euler axis of rotation. """ qs = self.unit().components() half_theta = acos(qs[0]) if half_theta < EPSILON: return (0.0,vector(1.0,0.0,0.0)) else: return (2.0*half_theta, vector.with_components(qs[1:])/sin(half_theta))
def motion(x, y): global trackball, xStart, yStart xNow, yNow = world(x,y) dx = xNow-xStart dy = yNow-yStart axis = vector(-dy,dx,0.0).unit() angle = asin(min(sqrt(dx*dx+dy*dy),1.0)) trackball = quat.for_rotation(angle,axis) * trackball xStart = xNow yStart = yNow glutPostRedisplay()
def keypress(key, x, y): """ Handle a "normal" keypress. """ global wireframe, snap, ddd if key == b'\033': # "\033" is the Escape key sys.exit(1) if key == b' ': wireframe = not wireframe resize(width, height) glutPostRedisplay() if key == b'=': ddd += 0.1 resize(width, height) glutPostRedisplay() if key == b'-': ddd -= 0.1 resize(width, height) glutPostRedisplay() if key == b'.': print("Taking snapshot. Hold still...") eye = point.origin() + trackball.recip().rotate(vector(0.0, 0.0, 2.5)) plane = point.origin() + trackball.recip().rotate(vector( 0.0, 0.0, 2.0)) up = trackball.recip().rotate(vector(0.0, 1.0, 0.0)) right = trackball.recip().rotate(vector(1.0, 0.0, 0.0)) away = trackball.recip().rotate(vector(0.0, 0.0, 1.0)) name = fileroot + str(snap) + ".ps" snap = snap + 1 lines = object.toPS(name, camera(eye, plane, right, up, away)) print("Wrote " + name + ".")
def make_newtonian(focal_length, aperture_radius): """A very simple Newtonian design where we don't even stick in the flat secondary, because we're just trying to analyze coma (which isn't affected by the flat secondary). """ source = standard_source(focal_length, aperture_radius) aperture0 = CircularAperture(point(0, 0, focal_length), vector(0, 0, -aperture_radius)) # Reflector is z = r^2 / (4 focal length), so at edge, # we have: z_reflector_edge = aperture_radius**2 / (4 * focal_length) aperture1 = CircularAperture(point(0, 0, z_reflector_edge), vector(0, 0, -aperture_radius)) reflector = make_paraboloid(focal_length) # In practice there would be another mirror. So we actually pretend the sensor # is facing up. sensor = PlanarSensor.of_q_x_y(point(0, 0, focal_length), -ii, -jj, flip_z=True) elements = Compound([aperture0, aperture1, reflector]) return Instrument(source, elements, sensor)
def normal(self): # If there's no normal, compute one. if not self.vn: # Sum the incident face normals. ns = vector(0.0,0.0,0.0) for e in self.around(): ns = ns + e.face.normal() # Normalize that sum. self.set_normal(ns.unit()) # Return the normal attribute. return self.vn
def main(argc, argv): global trackball, facets, cam, radius #read in input if argc is 3: shape = argv[1] smoothness = argv[2] elif argc is 2: shape = argv[1] smoothness = 10 else: shape = "bunny" smoothness = 15 #generate the .obj shapefile, and read it shapeFile = shape + str(smoothness) + ".obj" writeObj(str(shape), smoothness) s = surface() s.readObjFile(shapeFile) s.createHalfEdges() facets = s.faces radius = 2.0 cam = camera() #you can even extend facets to see the shapes overlaid #facets.extend(readObjFile'torus.obj') trackball = quat.for_rotation(0.0,vector(1.0,0.0,0.0)) glutInit(argv) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowPosition(0, 20) glutInitWindowSize(width, height) glutCreateWindow( 'shapes - Press ESC to quit' ) initRendering() # Register interaction callbacks. glutKeyboardFunc(myKeyFunc) glutSpecialFunc(myArrowFunc) glutMouseFunc(facetSelect) glutMotionFunc(sliceDir) glutReshapeFunc(resize) glutDisplayFunc(drawScene) print() print('Press the arrow keys rotate the object.') print('Press ESC to quit.\n') print() glutMainLoop() return 0
def Test3(): import geometry import device oDevice = device.CDevice() oVertex1 = geometry.CVertex(vector([30, 40, 0, 1]), vector([0, 0, 1, 0]), vector([0, 0]), 1) oVertex2 = geometry.CVertex(vector([10, 20, 0, 1]), vector([0, 0, 1, 0]), vector([1, 0]), 1) oVertex3 = geometry.CVertex(vector([20, 0, 0, 1]), vector([0, 0, 1, 0]), vector([0, 1]), 1) tTrapezoids = oDevice.trapezoidTriangle(oVertex1, oVertex2, oVertex3) print(tTrapezoids) for tTrapezoid in tTrapezoids: for oVertex in tTrapezoid: print(oVertex[0]) print(oVertex[1]) print("---------")
def motion(x, y): global trackball, xStart, yStart xNow = (x - width / 2) * scale yNow = (height / 2 - y) * scale change = point(xNow, yNow, 0.0) - point(xStart, yStart, 0.0) axis = vector(-change.dy, change.dx, 0.0) sin_angle = change.norm() / radius sin_angle = max(min(sin_angle, 1.0), -1.0) # clip angle = asin(sin_angle) trackball = quat.for_rotation(angle, axis) * trackball xStart, yStart = xNow, yNow glutPostRedisplay()
def __init__(self, obj_transform, x_rotate_rate=0, y_rotate_rate=0, z_rotate_rate=0, config_window=False): self.transform = obj_transform self.rotation_rate = vector([ math.pi * x_rotate_rate / 180, math.pi * y_rotate_rate / 180, math.pi * z_rotate_rate / 180 ])
def motion(x, y): global trackball, xStart, yStart xNow = (x - width/2) * scale yNow = (height/2 - y) * scale change = point(xNow,yNow,0.0) - point(xStart,yStart,0.0) axis = vector(-change.dy,change.dx,0.0) sin_angle = change.norm()/radius sin_angle = max(min(sin_angle,1.0),-1.0) # clip angle = asin(sin_angle) trackball = quat.for_rotation(angle,axis) * trackball xStart,yStart = xNow, yNow glutPostRedisplay()
def read(self,filename): obj_file = open(filename,'r') normali = 0 for line in obj_file: # Parse a line. parts = line[:-1].split() if len(parts) > 0: # Read a vertex description line. if parts[0] == 'v': x = float(parts[1]) y = float(parts[2]) z = float(parts[3]) P = point(x,y,z) vertex(P,self) # Read a vertex normal description line. elif parts[0] == 'vn': dx = float(parts[1]) dy = float(parts[2]) dz = float(parts[3]) vn = vector(dx,dy,dz).unit() self.vertex[normali].set_normal(vn) normali += 1 # Read a face/fan description line. elif parts[0] == 'f': vi_fan = [int(p.split('/')[0]) - 1 for p in parts[1:]] vi1 = vi_fan[0] # add the faces of the fan for i in range(1,len(vi_fan)-1): vi2 = vi_fan[i] vi3 = vi_fan[i+1] V1 = self.vertex[vi1] V2 = self.vertex[vi2] V3 = self.vertex[vi3] face(V1,V2,V3,self) # Wrap up the vertex fans. Re-chooses each vertex's out edge. self.finish() # Rescale and center the points. self.rebox()
def init(filename): """ Initialize aspects of the GL scene rendering. """ global trackball, flashlight, \ shaders, shadowers, mesh, mesh0 # Initialize quaternions for the light and trackball flashlight = quat.for_rotation(0.0,vector(1.0,0.0,0.0)) trackball = quat.for_rotation(0.0,vector(1.0,0.0,0.0)) # Read the .OBJ file into VBOs. mesh0 = object() mesh0.read(filename) vbo_ify(mesh0) mesh = mesh0 # Set up the shaders. shaders = init_shaders('shaders/vs-mesh.c', 'shaders/fs-mesh.c') shadowers = init_shaders('shaders/vs-shadow.c', 'shaders/fs-shadow.c') # Set up OpenGL state. glEnable (GL_DEPTH_TEST)
def read(cls,filename): obj_file = open(filename,'r') # Record the offset for vertex ID conversion. vertexi = len(vertex.all_instances()) # Count the number of vertex normals read. normali = 0 for line in obj_file: parts = line[:-1].split() if len(parts) > 0: # Read a vertex description line. if parts[0] == 'v': x = float(parts[1]) y = float(parts[2]) z = float(parts[3]) P = point(x,y,z) vertex.add(P) # Read a vertex normal description line. elif parts[0] == 'vn': dx = float(parts[1]) dy = float(parts[2]) dz = float(parts[3]) vn = vector(dx,dy,dz).unit() # vertex.with_id(normali).set_normal(vn) normali += 1 # Read a face/fan description line. elif parts[0] == 'f': #### ADDS AN OFFSET vertexi FROM THE .OBJ INDEX!!! (.OBJ starts at 1) #### vi_fan = [int(p.split('/')[0]) + vertexi - 1 for p in parts[1:]] vi1 = vi_fan[0] # add the faces of the fan for i in range(1,len(vi_fan)-1): vi2 = vi_fan[i] vi3 = vi_fan[i+1] V1 = vertex.with_id(vi1) V2 = vertex.with_id(vi2) V3 = vertex.with_id(vi3) face.add(V1,V2,V3) # rescale and center the points object.rebox()
def __init__(s): """ Initialize the plane, at 10000 feet going 150kts. """ # Parameters related to airplane's position # All parameters are in feet. # Some starting parameters s.altitude = ft2WU(12000) # in ft s.airspeed = kts2WUps(200) # in kts s.AngleOfAttack = 0.0 # in degrees s.Pilot = point(0.0, s.altitude, 0.0) s.Nose = s.Pilot + vector(0.0, 0.0, 1.0) s.Up = s.Pilot + vector(0.0, 1.0, 0.0) s.velocity = vector(0.0, 0.0, 1.0).scale(s.airspeed) ### OK. Init the rigid body. # The rigid body is the plane itself - it handles forces # incoming from this object and comptues the plane's new position. s.rigid = rigidBody(s.Pilot, 100, s.velocity) # Add forces to it: s.rigid.addForce(s.thrust) s.rigid.addForce(s.drag) s.rigid.addForce(s.gravity(s.rigid)) s.rigid.addPointForce(s.leftWing, 'left') s.rigid.addPointForce(s.rightWing, 'right') s.rigid.addPointForce(s.elevator, 'tail') s.rigid.addPointForce(s.rudder, 'tail') s.rigid.addPointForce(s.stabilizer, 'tail') s.warning = False # whether or not to flash the warning lamp # Control parameters s.x = 0.0 # The mouse/joystick x coord (-0.5 to 0.5) s.y = 0.0 # Mouse/joystick y coord (-0.5 to 0.5) s.r = 0.0 # Keyboard rudder control (-0.5 or 0.5)
def make_simple_refractor(focal_length, aperture_radius, d): """Refractor with single lens d is thickness of lens """ # TODO: Check whether the value of d gives us a lens consistent with the aperture. source = standard_source(d, aperture_radius) # We'll think of the aperture as just slightly in front of the lens. aperture = CircularAperture(point(0, 0, 0.75 * d), vector(0, 0, -aperture_radius)) sensor = PlanarSensor.of_q_x_y(point(0, 0, -focal_length), -ii, -jj) z_offset = 0. lens = make_lens_basic(focal_length, d, z_offset) elements = Compound([aperture, lens]) return Instrument(source, elements, sensor)
def color(self): return vector(0.5,0.45,0.57)
def init(argc, argv): """ Initialize aspects of the GL scene rendering. """ global trackball, flashlight, vertex_buffer, normal_buffer, color_buffer, colors, vertices, normals, surf, radius, phong_shader, shadow_shader, wireframe # initialize quaternions for the light and trackball flashlight = quat.for_rotation(0.0,vector(1.0,0.0,0.0)) trackball = quat.for_rotation(0.0,vector(1.0,0.0,0.0)) if argc < 2: print("No file specified. Use: python3.3 newview.py <PATH TO FILE> <Number of subdivisions> <flags> ") vertices = [] normals = [] colors = [] shadows = [] else: if argc >= 3: subdivisions = int(argv[2]) else: subdivisions = 1 if argc >= 4: if argv[3] == "-w": wireframe = True filename = argv[1] # read the .OBJ file into VBOs if(filename != None): print("Subdividing " + str(subdivisions) + " times.") surf.load(filename) if subdivisions > 0: for i in range(subdivisions): surf = subdivide(surf) vertices,normals,colors = surf.compile() else: print("No file! \n") vertices = [] normals = [] colors = [] shadows = [] vertex_buffer = glGenBuffers(1) glBindBuffer (GL_ARRAY_BUFFER, vertex_buffer) glBufferData (GL_ARRAY_BUFFER, len(vertices)*4, (c_float*len(vertices))(*vertices), GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer (GL_ARRAY_BUFFER, normal_buffer) glBufferData (GL_ARRAY_BUFFER, len(normals)*4, (c_float*len(normals))(*normals), GL_STATIC_DRAW) color_buffer = glGenBuffers(1) glBindBuffer (GL_ARRAY_BUFFER, color_buffer) glBufferData (GL_ARRAY_BUFFER, len(colors)*4, (c_float*len(colors))(*colors), GL_STATIC_DRAW) radius = surf.radius # set up the object shaders phong_shader = init_shaders('vs-phong-interp.c', 'fs-phong-interp.c') shadow_shader = init_shaders('vs-shadow.c', 'fs-shadow.c') glEnable (GL_DEPTH_TEST)
def draw(): """ Issue GL calls to draw the scene. """ global trackball, flashlight, \ vertex_buffer, normal_buffer, \ colors, color_buffer, selected_face, add_face, \ phong_shader, shadow_shader, wireframe ## TEST SECTION ## # Clear the rendering information. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Clear the transformation stack. glMatrixMode(GL_MODELVIEW) glLoadIdentity() glPushMatrix() # Transform the objects drawn below by a rotation. trackball.glRotate() #glTranslatef(0.0, 0.0, -0.5) # * * * * * * * * * * * * * * * * # Draw all the triangular facets. glUseProgram(phong_shader) h_vertex = glGetAttribLocation(phong_shader, 'vertex') h_normal = glGetAttribLocation(phong_shader,'normal') h_color = glGetAttribLocation(phong_shader,'color') h_eye = glGetUniformLocation(phong_shader,'eye') h_light = glGetUniformLocation(phong_shader,'light') if True: # all the vertex positions glEnableVertexAttribArray(h_vertex) glBindBuffer (GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer(h_vertex, 3, GL_FLOAT, GL_FALSE, 0, None) # all the vertex normals glEnableVertexAttribArray(h_normal) glBindBuffer (GL_ARRAY_BUFFER, normal_buffer) glVertexAttribPointer(h_normal, 3, GL_FLOAT, GL_FALSE, 0, None) # all the face vertex colors glEnableVertexAttribArray(h_color) glBindBuffer (GL_ARRAY_BUFFER, color_buffer) if selected_face and add_face: # paint that face's vertices ORANGE rgb_selected = [0.95,0.2,0.2] # ORANGE #rgb_selected = [1.0, 1.0, 0.0] # BRIGHT YELLOW!! for change in range(9): colors[selected_face.index * 9 + change] = rgb_selected[change % 3] # update the color buffer glBufferData (GL_ARRAY_BUFFER, len(colors)*4, (c_float*len(colors))(*colors), GL_STATIC_DRAW) add_face = False glVertexAttribPointer(h_color, 3, GL_FLOAT, GL_FALSE, 0, None) # position of the flashlight light = flashlight.rotate(vector(0.0,0.0,1.0)); glUniform3fv(h_light, 1, (2.0*radius*light).components()) # position of the viewer's eye eye = trackball.recip().rotate(vector(0.0,0.0,1.0)) glUniform3fv(h_eye, 1, eye.components()) # WIREFRAME MODE if wireframe == True: glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ) glDrawArrays (GL_TRIANGLES, 0, len(surf.triangles) * 3 + 18) glDisableVertexAttribArray(h_vertex) glDisableVertexAttribArray(h_normal) glDisableVertexAttribArray(h_color) # ---- Draw the shadow ---- glUseProgram(shadow_shader) h_vertex = glGetAttribLocation(shadow_shader, 'vertex') h_normal = glGetUniformLocation(shadow_shader, 'normal') h_plane = glGetUniformLocation(shadow_shader, 'plane') h_light = glGetUniformLocation(shadow_shader, 'light') glEnableVertexAttribArray(h_vertex) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer(h_vertex, 3, GL_FLOAT, GL_FALSE, 0, None) # Uniform variables - light, plane, and plane's normal light = flashlight.rotate(vector(0.0,0.0,1.0)); glUniform3fv(h_light, 1, (4.0*light).components()) glUniform3fv(h_plane, 1, [0.0, 0.0, 0.0]) # point on the plane glUniform3fv(h_normal, 1, [0.0, +1.0, 0.0]) # plane's normal vec glDrawArrays(GL_TRIANGLES, 0, len(surf.triangles)*3) glDisableVertexAttribArray(h_vertex) glPopMatrix() #if vertex_buffer == []: #glUseProgram(0) #sierp = sierpinsky(point(0.0, 1.0, 0.0), 0.5, 7) #sierp.draw() # Render the scene. glFlush() glutSwapBuffers()
def draw(): """ Issue GL calls to draw the scene. """ global trackball, flashlight, \ vertex_buffer, normal_buffer, color_buffer, \ shaders, wireframe, mesh # Clear the rendering information. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Clear the transformation stack. glMatrixMode(GL_MODELVIEW) glLoadIdentity() glPushMatrix() # Transform the objects drawn below by a rotation. trackball.glRotate() # * * * * * * * * * * * * * * * * # Draw all the triangular facets. shs = shaders glUseProgram(shs) h_vertex = glGetAttribLocation(shs,'vertex') h_normal = glGetAttribLocation(shs,'normal') h_color = glGetAttribLocation(shs,'color') h_bary = glGetAttribLocation(shs,'bary') h_eye = glGetUniformLocation(shs,'eye') h_light = glGetUniformLocation(shs,'light') h_wires = glGetUniformLocation(shs,'wires') # all the vertex positions glEnableVertexAttribArray(h_vertex) glBindBuffer (GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer(h_vertex, 3, GL_FLOAT, GL_FALSE, 0, None) # all the vertex normals glEnableVertexAttribArray(h_normal) glBindBuffer (GL_ARRAY_BUFFER, normal_buffer) glVertexAttribPointer(h_normal, 3, GL_FLOAT, GL_FALSE, 0, None) # all the face vertex colors glEnableVertexAttribArray(h_color) glBindBuffer (GL_ARRAY_BUFFER, color_buffer) glVertexAttribPointer(h_color, 3, GL_FLOAT, GL_FALSE, 0, None) # all the vertex barycentric labels glEnableVertexAttribArray(h_bary) glBindBuffer (GL_ARRAY_BUFFER, bary_buffer) glVertexAttribPointer(h_bary, 3, GL_FLOAT, GL_FALSE, 0, None) # position of the flashlight light = flashlight.rotate(vector(0.0,1.0,0.0)); glUniform3fv(h_light, 1, (4.0*light).components()) # position of the viewer's eye eye = trackball.recip().rotate(vector(0.0,0.0,1.0)) glUniform3fv(h_eye, 1, eye.components()) # show wireframe? glUniform1i(h_wires, wireframe) glDrawArrays (GL_TRIANGLES, 0, len(mesh.face) * 3) glDisableVertexAttribArray(h_vertex) glDisableVertexAttribArray(h_normal) glDisableVertexAttribArray(h_color) glDisableVertexAttribArray(h_bary) # * * * * * * * * * * * * * * * * # Draw the object's shadow shs = shadowers glUseProgram(shs) h_vertex = glGetAttribLocation(shs,'vertex') h_bary = glGetAttribLocation(shs,'bary') h_normal = glGetUniformLocation(shs,'normal') h_plane = glGetUniformLocation(shs,'plane') h_light = glGetUniformLocation(shs,'light') h_wires = glGetUniformLocation(shs,'wires') # all the vertex positions glEnableVertexAttribArray(h_vertex) glBindBuffer (GL_ARRAY_BUFFER, vertex_buffer) glVertexAttribPointer(h_vertex, 3, GL_FLOAT, GL_FALSE, 0, None) # all the vertex barycentric labels glEnableVertexAttribArray(h_bary) glBindBuffer (GL_ARRAY_BUFFER, bary_buffer) glVertexAttribPointer(h_bary, 3, GL_FLOAT, GL_FALSE, 0, None) # position of the flashlight light = flashlight.rotate(vector(0.0,1.0,0.0)); glUniform3fv(h_light, 1, (4.0*light).components()) # position of the plane glUniform3fv(h_plane, 1, [0.0,-0.50,0.0]) # normal to the plane's surface glUniform3fv(h_normal, 1, [0.0,+1.0,0.0]) # Show as a wireframe? No. # glUniform1i(h_wires, wireframe) glUniform1i(h_wires, 0) glDrawArrays (GL_TRIANGLES, 0, len(mesh.face) * 3) glDisableVertexAttribArray(h_vertex) glDisableVertexAttribArray(h_bary) glPopMatrix() # Render the scene. glFlush() glutSwapBuffers()
from constants import * from airplane import * from hud import * from time import * # global variables width = 512 # window h height = 512 # widow w radius = 1.0 # window "radius" - how large things appear xStart = 0 yStart = 0 trackball = quat.for_rotation(0.0,vector(1.0,0.0,0.0)) land = None vertex_buffer = None horizone_vertex_buffer = None vertices = [] forward = 0.0 right = 0.0 up = 0.0 plane = airplane() phud = hud(plane) # player's HUD mouse_x = 0.0 mouse_y = 0.0 rudder = 0.0
def gravity(s, obj): """ Gets the gravity vector """ return vector(0.0, -(ft2WU(32.2))*obj.M, 0.0)
def as_matrix(self): """ Returns a column major 3x3 rotation matrix for self. """ u = self*quat(0.0,vector(1.0,0.0,0.0))/self v = self*quat(0.0,vector(0.0,1.0,0.0))/self w = self*quat(0.0,vector(0.0,0.0,1.0))/self return [u.vector(),v.vector(),w.vector()]